SpringMVC Method Four Types of Return Values Summary of How many have you used

  • 2021-07-24 10:56:57
  • OfStack

SpringMVC is now a basic framework in the field of Java, which many people use every day, but are you fully aware of the return value of SpringMVC method? Today, Song Ge will talk with you about 4 different types of return values in SpringMVC to see if get has reached your knowledge blind spot.

1. ModelAndView

In the past, ModelAndView should be the most common return value type without separation of front and back ends. Now, after separation of front and back ends, the back end mainly returns JSON data. It is easy to understand that the back end returns ModelAndView. The developer can specify the view name in the ModelAndView object, and then bind the data, as follows:


@RequestMapping("/book")
public ModelAndView getAllBook() {
  ModelAndView mv = new ModelAndView();
  List<Book> books = new ArrayList<>();
  Book b1 = new Book();
  b1.setId(1);
  b1.setName("3 Romance of the Kingdom ");
  b1.setAuthor(" Luo Guanzhong ");
  books.add(b1);
  Book b2 = new Book();
  b2.setId(2);
  b2.setName(" Dream of Red Mansions ");
  b2.setAuthor(" Cao Xueqin ");
  books.add(b2);
  // Specify the data model 
  mv.addObject("bs", books);
  mv.setViewName("book");// Specify the view name 
  return mv;
}

Returning ModelAndView, the two most common operations are specifying the data model + specifying the view name.

2. Void

When the return value is void, it may be that you really have no value to return, or you have other methods. Song Ge classifies it into the following four categories. Let's take a look.

2.1 No value

If there is no return value, void is returned, but 1 must be noted that at this point, the @ ResponseBody annotation needs to be added to the method, like this:


@RequestMapping("/test2")
@ResponseBody
public void test2(){
  // Your code 
}

2.2 Redirection

Because the methods in SpringMVC all have HttpServletResponse parameters by default, you can regain the skills in Servlet/Jsp and realize redirection by manually setting the response header as follows:


@RequestMapping("/test1")
@ResponseBody
public void test1(HttpServletResponse resp){
  resp.setStatus(302);
  resp.addHeader("Location","/aa/index");
}

You can also call the redirected method directly as follows:


@RequestMapping("/test1")
@ResponseBody
public void test1(HttpServletResponse resp){
  resp.sendRedirect("/aa/index");
}

Of course, no matter how you write redirection, it is a knowledge point in Servlet/Jsp, and the above two ways of writing are equivalent to returning to ancient times.

2.3 Server Jump

Since you can redirect, of course, you can also jump on the server side, like the following:


@GetMapping("/test5")
public void test5(HttpServletRequest req,HttpServletResponse resp) {
  req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req,resp);
}

2.4 Return String

Of course, HttpServletResponse can also be used to return other string data, including but not limited to JSON, as follows:


@RequestMapping("/test2")
@ResponseBody
public void test2(HttpServletResponse resp) throws IOException {
  resp.setContentType("application/json;charset=utf-8");
  PrintWriter out = resp.getWriter();
  List<Book> books = new ArrayList<>();
  Book b1 = new Book();
  b1.setId(1);
  b1.setName("3 Romance of the Kingdom ");
  b1.setAuthor(" Luo Guanzhong ");
  books.add(b1);
  Book b2 = new Book();
  b2.setId(2);
  b2.setName(" Dream of Red Mansions ");
  b2.setAuthor(" Cao Xueqin ");
  books.add(b2);
  String s = new Gson().toJson(books);
  out.write(s);
  out.flush();
  out.close();
}

This is the case when the return value is void, and the return value of the method is void. If it is not 1, it will really not be returned. There may be other ways to give the front-end data.

3. String

There are several different situations when the return value of the SpringMVC method is of type String.

3.1 Logical View Name

The most common way to return String is the logical view name. In this case, the default parameter Model is used to pass data, as follows:


@RequestMapping("/hello")
public String aaa(Model model) {
  model.addAttribute("username", " Zhang 3");
  return "hello";
}

At this time, the returned hello is the logical view name, and the data to be carried is placed in model.

3.2 Redirection

It can also be redirected. In fact, if there is a need for redirection in SpringMVC, 1 generally adopts this method:


@RequestMapping("/test4")
public String test4() {
  return "redirect:/aa/index";
}

3.3 forward Forwarding

It can also be forwarded by forward. In fact, if there is a need for forward forwarding in SpringMVC, 1 generally adopts this method:


@RequestMapping("/test3")
public String test3() {
  return "forward:/WEB-INF/jsp/order.jsp";
}

3.4 Really String

Of course, there is also a situation where you really want to return an String. In this case, you only need to add @ ResponseBody annotation to the method, or Controller itself adds a combination annotation @ RestController, like the following:


@RestController
public class HelloController {
  @GetMapping("/hello")
  public String hello() {
    return "hello provider!";
  }
}

It can also look like this:


@RequestMapping("/test2")
@ResponseBody
public void test2(){
  // Your code 
}
0

These are several cases where the return value is String.

4. JSON

Returning JSON is the most common, Under the trend of separation of front and rear ends, Most backends only need to return JSON, Then the common List collection, Map, entity class, etc. can be returned, and these data are automatically changed from HttpMessageConverter to JSON. If you use Jackson or Gson, you can automatically return JSON without additional configuration, because the framework provides us with the corresponding HttpMessageConverter. If you use Fastjson of Alibaba, you need to manually provide an instance of the corresponding HttpMessageConverter. The return value of the method is as follows:


@RequestMapping("/test2")
@ResponseBody
public void test2(){
  // Your code 
}
1

Summarize

Ok, this is the four different types of return values of SpringMVC method summarized by Song Ge for everyone, but it is not difficult! If you have any questions, please leave a message for discussion.


Related articles: