Skip to content

数据响应

SpringMVC的数据响应方式可以分为:

  • 页面跳转
    • 直接返回字符串,如return "/success.jsp";,跳转到success.jsp页面
    • 通过ModelAndView对象返回
  • 回写数据
    • 直接返回字符串
    • 返回对象或集合

页面跳转

页面跳转有两种方式:直接返回字符串和通过ModelAndView对象返回

直接返回字符串

页面跳转中直接返回字符串的方式:将返回的字符串与视图解析器的前后缀拼接后跳转

配置内部资源视图解析器

xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    
	<!-- 配置内部资源视图解析器,配置其前缀和后缀 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

配置完内部资源视图解析器后,我们进行视图跳转时,就可以不需要写前缀和后缀了,直接写视图的文件名

java
@Controller   // 放到Spring容器中
public class UserController {
    @RequestMapping("/quick")  // 请求映射,访问/quick时,就会映射到save()方法
    public String save() {
        System.out.println("Controller save running");
        return "success";
    }
}

最终的转发地址:/jsp/success.jsp

返回带有前缀的字符串:

  • 转发:forward:/jsp/success.jspforward:可以不写)
  • 重定向:redirect:/success.jsp(重定向表示客户端再次访问请求,要想重定向,资源必须处于一个可以被访问的位置,即有访问权限)

返回ModelAndView对象

ModelAndView对象中主要涉及两个方面:

  • Model:模型,作用是封装数据
  • View:视图,作用是展示数据
java
import org.springframework.web.servlet.ModelAndView;

@Controller   // 放到Spring容器中
public class UserController {
    // 返回ModelAndView对象写法一
    @RequestMapping("/quick2")  // 请求映射,访问/quick2时,就会映射到save()方法
    public ModelAndView save() {
        ModelAndView modelAndView = new ModelAndView();
        // 设置模型数据,以键值对的形式存放,放到request域中
        modelAndView.addObject("username", "jlc");
        // 设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
    }
    // 返回ModelAndView对象写法二
    @RequestMapping("/quick2")  // 请求映射,访问/quick2时,就会映射到save()方法
    // SpringMVC对应的方法参数可以帮我们进行注入,在解析参数的时候,发现ModelAndView需要SpringMVC框架提供,那么SpringMVC就会为我们提供一个ModelAndView对象
    public ModelAndView save(ModelAndView modelAndView) {  
        // 设置模型数据,以键值对的形式存放,放到request域中
        modelAndView.addObject("username", "jlc");
        // 设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
    }
    // 返回ModelAndView对象写法三,只设置模型数据
    @RequestMapping("/quick2")  // 请求映射,访问/quick2时,就会映射到save()方法
    public String save(Model model) {
        // 设置模型数据,以键值对的形式存放,放到request域中
        model.addAttribute("username", "jlc");
        return "success";
    }
}

上述的方法本质上也可以使用原始的方式向域中进行数据的存储(原生的方式不常用,推荐用框架方式):

java
@RequestMapping("/quick2")  // 请求映射,访问/quick2时,就会映射到save()方法
public String save(HttpServletRequest request) {
 request.setAttribute("username", "jlc");
 return "success";
}

ModelAndViewModelSpringMVC给我们封装好的对象,HttpServletRequest是原生的对象

success.jsp文件中获取模型数据:

html
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Success!${username}</h1>
</body>
</html>

在浏览器地址中输入:localhost:8080/quick2

网页中显示:success!jlc


回写数据

回写数据指的是客户端访问服务端,服务端将数据直接回写给客户端进行展示,回写数据的方式分为两种:直接返回字符串和返回对象或集合

直接返回字符串

  • 通过SpringMVC框架注入的response对象,使用response.getWriter().print("hello world")回写数据,此时不需要视图跳转,业务方法返回值为void

    java
    @RequestMapping("/quick2")  // 请求映射,访问/quick2时,就会映射到save()方法
    public Void quickMethod(HttpServletRequest request) throws IOException {
        response.getWriter().print("hello world");
    }

    在浏览器地址中输入localhost:8080/quick2,回车,在页面中显示hello world

  • 将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,其方法返回的字符串不是跳转,而是直接在http响应体中返回

    java
    @RequestMapping("/quick2")  // 请求映射,访问/quick2时,就会映射到save()方法
    @ResponseBody // 告知SpringMVC框架,其方法返回的字符串不是跳转,而是直接在http响应体中返回
    public String quickMethod() throws IOException {
        return "hello world";
    }

在实际的开发中,往往不会直接进行字符串的返回,往往返回一些有用格式的内容(如JSON格式)我们一般采用对象转化工具进行转换

使用转换工具时,需要在pom.xml配置文件中进行导入相应包的坐标

xml
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0.RELEASE</version>
</dependency>

使用转换工具,将对象转换成json字符串进行回写数据的返回

java
@RequestMapping("/quick2")
@ResponseBody
public String quickMethod() throws IOException {
    User user = new User();
    user.setUsername("jlc");
    user.setAge(25);
    // 使用json的转换工具将对象转换成json格式字符串
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(user);
    return json;  // 以JSON格式进行返回
}

在浏览器地址中输入localhost:8080/quick2,回车,在页面中显示{"username":"jlc","age":25}

返回对象或集合

对于上述的对象转json字符串的过程,SpringMVC框架做了封装,我们只需进行配置即可使用,就是返回对象或集合的方式

首先需要在SpringMVC配置文件spring-mvc.xml中进行配置:

xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    
	<!-- 配置处理器映射器,注入一个json转换器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
            	<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
            </list>
        </property>
    </bean>
    
</beans>

将对象或集合直接转换成json字符串进行返回

java
@RequestMapping("/quick2")
@ResponseBody
public User quickMethod() throws IOException {
    User user = new User();
    user.setUsername("jlc");
    user.setAge(25);
    return user;  // user对象会被知道的转换成JSON格式字符串进行返回
}

在浏览器地址中输入localhost:8080/quick2,回车,在页面中显示{"username":"jlc","age":25}

配置转换器的方式也是比较麻烦的,我们可以使用mvc的注解驱动代替上述配置:

即使用下面的内容配置来替代之前繁琐的处理器映射配置

xml
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    
	<!--mvc的注解驱动-->
	<mvc:annotation-driven/>
    
</beans>

SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。

使用 <mvc:annotation-driven> 可以自动加载 RequestMappingHandlerMapping(处理映射器)和 RequestMappingHandlerAdapter(处理适配器),可用在 Spring-xml.xml 配置文件中使用 <mvc:annotation-driven> 替代注解处理器和适配器的配置。

同时使用 <mvc:annotation-driven> 默认底层就会集成 jackson 进行对象或集合的 json 格式字符串的转换

Released under the MIT License.