SpringMVC is now a basic framework in the Java world. Many people use SpringMVC every day, but do you fully understand the return value of SpringMVC methods? Today Songo is going to talk to you about the four different types of return values in SpringMVC and see if you can get your knowledge blind spots.

1. ModelAndView

ModelAndView should have been the most common return value type when the front and back end were separated. Now, after the front and back end are separated, the back end returns JSON data mainly. The back end returns ModelAndView, which is easier to understand. The developer can specify the view name in the ModelAndView object, and can also bind the data, as follows:

@RequestMapping("/book")
public ModelAndView getAllBook(a) {
    ModelAndView mv = new ModelAndView();
    List<Book> books = new ArrayList<>();
    Book b1 = new Book();
    b1.setId(1);
    b1.setName(Romance of The Three Kingdoms);
    b1.setAuthor("Luo Guanzhong");
    books.add(b1);
    Book b2 = new Book();
    b2.setId(2);
    b2.setName(A 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;
}
Copy the code

To return ModelAndView, the two most common operations are to specify the data model + specify the view name.

2. Void

When you return void, either you really don’t have a value to return, or you have another way to do it, Songo categorized it into four categories, so let’s see.

2.1 no value

If no value is returned, void is returned, but be sure to add the @responseBody annotation to the method as follows:

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

2.2 the redirection

Since methods in SpringMVC have the HttpServletResponse parameter by default, you can pick up the skills in servlets/JSPS and implement 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");
}
Copy the code

You can also call the redirection method directly as follows:

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

Of course, redirection, however you write it, is the stuff of Servlet/Jsp, and both of the above are a throwback to ancient times.

2.3 Server Redirect

If you can redirect, you can also redirect on the server side, as follows:

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

2.4 Returned String

You can also use HttpServletResponse 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(Romance of The Three Kingdoms);
    b1.setAuthor("Luo Guanzhong");
    books.add(b1);
    Book b2 = new Book();
    b2.setId(2);
    b2.setName(A Dream of Red Mansions);
    b2.setAuthor("Cao Xueqin");
    books.add(b2);
    String s = new Gson().toJson(books);
    out.write(s);
    out.flush();
    out.close();
}
Copy the code

This is the case when the method returns void, and if the method returns void, it doesn’t necessarily mean it doesn’t return, there might be other ways to give data to the front end.

3. String

There are several different situations when a SpringMVC method returns a String value.

3.1 Logical View name

Return String The most common is the logical view name, in which case the default parameter Model is used to pass data, as follows:

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

The hello returned is the name of the logical view that needs to carry the data into the Model.

3.2 the redirection

Redirection is also possible. In fact, if there is a need for redirection in SpringMVC, it usually works like this:

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

3.3 forward forward

Forward forwarding can also be done. In fact, if there is a requirement for forward forwarding in SpringMVC, it is usually done this way:

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

3.4 is really a String

Of course, there is a case where you really want to return a String, in which case you can just add the @responseBody annotation to the method, or the @restController composite annotation to the Controller itself, as follows:

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

It could also look like this:

@Controller
public class HelloController {
    @GetMapping("/hello")
    @ResponseBody
    public String hello(a) {
        return "hello provider!"; }}Copy the code

These are the cases where the return value is String.

4. JSON

HttpMessageConverter automatically converts data from a List, Map, or entity class to JSON. If you are using Jackson or Gson, you will automatically return JSON with no extra configuration because the framework provides the corresponding HttpMessageConverter. If you are using Alibaba Fastjson, You need to manually provide an instance of the corresponding HttpMessageConverter method that returns something like this:

@GetMapping("/user")
@ResponseBody
public User getUser(a) {
    User user = new User();
    List<String> favorites = new ArrayList<>();
    favorites.add("Football");
    favorites.add("Basketball");
    user.setFavorites(favorites);
    user.setUsername("zhagnsan");
    user.setPassword("123");
    return user;
}
@GetMapping("/users")
@ResponseBody
public List<User> getALlUser(a) {
    List<User> users = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        User e = new User();
        e.setUsername("zhangsan:" + i);
        e.setPassword("pwd:" + i);
        users.add(e);
    }
    return users;
}
Copy the code

conclusion

Ok, here are the four different types of return values from SpringMVC method summarized by Songo for everyone. If you have any questions, please leave a comment.

Pay attention to the public account [Jiangnan little Rain], focus on Spring Boot+ micro service and front and back end separation and other full stack technology, regular video tutorial sharing, after attention to reply to Java, get Songko for you carefully prepared Java dry goods!