Return view string with query parameters from Spri

2019-08-25 07:33发布

This is the effect I'd like but I can't figure-out the syntax:

@RequestMapping(method = RequestMethod.GET, params = { "param1", "param2" }, produces = "text/html")
public String createForm(Model uiModel, @RequestParam("param1") String param1, @RequestParam("param2") String param2, HttpServletRequest request, HttpServletResponse response) throws IOException {
  populateEditForm(uiModel, new Object());
  return "fubar/update?param1=" + param1+ "&param2=" + param2;

}

The error is

javax.servlet.ServletException: Could not resolve view with name 'fubar/update?param1=...

Is there a way to attach query parameters to the return string?

Thanks!

标签: spring-mvc
2条回答
【Aperson】
2楼-- · 2019-08-25 08:17

Looking at the comment you added below your question, it looks like you were trying to FORWARD to a view (ex: JSP). So, yes, no redirects there. And you can either set these parameters on the HTML FORM (like you did). But you could also set these values by adding them to the model. So, in this case, you should definitely be using the first ModelAndView contructor parameter to specify the view to forward to [without the "redirect" part] and use the second parameter to pass the model parameters.

This is something that happens a lot when converting older Struts applications to Spring applications. In struts, it "looks like" you can add request/URL parameters in funny ways. When in reality, once you received the inboud HTTP request, it makes no sense to add things to the URL parameters. You'd just want to add new values to your "Request processing" logic (add parameters to the MODEL). If you really need to add parameters to a URL, it's only if you want to create a new request (mostly a redirect to another page). And in that case, the other answer is on the correct path but you want to add the URL parameters to the "redirect:" String (in the FIRST parameter of the ModelAndView constructor):

return new ModelAndView("redirect:fubar/update?param1=" + param1+ "&param2=" + param2);

Of course, that's if you want to do a redirect (HTTP 302) to another page.

查看更多
够拽才男人
3楼-- · 2019-08-25 08:39

I used two controllers to render a view having a query param in it's address bar:

@GetMapping("/requesting-path")
public String backToApp(Model model) {
    return "redirect:/shown-in-addressbar-path?paramKey=paramValue";
}

@GetMapping("/shown-in-addressbar-path")
public String backToApp(Model model) {
    return "/view-id";
}
查看更多
登录 后发表回答