• SpringMVC项目响应


    SpringMVC接收到请求和数据后,进行一些了的处理,当然这个处理可以是转发给Service,Service层再调用Dao层完成的,不管怎样,处理完以后,都需要将结果告知给用户。

    比如:根据用户ID查询用户信息、查询用户列表、新增用户等。

    对于响应,主要就包含两部分内容:

    • 响应页面
    • 响应数据
      • 文本数据
      • json数据

    因为异步调用是目前常用的主流方式,所以我们需要更关注的就是如何返回JSON数据,对于其他只需要认识了解即可。

    1. 环境准备

    • 创建一个Web的Maven项目

    • pom.xml添加Spring依赖

      
      
      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
      
        <groupId>com.dcxuexigroupId>
        <artifactId>springmvc_04_responseartifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>warpackaging>
      
        <name>springmvc_04_response Maven Webappname>
        
        <url>http://www.example.comurl>
      
        <properties>
          <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
          <maven.compiler.source>1.8maven.compiler.source>
          <maven.compiler.target>1.8maven.compiler.target>
        properties>
      
        <dependencies>
          <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.15.RELEASEversion>
          dependency>
          <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
          dependency>
          <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.9.8version>
          dependency>
        dependencies>
      
        <build>
          <plugins>
            <plugin>
              <groupId>org.apache.tomcat.mavengroupId>
              <artifactId>tomcat7-maven-pluginartifactId>
              <version>2.1version>
              <configuration>
                <port>80port>
                <path>/springmvcpath>
                <uriEncoding>UTF-8uriEncoding>
              configuration>
            plugin>
          plugins>
        build>
      
      project>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
    • 创建对应的配置类SpringMvcConfig和ServletContainersInitConfig

      @Configuration
      @ComponentScan("com.dcxuexi.controller")
      // 开启json数据类型转换
      @EnableWebMvc
      public class SpringMvcConfig {
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
          @Override
          protected Class<?>[] getRootConfigClasses() {
              return new Class[0];
          }
      
          @Override
          protected Class<?>[] getServletConfigClasses() {
              return new Class[]{SpringMvcConfig.class};
          }
      
          @Override
          protected String[] getServletMappings() {
              return new String[]{"/"};
          }
      
          // 处理乱码
          @Override
          protected Filter[] getServletFilters(){
              CharacterEncodingFilter filter = new CharacterEncodingFilter();
              filter.setEncoding("utf-8");
              return new Filter[]{filter};
          }
          
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
    • 编写模型类User和City

      public class User {
          private String userName;
          private Integer userAge;
          private String userSex;
          private City city;
      
          public String getUserName() {
              return userName;
          }
      
          public void setUserName(String userName) {
              this.userName = userName;
          }
      
          public Integer getUserAge() {
              return userAge;
          }
      
          public void setUserAge(Integer userAge) {
              this.userAge = userAge;
          }
      
          public String getUserSex() {
              return userSex;
          }
      
          public void setUserSex(String userSex) {
              this.userSex = userSex;
          }
      
          public City getCity() {
              return city;
          }
      
          public void setCity(City city) {
              this.city = city;
          }
      
          @Override
          public String toString() {
              return "{" +
                      "userName='" + userName + '\'' +
                      ", userAge=" + userAge + 
                      ", userSex='" + userSex + '\'' +
                      ", city=" + city +
                      '}';
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      public class City {
          private String country;
          private String provice;
          private String area;
      
          public String getCountry() {
              return country;
          }
      
          public void setCountry(String country) {
              this.country = country;
          }
      
          public String getProvice() {
              return provice;
          }
      
          public void setProvice(String provice) {
              this.provice = provice;
          }
      
          public String getArea() {
              return area;
          }
      
          public void setArea(String area) {
              this.area = area;
          }
      
          @Override
          public String toString() {
              return "{" +
                      "country='" + country + '\'' +
                      ", provice='" + provice + '\'' +
                      ", area='" + area + '\'' +
                      '}';
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
    • webapp下创建user.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      
      
          user
      
      
          

      Hello World!

      springmvc response.

      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
    • 编写UserController

      @Controller
      public class UserController {
      
      }
      
      • 1
      • 2
      • 3
      • 4

    最终创建好的项目结构如下:

    在这里插入图片描述

    2. 响应页面

    步骤1:设置返回页面

    @Controller
    public class UserController {
    
        @RequestMapping("/toJumpPage")
        //@ResponseBody  //1.此处不能添加@ResponseBody,如果加了该注入,会直接将page.jsp当字符串返回前端
        //2.方法需要返回String
        public String toJumpPage(){
            System.out.println("跳转首页页面");
            return "user.jsp";
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    步骤2:启动程序测试

    此处涉及到页面跳转,所以不适合采用PostMan进行测试,直接打开浏览器,输入

    http://localhost/springmvc/toJumpPage

    在这里插入图片描述

    3. 返回文本数据

    步骤1:设置返回文本内容

    @Controller
    public class UserController {
        
        @RequestMapping("/toText")
        @ResponseBody  //此处该注解就不能省略,如果省略了,会把toText txt当前页面名称去查找,如果没有回报404错误
        public String toText(){
            System.out.println("返回纯文本数据");
            return "toText txt";
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    步骤2:启动程序测试

    此处不涉及到页面跳转,因为我们现在发送的是GET请求,可以使用浏览器也可以使用PostMan进行测试,输入地址http://localhost/springmvc/toText访问

    在这里插入图片描述

    4. 响应JSON数据

    响应POJO对象

    @Controller
    public class UserController {
        
        @RequestMapping("/toJsonPOJO")
        @ResponseBody
        public User toJsonPOJO(){
            System.out.println("返回json对象数据");
            User user = new User();
            City city = new City();
            city.setCountry("中国");
            city.setProvice("上海");
            city.setArea("浦东新区");
            user.setUserName("小闯");
            user.setUserAge(20);
            user.setUserSex("男");
            user.setCity(city);
            return user;
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    返回值为实体类对象,设置返回值为实体类类型,即可实现返回对应对象的json数据,需要依赖==@ResponseBody注解和@EnableWebMvc==注解

    重新启动服务器,访问http://localhost/springmvc/toJsonPOJO

    在这里插入图片描述

    响应POJO集合对象

    @Controller
    public class UserController {
        
        @RequestMapping("/toJsonPOJOList")
        @ResponseBody
        public List<User> toJsonPOJOList(){
            System.out.println("返回json对象集合数据");
            List<User> userList  = new ArrayList<>();
            User user = new User();
            City city = new City();
            city.setCountry("中国");
            city.setProvice("上海");
            city.setArea("浦东新区");
            user.setUserName("小闯");
            user.setUserAge(20);
            user.setUserSex("男");
            user.setCity(city);
    
            User user2 = new User();
            City city2 = new City();
            city2.setCountry("中国");
            city2.setProvice("北京");
            city2.setArea("西城区");
            user2.setUserName("张三");
            user2.setUserAge(18);
            user2.setUserSex("男");
            user2.setCity(city2);
    
            userList.add(user);
            userList.add(user2);
            return userList;
        }
        
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    重新启动服务器,访问http://localhost/springmvc/toJsonPOJOList

    在这里插入图片描述

    知识点1:@ResponseBody

    名称@ResponseBody
    类型方法\类注解
    位置SpringMVC控制器方法定义上方和控制类上
    作用设置当前控制器返回值作为响应体,
    写在类上,该类的所有方法都有该注解功能
    相关属性pattern:指定日期时间格式字符串

    说明:

    • 该注解可以写在类上或者方法上
    • 写在类上就是该类下的所有方法都有@ReponseBody功能
    • 当方法上有@ReponseBody注解后
      • 方法的返回值为字符串,会将其作为文本内容直接响应给前端
      • 方法的返回值为对象,会将对象转换成JSON响应给前端

    此处又使用到了类型转换,内部还是通过Converter接口的实现类完成的,所以Converter除了前面所说的功能外,它还可以实现:

    • 对象转Json数据(POJO -> json)
    • 集合转Json数据(Collection -> json)

    项目代码

  • 相关阅读:
    【论文总结】Composition Kills: A Case Study of Email Sender Authentication
    [数据管理] 数据治理/大数据平台-开源软件与框架篇
    PI3K α/β 靶向抑制剂协同 BCL-2 阻断过程可用于治疗 DLBCL
    初步了解进程、进程调度的基本属性、进程间通信
    Linux进程概念
    Git高频命令【最实用命令】
    计算机视觉面试知识点总结
    LeetCode542. 01 矩阵(C++中等题)
    Shell编程之免交互
    计算机体系结构:1.1.系统加速比计算例题
  • 原文地址:https://blog.csdn.net/qq_37726813/article/details/127715159