Forward request to spring controller

空扰寡人 提交于 2021-02-10 16:00:50

问题


From a servlet , I am forwarding the request to a spring controller like below

RequestDispatcher rd = request.getRequestDispatcher("/myController/test?reqParam=value");
rd.forward(request, response);

In order to pass a parameter to the spring controller , I am passing it as request parameter in the forward URL.

Is there a better way of doing this ?

Instead of passing in request parameter , can I pass as a method parameter to the spring controller during forward ?


回答1:


This will be called when /myController/test?reqParam=value is requested:

@RequestMapping("/myController/test")
public String myMethod(@RequestParam("reqParam") String reqParamValue) {
  return "forward:/someOtherUrl?reqParam="+reqParamValue;  //forward request to another controller with the param and value
}

Or you can alternatively do:

@RequestMapping("/myController/test")
public String myMethod(@RequestParam("reqParam") String reqParamValue,
                       HttpServletRequest request) {
  request.setAttribute("reqParam", reqParamValue);
  return "forward:/someOtherUrl"; 
}



回答2:


you can use path variable such as follow without need to use query string parameter:

@RequestMapping(value="/mapping/parameter/{reqParam}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String reqParam) {
    //Perform logic with reqParam
}


来源:https://stackoverflow.com/questions/42465091/forward-request-to-spring-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!