问题
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