I am trying to forward my request from a Spring-MVC controller method - to a JSP page.
My controller method is supposed to handle an Ajax request. By forwarding the request to the JSP file, I want the response to the Ajax request to be the (dynamic) HTML output of the JSP file.
What I have tried:
public ModelAndView ajaxResponse(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("command", "hello world");
request.getRequestDispatcher("jspfile").forward(request, response);
return null;
}
This fails and I get "HTTP Status 404"
"jspfiles" is defined in a tiles config file to be directed to the actual jsp file. When I run the following method:
public String ajaxResponse(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("command", "hello world");
return "jspfile";
}
... I get the content of the file as my Ajax response - but JSP tags in that file are not parsed) - hence I conclude that my tiles definition is correct (???).
My JSP file looks like this:
<%=command%>
So I want to get as my Ajax response the string "hello world".
Could you show me an example code of how to achieve my purpose?
Specifically I need to know:
What should be the controller method return type?
What should be the controller method actual return value (if it matters)?
How should I set the jsp file path in the request.getRequestDispatcher(...) so it would be recognized?
Have a look at the controller example here:
http://maestric.com/doc/java/spring/mvc
It's a bit out of date, but the concept of what you must do remains the same. Spring 3 has annotation-based ways to do a lot of what is in that example.
Related
I have a line of code that looks like this:
req.getRequestDispatcher(page).forward(req, resp);
Where req and resp are HttpServletRequest and HttpServletResponse objects respectively, and page is a String. I want the above line of code to forward the request and response to the current resource used by req. So, if it's currently using index.jsp, I want the String page to have a value of index.jsp, if I am currently at WEB-INF/view/main.jsp, I want page to be WEB-INF/view/main.jsp. I've skimmed through documentation on ServletRequest, ServletResponse, ServletContext and RequestDispatcher, but havn't found what I am looking for, is there any method to get the path to the .jsp file of the page?
I have this two controller from two separate projects lets name them:
project1.controller1
project2.controller1
Obviously these are two Spring controllers from different projects.What I want is to make project1.controller1 a gateway all request will be sent here. And will process the request if it will go to project2.controller1 or a new controller.
Some pseudoCode:
#Controller
public class someClassFromProject1{
#RequestMapping(value="/controller1", method=RequestMethod.POST)
public String smsCatcher(String target, HttpServletRequest request,
HttpServletResponse response){
//some processing, converting request to string, etc
if("someStringThatIsPartOfTheRequest".equals("someString"))
//carry request and forward it to project2.controller1
else
//go to another external controller
}
}
And in project2.controller 1 will look something like this:
#Controller
public class someClassFromProject2{
#RequestMapping(value="/controller1", method=RequestMethod.POST)
public String smsCatcher(String target, HttpServletRequest request,
HttpServletResponse response){
//processing
}
}
I've already tried return "forward:/someUrl"; and return "redirect:someUrl";. It didn't work and it didn't reach project2.controller1. So any ideas on this one?
Edit: Forgot to add this one, different project means different WAR but deployed on the same sever. And the request should be carried over from project1.controller1 to project2.controller1 because I'm gonna process the request there.
Thanks!
You need to use redirect instead of forward.
The protocol is required if the host is different to that of the current host
return "redirect:http://www.yahoo.com";
Have a look at the redirect: prefix section from Spring Web MVC framework also check this
A logical view name such as redirect:/myapp/some/resource will
redirect relative to the current Servlet context, while a name such as
redirect:http://myhost.com/some/arbitrary/path will redirect to an
absolute URL.
Figured it out but then it's kind of messy, I've used HttpClient to Post my Request to the URL. It also carried the request along with the forwarding. Anyway, thanks for all the help guys. Thanks :)
I'm new to jquery and SpringMVC. I'm using jquery to submit a request after a user clicks a href. After the server processes the request, a modal popup is displayed with the details from the server.
$.post(taskSrchURL, function(data) {
$('#popupmodal').modal('show');
});
Here is the Controller:
#RequestMapping(value = "/api/task/{id}", method =
{RequestMethod.POST})
public ModelAndView searchDetails(#PathVariable("id") String
id,
HttpServletRequest request, HttpServletResponse response)
throws SearchException, ApplicationException {
Details details = service.getDetails(id, request, response);
prepareResponse(request, response, taskDetails);
ModelAndView modelAndView = new ModelAndView("details ");
modelAndView.addObject("details ", details);
return modelAndView;
I'm expecting to have access to the "details" object when the response returns, however, I'm not sure how to access it. I'm expecting to be able to use jstl tags to reference the data as it is complex and needs to be dispalyed on several tabs.
However,
<c:out value="${details.id}"/>
does not work. I have seen a lot examples that set the 'data' from the ModalAndView to the html element of a div, but I don't want to do that.
Is there a way to do this?
Thanks in advance!
You basically have 2 choices:
Client-side rendering:
If the data you need from the server can be inserted into your page with javascript without too much hassle, you should return it as JSON from your Controller method using #ResponseBody. Convertion to JSON can be done by Jackson automatically.
You could then use an existing Javascript template engine library to render your data to html on the clients browser and insert it into the page or just insert it manually (for example with jQuery).
Server-side rendering:
If you want to render the part of the page with the data on the server-side to then send the ready-made part of your page back to the client, you need a template engine which allows you to render your templates anytime anywhere (in your controller method in this case). You could then send the html String back again as JSON using #ResponseBody and insert it into the page.
I don't think JSP/JSTL can do this (or it is very difficult/hacky). I recommend FreeMarker instead.
You could still use JSP/JSTL for your "complete" pages, and FreeMarker for the parts. FreeMarker is not too different from JSP/JSTL, so you could probably translate the part of your page without too much problems.
Besides my comment, I would highly recommend using the #ResponseBody annotation instead of using ModelAndView
Be sure to have jackson-databind on your classpath, this will cause Spring to automatically serialize your POJO into JSON, which can be directly used as Javascript objects in the ajax callback function
See a quick tutorial here:
http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program
This approach decouples the Application Server from your view, thus liberating you from having to rely on JSTL templating and you can choose a front-end workflow that is intuitive for you (checkout AngularJS).
I am using Liferay and Spring MVC and I want to redirect to another portlet and pass it a parameter, but when I try to set render parameters I get this error:
15:20:24,859 ERROR [portal-web.docroot.html.portal.render_portlet_jsp] (http-foo-10.23.243.3-8080-7) java.lang.IllegalStateException: Set render parameter has already been called
at com.liferay.portlet.ActionResponseImpl.sendRedirect(ActionResponseImpl.java:48)
at sk.foo.showcasePortlet.ShowcaseController.redirect(ShowcaseController.java:65)
The showcaseController's method which is being resolved contains just the assignement and the redirect:
#ActionMapping(params = { "action=redirect" })
public void redirect(ActionRequest request, ActionResponse response)
throws IOException {
response.setRenderParameter("path", request.getParameter("path"));
response.sendRedirect("/path/to/portlet");
}
Why can't I assign that parameter? When I remove the line the redirection works, but the problem is that the portlet which the user is being redirected to expects a string parameter "path":
#RenderMapping
public String barBaz(RenderRequest request, #RequestParam String path){
// ...
return "some/jsp";
}
How can I pass the parameter to the barBaz method in another portlet, please?
You exception says this IllegalStateException: Set render parameter has already been called
Be aware that this interceptor is calling setRenderParameter on the ActionResponse, which means that you cannot call sendRedirect in your handler when using this interceptor. If you need to do external redirects then you will either need to forward the mapping parameter manually or write a different interceptor to handle this for you
DOC
Is it possible to setup error-page but that should be triggered not for all URI's but for example with /custom-path, and for requests with URI's /main-path do not handle errors?
In web.xml i suppose it is only possible to match error page with certain Exception types.
The problem is we have one single war file inside which we have both rest api and html management UI. So if error comes from rest api, it should be rendered as it is and no error page should be displayed.
I had the same problem and I solved it by calling setStatus() on HttpServletResponse instead of throwing exceptions or calling sendError().
Example of my Spring MVC controller:
#RequestMapping(value = "/{ean}", method = RequestMethod.GET)
#ResponseBody
public User getUser(#PathVariable("id" Long id, HttpServletResponse response) {
// response.sendError(HttpServletResponse.SC_NOT_FOUND)
response.setStatus(HttpServletResponse.SC_NOT_FOUND)
}
This way my RESTful API controllers don't render error pages.