I have the above js and JSP code, I want to invoke procedureCall() while clicking on ok button on confirm window poopup (inside "if" statement). Is it possible and if yes, how it can be done?
<script type="text/javascript">
function confirmDelete() {
var answer = confirm("Are you sure you want to delete");
if (answer == true) {
return true;
} else {
return false;
}
}
</script>
JSP piece:
<%! public void procedureCall(int cId) {
String procedureCall = "{call NEW_PORTING_PRC.delete_album_metadata(cId)}";
try (CallableStatement cal = conn.prepareCall(procedureCall);) {
} catch (Exception e) {
e.printStackTrace();
}
%>
javascript runs in your browser, your java code is deployed in your container(Tomcat).
So only way to invoke this is via a Web call. Your javascript should invoke an ajax call to one servlet(configured in web.xml) and this servlet should invoke your java method.
like from JS you write as
$.get('URLofServlet');
OR
what you can try is submit the JSp with some parameters and reloading the JSP..
if (answer == true)
{
document.getElementById("param1").value='paramvalue';
document.getElementById("myForm").action='yourJspPath.jsp';
document.getElementById("myForm").submit();
}
Also I assume id and name will both be 'param1' for simplicity..
and in scriptlet you can do like
<%
if(request.getParamter("param1")=='paramvalue'){procedureCall();}
%>
Just to add I will recommend to remove scriplets and use ajax as in first approach.
Use form submission or ajax request or framework action to go back end and process the things needed for you.In your approach its not possible I think.
And please dont use scriplets in jsp,its not a good practice.
Related
I try my best to describe my situation.
My wicket site contains list wicket component, where every list element has another list. Each element in lowest level list has ajax wicket link to download some file. All this works fine. I used to this AjaxBehaviour. Method startDownload of this behaviour is invoked within link onClick method.
public void startDownload(AjaxRequestTarget target) {
target.appendJavaScript("window.location.href='" + getCallbackUrl() +"'");
}
Method onRequest of this behaviour is:
#Override
public void onRequest() {
IRequestHandler fileTarget = new IRequestHandler() {
#Override
public void respond(IRequestCycle requestCycle) {
if (null != file) {
try {
FileInputStream inputStream = new FileInputStream(file);
WebResponse resp = (WebResponse) requestCycle.getResponse();
resp.setAttachmentHeader(fileName);
String contentType = FileUtils.getFileType(fileName);
if (contentType != null) {
resp.setContentType(contentType);
}
resp.setHeader("Pragma", "anytextexeptno-cache");
resp.setHeader("Cache-Control", "max-age=0");
Streams.copy(inputStream, requestCycle.getResponse().getOutputStream());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
Now i need to reload model and refresh some components in the page after download file action. I tried to add entire page to the AjaxRequestTarget in method onclick, after code invoked startDownload method. Reload page works fine but window with file to download doesn`t show.
I think that i have to do reload page in other, separate request (maybe i'm mistaken? ), because in this request i call 'window.location.href=....', but i don`t know how i can to enforce second request to reload page.
Does have someone some ideas what I do wrong ? And how can I resolve my problem ?
Seems you need something like this:
https://cwiki.apache.org/confluence/display/WICKET/AJAX+update+and+file+download+in+one+blow
It seems that my implementation is simmilar to this from cwiki.apache.org website. In onRequest method i used getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler), and despite of this doesn`t work.
Is possible that reason of this is component, which cause request is added to target (because i add to target entire page and component - ajaxLink in this example, is child of this page)
I'm working with jsp and I have two conditions for redirect to some page, this is my code
<%
if(traer.getFormapacretro().equals("RELACIONESLABORALES")&&tarea.getEstado()==4)
{
System.out.println("::::::::::::::::RELACIONES"+tarea.getEstado()+"LABORALES:::::::::::::::::::::");
response.sendRedirect("/html/controltareas/viewpacrl.jsp");
}
else if(traer.getFormapacretro().equals("CAPACITACION")&&tarea.getEstado()==4)
{
System.out.println("::::::::::::::::CAPACITACION"+tarea.getEstado()+":::::::::::::::::::::");
response.sendRedirect("/html/controltareas/viewpaccapacita.jsp");
}
%>
But when the form is loaded it only shows results on the console but not redirect to the page in the condition, some help?
You have to always use return; when you are using
response.sendRedirect("");
Your code should look like this
<%
if(traer.getFormapacretro().equals("RELACIONESLABORALES")&&tarea.getEstado()==4)
{
System.out.println("::::::::::::::::RELACIONES"+tarea.getEstado()+"LABORALES:::::::::::::::::::::");
response.sendRedirect("/html/controltareas/viewpacrl.jsp");
return;
}
else if(traer.getFormapacretro().equals("CAPACITACION")&&tarea.getEstado()==4)
{
System.out.println("::::::::::::::::CAPACITACION"+tarea.getEstado()+":::::::::::::::::::::");
response.sendRedirect("/html/controltareas/viewpaccapacita.jsp");
return;
}
%>
I am creating a jsp application in Netbeans Ide. I am having problems in calling a java class method in ajax.Is it possible to do so
My java class is something like this:
public class Hello
{
public String execute(String s)
{
return "success";
}
}
I am not able to figure out how to call the execute method using ajax :
My current ajax code is:
var val="test string";
$.ajax({
type: "GET",
url: "http://localhost:8084/Shade/src/java/mail/Main.execute",
data: val,
async: true,
cache: false,
success: function (msg) {
alert("hi");
$(".col-1").html(msg);
});
Thanx in advance :)
AJAX is an acronym for Asynchronous JavaScript And XML. It provides an ability to communicate with the server asynchronously.
To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
So, you can not access Java Class directly as url to make your Ajax request. It should any mapped url like JSP, Servlets, PHP etc.
Create a JSP (e.g. hello.jsp)
<%
String strResponse;
mail.Main objMain = new mail.Main();
strResponse = objMain.execute();
%>
<%=strResponse %>
In Ajax request
url: "hello.jsp",
EDIT: Added Example:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function getData() {
var dataToBeSent = {
uName : $("#userName").val() , //
passwd: $("#password").val()
}; // you can change parameter name
$.ajax({
url : 'getDataServlet', // Your Servlet mapping or JSP(not suggested)
data :dataToBeSent,
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
In Servlet/JSP access your parameters request.getParameter("uName");
You cannot call the method directly. You should map an URL to the method you want to call.
This can be done in a servlet. If you're already serving pages through your Java code, you just add a new method to serve a page with the content you want.
I'm quite new to JSP/Liferay portlet development and I'm trying to add a progress bar using jQuery, I found this question but wasn't very specific to how it will be done using AJAX.
I was wondering if anyone can point me in the right direction to help me get started.
thanks.
EDIT:
I used JSON simple, and manage to make some changes but I am getting a bad request(error code 400 when using fire bug) and a 404 not found on my JS
below is my code:
public void processAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
//some code here
this.generateJSON(actionRequest, actionResponse);//manual call the method?
public void generateJSON(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
try{
//just want to see a progress bar so do static for now...
JSONObject obj=new JSONObject();
obj.put("percent",new Integer(30));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
}catch(Exception ex){
System.out.print(ex);
}
}
}//end of class
JS here
function checkStatus(){
$.ajax({
type: 'POST',
//url: '<%=request.getContextPath()%>/checkStatusServlet',
url: '<%=request.getContextPath()%>/generateJSON',
dataType: 'json',
success: function( data )
{
alert(data.statusPercent);
var statusPercent = data.percent;
//Update your jQuery progress bar
$( "#progressbar" ).progressbar({value: statusPercent});
}
});
//below works and alert is being called...
/*for (i=0;i<=5;i++)
{
$( "#progressbar" ).progressbar({value: i+10});
}
alert('got here');
*/
}
HTML/JSP
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects/>
<portlet:renderURL var="resourceUrl"></portlet:renderURL>
<!-- Javascript files -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/main.js"></script>
<!-- end of Java script files -->
<script type="text/javascript">
setTimeout('checkStatus()',1000);
</script>
<div id="progressbar"></div>
You can't generate JSON in processAction. This method is meant to change the portlet state, but not generate output. The portal-way to accomplish what you need it to use the serveResource method/lifecycle-phase: you get the URL for this from the portal ( < portlet:resourceURL / >). Specifically you shouldn't create them yourself.
An alternative (but not the portal way) is to use a servlet - but in this you don't have the portlet state that you might need.
And you might want to use < portlet:namespace / > to disambiguate your global names - or use proper namespacing - because you can never say how many times your portlet will be placed on a page.
(added spaces to jsp-tags so that they don't get eaten by markup)
Short: Read about resource-serving for portlets, this will most likely solve your underlying problem: With the code you give above you won't be able to access your JSON at all - no matter what you do on the JS side.
The answer really depends on your specific needs. Are you trying to display how much time is actually left for some task, or how much time till a page loads or what?
You could poll from the client and update the progress bar in the browser depending on how much is left to process. A simple jQuery ajax example:
function checkStatus
{
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/checkStatusServlet',
dataType: 'json',
success: function( data )
{
var statusPercent = data.statusPercent;
//Update your jQuery progress bar
$( "#progressbar" ).progressbar({value: statusPercent });
}
});
}
Then you can simply poll this function till its done
setTimeout('checkStatus()' 1000);
Of course you will also need to construct a servlet or struts action or portlet to handle the processing on the server, and return the appropriate status for the task.
EDIT:
Use the JSON library
From your servlet or action. (code below is from struts2 action)
public String checkStatus()
{
try
{
Integer percentDone = 50; //Calculate how much time is left
JSONObject statusResult = new JSONObject();
statusResult.put("statusPercent", percentDone);
//Obtain HttpServletResponse..
//implementation depends on your framework.
//PortletResponse should work too.
PrintWriter out = this.response.getWriter();
out.write( statusResult.toString(4) );
out.flush();
out.close();
}
catch (IOException e) {}
catch (JSONException e) {}
return null;
}
Hi I have the followig code:
page1.jsp
The ajax function called on click of button
function ajaxFunction()
{
var xmlHttp;
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
alert("Data loaded");
}
}
xmlHttp.open("GET","page2.jsp",true);
xmlHttp.send(null);
}
page2.jsp
<%# page import="javax.jms.*" %>
<%!
private QPublisher qPublisher = null;
public class QPublisher {
private TopicPublisher publisher = null;
private TopicSession session = null;
public void configPublisher(){
TopicConnectionFactory factory = null;
TopicConnection connection = null;
try {
factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory("tcp");
connection = factory.createTopicConnection("user","pwd");
session = connection.createTopicSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
javax.jms.Topic topic = session.createTopic("topic1");
publisher = session.createPublisher(topic);
}
}
public void publish(String msg)
{
javax.jms.TextMessage message = session.createTextMessage();
message.setText(msg);
publisher.publish(message);
}
}
public void jspInit(){
qPublisher = new QPublisher();
qPublisher.configPublisher();
}
%>
<%
qPublisher.publish("This is a test for TT");
%>
If I call page2.jsp without using ajax, i.e from page1.jsp using
<form action="page2.jsp">
the message is picked by the subsciber and displayed.
but not by making an ajax..
I have basic idea of ajax, so please guide what am i missing?
I know this isn't really an answer to your question, but if you're not too coupled to using strict JSP and JMS you may want to investigate frameworks that do the plumbing for you.
For example, this is a video of a presentation on How using Grails to build twitter in 40 minutes. The presentation is by Graeme Rocher [twitter] - CTO of G2One, now owned by Spring Source. In the presentation, Graeme creates a fully functional, AJAX enabled, searchable, secure, JMS based twitter clone.
I'm sure there are similar examples for other web frameworks.
Like someone once said - "Don't reinvent the wheel, unless you're really interested in learning alot of low-level detail about wheels"
Are you sure that the Ajax code successfully invokes the page2.jsp? To verify this, you could simply replace the JMS related code with something more simple, just a JSP command which shows "Hello World" in the client.