Spring MVC return value processing

Posted by edcaru on Thu, 03 Mar 2022 14:43:08 +0100

There are four common types of return values of processor methods annotated with @ Controller:
The first: ModelAndView
The second type: String
The third type: no return value void
The fourth type: return custom type objects
Use different returns according to different situations

preparation:
1. Import required dependencies:

  <dependencies>

    <!-- junit Test dependency -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.7.0</version>
      <scope>test</scope>
    </dependency>

    <!-- servlet rely on -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- springMVC rely on -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
      <scope>compile</scope>
    </dependency>

    <!--jstl Tag library package-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <!--  jackson rely on-->
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
      <scope>compile</scope>
    </dependency>


  </dependencies>

2. Configure spring configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- Turn on component scanning   -->
    <context:component-scan base-package="com.test"></context:component-scan>

    <!--Claim configuration springMVC view resolver -->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--Prefix: path to view file-->
        <property name="prefix" value="/WEB-INF/view/" />
        <!--Suffix: extension of the view file-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--Reading and writing JSON Support of( Jackson)-->
    <mvc:annotation-driven />

</beans>

3. Configure web XML file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!-- statement springMvc Core object of DispatcherServlet -->
    <servlet>
        <servlet-name>web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springConfig.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>web</servlet-name>
        <url-pattern>*.mvc</url-pattern>
    </servlet-mapping>

    <!--  Register character set filter,solve post Chinese garbled code problem of request-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <param-name>forRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>

    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

4. My package directory structure:

1. Return to ModelAndView (common)

1. Use ModelAndView to return data: the returned data is in the request
Want to be in view addObject("messages","hello world"); Is equivalent to request setAttribute("messages","hello world"); of

2.Controller layer code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {

    // 1. Use ModelAndView to return data: the returned data is in the request
    @GetMapping(value = "returnModelAndView.mvc")
    public ModelAndView returnModelAndView(HttpServletRequest request){
        
        ModelAndView view = new ModelAndView();
        view.addObject("messages","hello world");
        view.setViewName("show");
        return view;
    }
}

3. Front end receiving data:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>use ModelAndView As return value: ${requestScope.messages}</h2>
</body>
</html>

4. Effect display:

2. The return value is String; (common)

Configure the view parser to jump to the page:

If the resource to jump to is an internal resource, the view parser can use the InternalResourceViewResolver internal resource view parser. At this time, the string returned by the processor method is the part of the file name of the page to jump to minus the file extension. This string is combined with prefix and suffix in the view parser to form the URI to be accessed

1.controller layer code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {
    // Use the view parser and return String to jump to the page
    @GetMapping("returnStringView.mvc")
    public String returnStringView(){
        return "index";
    }
}

2. Front end code: index Jsp code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>use String Return value jump to this page</h1>
</body>
</html>

3. Effect display:

3. Return void (understand)

For the application scenario where the processor method returns void, AJAX responds
If the processor does not need to jump to any other resources after processing the request, the processor method can return void at this time.

1.controller layer code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {


    
    // If there is no return value, use the HttpServletRequest object to jump to the page and transfer data to the session
    @GetMapping("returnVoid.mvc")
    public void returnVoid(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/view/index.jsp").forward(request,response);
        session.setAttribute("message","Hello Word");
    }
}

2. Front end index Jsp code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>No: use return value HttpServletResponse Object jumps to the page:session Data in domain: ${sessionScope.message}</h1>
</body>
</html>

3. Effect display:

4. Return custom type objects (focus on this)

Processor methods can also return Object objects. This Object can be Integer, String, custom Object, Map, List, etc. However, the returned Object does not appear as a logical view, but as data directly displayed on the page. To return the Object, you need to use the @ ResponseBody annotation to put the converted JSON data into the response body.

4.1. Use ajax to return custom type objects:

1. Entity class code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:35
 */
public class User  implements Serializable {
    private int id;
    private String username;
    private String password;
    private String email;
    private String telephone;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public User(int id, String username, String password, String email, String telephone) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
        this.telephone = telephone;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", telephone='" + telephone + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id && username.equals(user.username);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, username);
    }
}

2.controller code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {

    // Used to jump to Ajax JSP page
    @GetMapping("ajax.mvc")
    public String ajax(){
        return "ajax";
    }

   // Used to respond to ajax requests
    @ResponseBody
    @PostMapping("AjaxReturnObject.mvc")
    public User AjaxReturnObject(User user){
        User myUser = new User(user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getTelephone());
        // Return json string
        return myUser;
    }
}

3. Front end code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
<body>
<script type="text/javascript">
    $(function(){
        $("#btn").click(function(){
            alert("button click");
            $.ajax({
                url:"/user/AjaxReturnObject.mvc",
                data:{
                    id:1,
                    username:"admin",
                    password:"root",
                    email:"admin@qq.com",
                    telephone:"123456"
                },
                type:"post",
                dataType:"json",
                success:function(data){
                    // The returned data is placed in data
                    console.log(data);
                    document.getElementById("id").innerHTML=data.id;
                    document.getElementById("username").innerHTML=data.username;
                    document.getElementById("password").innerHTML=data.password;
                    document.getElementById("email").innerHTML=data.email;
                    document.getElementById("telephone").innerHTML=data.telephone;
                }
            });
        });



    });
</script>

<button id="btn" type="button">Submit parameters</button>
<br/>
<p>Data echo:-------------------------</p>
<p>id: <span id="id"></span></p>
<p>full name:<span id="username"></span></p>
<p>password:<span id="password"></span></p>
<p>Email:<span id="email"></span></p>
<p>Telephone:<span id="telephone"></span></p>
<p></p>


</body>
</html>

Note: if dataType:"text" is like this, it is a json string. You need to convert the json string into a js object.

js object to json string: VAR jsonstr = json Stringify ("js object to be converted");
json string to js object: VAR data = json Parse ("json string to be converted");

4.2 return list set: the json array is the list set returned to the front end:

controller code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {

   // Used to respond to ajax requests
    @ResponseBody
    @PostMapping("AjaxReturnObject.mvc")
    public User AjaxReturnObject(User user){
        User myUser = new User(user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getTelephone());
        // Return json string
        return myUser;
    }
 
   // Returns the List collection
    @ResponseBody
    @GetMapping("AjaxReturnList.mvc")
    public List<User> AjaxReturnList(){

        List<User> userList= new ArrayList<User>();
        User user1 = new User(1,"admin1","root1","admin@qq.com1","1001");
        User user2 = new User(2,"admin2","root2","admin@qq.com2","1002");
        User user3 = new User(3,"admin3","root3","admin@qq.com3","1003");
        User user4 = new User(4,"admin4","root4","admin@qq.com4","1004");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        // Return json array
        return userList;
    }
}

2. Front end code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
<body>
<script type="text/javascript">
    $(function(){
         $("#ajax").click(function(){
            alert("button click");
            $.ajax({
                url:"/user/AjaxReturnList.mvc",
                type:"get",
                // dataType:"text", / / return json string, which needs to be converted into js object
                dataType:"json", // Directly return js object
                success:function(result){
                    // The returned data is placed in data
                   console.log(result);
                    for(var i = 0;i<result.length;i++){
                     console.log("id:"+result[i].id);
                     console.log("username:"+result[i].username);
                     console.log("password:"+result[i].password);
                     console.log("email:"+result[i].email);
                     console.log("telephone:"+result[i].telephone);
                     console.log("-------------I am a beautiful dividing line---------------------");

                    }
                }
            });
        });


    });
</script>
<button id="ajax" type="button">launch ajax</button>
</body>
</html>

This is mainly about the return value. I didn't render all the front-end pages, but just output them on the console.

3. Effect display:

4.3 return Map set:

1.controller code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {
   // Used to jump to Ajax jsp
    @GetMapping("ajax.mvc")
    public String ajax(){
        return "ajax";
    }

    @ResponseBody
    @GetMapping("AjaxReturnMap.mvc")
    public Map<String,Object> AjaxReturnMap(){

      Map<String, Object> map = new HashMap<>();

        User user1 = new User(1,"admin","root","admin@qq.com","1001");
        User user2 = new User(2,"admin2","root2","admin@qq.com2","1002");
        User user3 = new User(3,"admin3","root3","admin@qq.com3","1003");
        User user4 = new User(4,"admin4","root4","admin@qq.com4","1004");
        map.put("user1",user1);
        map.put("user2",user2);
        map.put("user3",user3);
        map.put("user4",user4);
        return map;
    }

}

2. Front end code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
<body>
<script type="text/javascript">
    $(function(){
           // Return map collection  
       $("#map").click(function(){
            $.ajax({
                url:"/user/AjaxReturnMap.mvc",
                type:"get",
                dataType:"json", // Directly return js object
                success:function(result){
                    // The returned data is placed in data
                    console.log(result);
                }
            });
        });

    });
</script>

<button id="map" type="button">launch ajax(map)</button>
</body>
</html>

3. Result display:


4.4 return String:
When the return value is String, how to distinguish whether the view or String is returned?

If there is no @ ResponseBody annotation on the method, it is to return the view, and if there is, it is to return the string.

1. Back end code:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {
   // Used to jump to Ajax jsp
    @GetMapping("ajax.mvc")
    public String ajax(){
        return "ajax";
    }

      // Return string directly
    @ResponseBody
    @GetMapping("AjaxReturnString.mvc")
    public String AjaxReturnString(){
        return "hello world";
    }

}

2. Front end code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
<body>
<script type="text/javascript">
    $(function(){
      // Return String collection
        $("#str").click(function(){
            $.ajax({
                url:"/user/AjaxReturnString.mvc",
                type:"get",
                dataType:"text", // Directly return js object
                success:function(result){
                    // The returned data is placed in data
                  alert(result);
                }
            });
        });

    });
</script>

<button id="str" type="button">launch ajax(map)</button>
</body>
</html>

It should be noted that if the returned String is String, dataType:"text" is text, otherwise there is a problem when receiving the value.

Topics: Java