问题
I am a PHP developer but am transitioning to Java. (very new to Java at this point)
Is there a way to make an ajax call to a Servlet, and respond with the output of a separate .jsp file (as opposed to html or json created directly in the Servlet)?
Here is an example of what is common practice w/ Zend Framework, which is what I would like to do with Java if possible:
public function myAjaxCallAction(){
$this->view->someVar = 'whatever';
$this->view->hello = 'world';
$output = $this->view->render('someViewScript.phtml'); // the above vars are in this view
echo $output;
}
Again very new to java, any advice pertaining to this type of situation would be much appreciated!
回答1:
Just try to load the .jsp that you want. Normally you will use a JSP fragment (.jspf). If you want to load its contents, you can do something like:
Your page:
... content ...
<div id="container"></div>
... content ...
Javascript of the page above (using jQuery):
$(function(){
$( "#container" ).load( "pathToYoutJsp/file.jsp", { someVar: "whatever", hello: "world" } );
});
The JSP that will be loaded will look something like:
... content ...
${param.someVar} foo foo foo ${param.hello}
... content ...
回答2:
Yes, If i get your question correctly then what you want to do is a simple AJAX request to a JSP file and get reaponse. Do it as follows:
In client Javascript:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET","ajaxreq.jsp?query=John", false );
xmlHttp.send();
return xmlHttp.responseText;
//returns the response from server. here it is "Hello John"
In server ajaxreq.jsp :
<%
.. //import required libraries and other application logic
out.print("Hello "+request.getParameter("query"));
..
%>
Hope this helps.
回答3:
Yes you can, by using request.setAttribute before dispatch and then dispatch to your separate page
request.setAttribute("someVa", "whatever");
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/thankYou.jsp");
requestDispatcher.forward(request, response);
See the following link redirect jsp from servlet RequestDispatcher
来源:https://stackoverflow.com/questions/11813643/how-do-you-output-a-view-file-as-an-ajax-response-in-java