使用@Controller 注解的处理器的处理器方法,其返回值常用的有四种类型:
➢ 第一种:ModelAndView
➢ 第二种:String
➢ 第三种:无返回值 void
➢ 第四种:返回自定义类型对象
根据不同的情况,使用不同的返回

准备工作:
1.导入需要的依赖:

<dependencies>

    <!-- junit测试依赖 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.7.0</version>
      <scope>test</scope>
    </dependency>

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

    <!-- springMVC依赖 -->
    <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标签库包-->
    <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 依赖-->
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
      <scope>compile</scope>
    </dependency>


  </dependencies>

2.配置spring配置文件:

<?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">
    <!-- 开启组件扫描   -->
    <context:component-scan base-package="com.test"></context:component-scan>

    <!--声明 配置springMVC视图解析器-->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀:视图文件的路径-->
        <property name="prefix" value="/WEB-INF/view/" />
        <!--后缀:视图文件的扩展名-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--读写JSON的支持(Jackson)-->
    <mvc:annotation-driven />

</beans>

3.配置web.xml文件:

<?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">
<!-- 声明springMvc的核心对象 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>

    <!--  注册字符集过滤器,解决post请求的中文乱码问题-->
    <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.我的包目录结构:

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_xml

1.返回ModelAndView(常用)

1.使用ModelAndView返回数据:返回的数据是在request中的
想当于view.addObject("messages","hello world");是等同于 request.setAttribute("messages","hello world");的。

2.Controller层代码:

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

    // 1.使用ModelAndView返回数据:返回的数据是在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.前端接收数据:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>使用ModelAndView作为返回值:${requestScope.messages}</h2>
</body>
</html>

4.效果展示:

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_mvc_02

2.返回值为String;(常用)

配置视图解析器,用于跳转页面:

若要跳转的资源为内部资源,则视图解析器可以使用 InternalResourceViewResolver 内部资源视图解析器。此时处理器方法返回的字符串就是要跳转页面的文件名去掉文件扩展名后的部分。这个字符串与视图解析器中的 prefix、suffix 相结合,即可形成要访问的 URI

1.controller层代码:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {
    // 使用视图解析器加返回String用于跳转页面
    @GetMapping("returnStringView.mvc")
    public String returnStringView(){
        return "index";
    }
}

2.前端代码:index.jsp代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>使用String返回值跳转到该页面</h1>
</body>
</html>

3.效果展示:

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_mvc_03

3. 返回 void(了解)

对于处理器方法返回 void 的应用场景,AJAX 响应.

若处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void。

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_xml_04


1.controller层代码:

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


    
    // 无返回值,使用HttpServletRequest对象跳转页面,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.前端index.jsp代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>无返回值:使用HttpServletResponse对象跳转到该页面:session域中的数据:${sessionScope.message}</h1>
</body>
</html>

3.效果展示:

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_java_05

4.返回自定义类型对象(重点掌握这个)

处理器方法也可以返回 Object 对象。这个 Object 可以是 Integer,String,自定义对象,Map,List 等。但返回的对象不是作为逻辑视图出现的,而是作为直接在页面显示的数据出现的。返回对象,需要使用@ResponseBody 注解,将转换后的 JSON 数据放入到响应体中。

4.1.使用ajax返回自定义类型对象:

1.实体类代码:

/**
 * @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代码:

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

    // 用于跳转到 ajax.jsp页面
    @GetMapping("ajax.mvc")
    public String ajax(){
        return "ajax";
    }

   // 用于响应ajax请求
    @ResponseBody
    @PostMapping("AjaxReturnObject.mvc")
    public User AjaxReturnObject(User user){
        User myUser = new User(user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getTelephone());
        // 返回json字符串
        return myUser;
    }
}

3.前端代码:

<%@ 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){
                    // 返回的数据都放在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">提交参数</button>
<br/>
<p>数据回显:-------------------------</p>
<p>id:<span id="id"></span></p>
<p>姓名:<span id="username"></span></p>
<p>密码:<span id="password"></span></p>
<p>邮箱:<span id="email"></span></p>
<p>电话:<span id="telephone"></span></p>
<p></p>


</body>
</html>

注意点:如果dataType:"text"是这样的,是一个json字符串,需要将json字符串转化为js对象。

js对象转json字符串:var jsonStr = JSON.stringify(“需要转换的js对象”); json字符串转js对象: var data =JSON.parse(“需要转换的json字符串”);

4.2返回List集合:list集合返回到前端就是json数组:

controller代码:

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

   // 用于响应ajax请求
    @ResponseBody
    @PostMapping("AjaxReturnObject.mvc")
    public User AjaxReturnObject(User user){
        User myUser = new User(user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getTelephone());
        // 返回json字符串
        return myUser;
    }
 
   // 返回List集合
    @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);
        // 返回json数组
        return userList;
    }
}

2.前端代码:

<%@ 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", //返回json字符串,需要转换为js对象
                dataType:"json", // 直接返回js对象
                success:function(result){
                    // 返回的数据都放在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("-------------我是一条美丽的分割线---------------------");

                    }
                }
            });
        });


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

这里主要是说返回值问题,所有前端页面我就没有去渲染了,只是在控制台输出了一下。

3.效果展示:

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_xml_06


4.3返回Map集合:

1.controller代码:

/**
 * @author compass
 * @version 1.0
 * @date 2021-04-21 13:37
 */
@Controller
@RequestMapping(value = "/user/")
public class UserController {
   // 用于跳转到 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.前端代码:

<%@ 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(){
           // 返回map集合  
       $("#map").click(function(){
            $.ajax({
                url:"/user/AjaxReturnMap.mvc",
                type:"get",
                dataType:"json", // 直接返回js对象
                success:function(result){
                    // 返回的数据都放在data中
                    console.log(result);
                }
            });
        });

    });
</script>

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

3.结果展示:

java controller 返回数据对象应该怎么命名 springmvc controller返回值类型_spring_07


4.4 返回String字符串:

返回值为String的时候如何区分到底返回的是视图还是String字符串呢?

如果方法上没有 @ResponseBody注解那就是返回视图,有就是返回字符串。

1.后端代码:

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

      // 直接返回字符串
    @ResponseBody
    @GetMapping("AjaxReturnString.mvc")
    public String AjaxReturnString(){
        return "hello world";
    }

}

2.前端代码:

<%@ 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(){
      // 返回String集合
        $("#str").click(function(){
            $.ajax({
                url:"/user/AjaxReturnString.mvc",
                type:"get",
                dataType:"text", // 直接返回js对象
                success:function(result){
                    // 返回的数据都放在data中
                  alert(result);
                }
            });
        });

    });
</script>

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

需要注意的是如果返回的是String字符串, dataType:"text"是text,否则接收值的时候是有问题的。