Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from HttpServletRequest with spring mvc

I am new to Spring MVC.

What I want to achieve is to add a map of data into HttpServletRequest; Example:

private NewRequestService newRequest = new NewRequestService();

public ModelAndView inputRequiredInfo(@ModelAttribute("requestForm") HttpServletRequest request) {
  request.setAttribute("mylist", newRequest.loadAllUserDomainType());

  return new ModelAndView("request/selectDomainUser","requestForm", request);

}

And then in the view jsp file, I want to get those data which pass into the request and put it into dropdown list.

like image 365
H.dev.guy Avatar asked Sep 09 '13 02:09

H.dev.guy


1 Answers

Forget what you've done right now.

There are two ways from a @Controller handler methods to make attributes available to a JSP.

  1. Make your method accept an HttpServletRequest parameter and set the target object as a request attribute directly.
  2. Make your method accept a Model, ModelMap, ModelAndView, or Map parameter and set the target object as a request attribute on that Model argument. You can also make your method return any of the above.

For 2., Spring will take the elements you added to the Model and put them into the HttpServletRequest attributes. They will then be available while rendering the JSP.

Let's have some examples:

Return a ModelAndView with one attribute

public ModelAndView inputRequiredInfo() {
    Map map = newRequest.loadAllUserDomainType();

    return new ModelAndView("request/selectDomainUser","mylist", map);
}

Return a ModelAndView with no attributes, but add the attribute directly to HttpServletRequest

public ModelAndView inputRequiredInfo(HttpServletRequest request) {
    Map map = newRequest.loadAllUserDomainType();
    request.setAttribute("mylist", map);
    return new ModelAndView("request/selectDomainUser");
}

Return a String view name but add attributes to a Model passed as argument

public String inputRequiredInfo(Model model) {
    Map map = newRequest.loadAllUserDomainType();
    model.addAttribute("mylist", map);
    return "request/selectDomainUser";
}

In the above example, you could have passed Model, ModelMap, or java.util.Map.

Same but with HttpServletRequest

public String inputRequiredInfo(HttpServletRequest request) {
    Map map = newRequest.loadAllUserDomainType();
    request.setAttribute("mylist", map);
    return "request/selectDomainUser";
}

For a more complete list of accepted method arguments, see section 17.3.3 of the official documentation. While you are at it, also read the supported return types to understand the difference between returning a ModelAndView and returning a String.

like image 188
Sotirios Delimanolis Avatar answered Oct 16 '22 14:10

Sotirios Delimanolis