Several return types of controller in springMVC

  • 2021-08-31 07:47:48
  • OfStack

The return value of the Controller method can be of the following types:

1. Return ModelAndView

One of the most common return results when returning ModelAndView. You need to define an ModelAndView object at the end of the method, and set Model and View separately.

2. Return String

1): The string represents the logical view name

Real access path = "prefix" + logical view name + "suffix"

Note: If the returned String represents the logical view name, then Model is returned as follows:


public String testController(Model model){
model.addAttribute(attrName,attrValue);// Equivalent to ModelAndView Adj. addObject Method 
return " Logical view name ";
 }

2): Represents redirect redirection

The characteristics of redirect are similar to those of servlet1. If redirect is used for redirection, URL in the address bar will change, and request of the previous time will not be carried at the same time

Case:


public String testController(Model model){
 return "redirect:path";//path Represents the address of the redirection 
 }

3): Represents forward forwarding

Forwarding through forward, the URL in the address bar will not change, and the last request will be carried to the Write 1 request

Case:


 public String testController(Model model){
 return "forward:path";//path Represents the forwarded address 
 }

3. Return void

When this result is returned, the HTTPServletRequest and HTTPServletResponse objects can be defined in the formal parameters of the Controller method to receive and respond to the request

1) Forward pages using request


request.getRequestDispatcher(" Forwarding path ").forward(request,response);

2) Page redirection using response


response.sendRedirect(" Redirect path ");

3) You can also specify response results using response


response.setCharacterEncoding("UTF-8"); 
response.setContentType("application/json;charset=utf-8"); 
 response.getWriter.write("json String "); 

There is no difference between important and unimportant return values above. Generally speaking, they will all be used, but sometimes there will be some subtle differences in the way they are used

Added: In SpringMvc, various implementations of Controller methods (specifying which page to return to, specifying the data to return to the page)

1) ModelAndView


@RequestMapping("/list")
 public ModelAndView itemsList() throws Exception{  
 List<Items> list = itmesService.list();
 // Create ModelAndView View 
 ModelAndView modelAndView = new ModelAndView();
 // Will list Add data to the attempt 
 modelAndView.addObject("itemList", list);
 modelAndView.setViewName("itemList");// Set the name of the view, that is, which page to return to 
 // Because of the role of view parser, prefixes and suffixes are omitted, and the pages visited are ( "/WEB-INF/jsp/itemList.jsp" ) 
 return modelAndView;
 }
 

2) String (most commonly used, most convenient, recommended)


@RequestMapping("/itemEdit/{id}")
 public String itemEdit(@PathVariable("id") Integer id, HttpServletRequest reuqest, 
  Model model) throws Exception{
 
 //String idStr = reuqest.getParameter("id");
 Items items = itmesService.findItemsById(id);
 // Will items Add data to the view 
 model.addAttribute("item", items);
 
 // Back here editItem , in @Controller Under the annotation of, the prefix and suffix are automatically added back, but it is actually returned to the page ("/WEB-INF/jsp/editItem.jsp")
 return "editItem";
 }

3) Returns void


public void update(Items items,HttpServletRequest request,HttpServletResponse response)throws Exception{
 // Returns data, setting the items The contents of the items In, jsp Page invocation items Just do it 
 request.setAttribute("items", items);
 // Return to the specified page 
 // If it is void Type, you will not call the SpringMvc Therefore, the view parser cannot be loaded automatically, so the jump 
 // The page name should be its full path name 
 request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
 }
 You won't call SpringMvc Therefore, the view parser cannot be loaded automatically, so the jump 
 // The page name should be its full path name 
 request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
 }

4) Definition of parameters required in the method

For the example in 3), I defined in the update method:

Items items, HttpServletRequest request and HttpServletResponse response.

But you can find that in fact, I didn't use response in the method, so I can delete it. For the program, it won't

Have an impact.

Therefore, when you define methods, you can define the required classes according to your actual needs, or if you are afraid that the code needs to be changed in the future,

All definitions are ok.

Update

5) If you want the interface to return data instead of jumping pages, you need to add an annotation for @ ResponseBody

Example:


@RequestMapping("atimynyc/getUser")
@ResponseBody
public User getUser(String id){
  User user = new User();
  user.setUserName = "Atimynyc";
  user.setUserAge = 18;
  user.setUserPhone = "123456789";
  return User;
}

By adding ResponseBody, springmvc knows that this interface returns data. For example, when we call the above interface url with ajax, atimynyc/getUser can get the object user.


Related articles: