SpringMVC 第十一章 SpringMVC 的数据响应


SpringMVC —— 第十一章 SpringMVC 的数据响应


1. SpringMVC 的数据响应方式

  1. 页面跳转
    • 直接返回字符串
    • 通过 ModelAndView 返回
  2. 回写数据
    • 直接返回字符串
    • 返回对象集合

2. 页面跳转

2.1. 直接返回字符串

直接返回字符串:此种方式会将返回的字符串于视图解析器的前后缀拼接后跳转。

@RequestMapping("/quick")
public String quickMethod() {
      return "index";
}
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />

由上述代码可知,转发资源地址为:/WEB-INF/views/index.jsp

返回带有前缀的字符串:

转发:forward:/WEB-INF/views/index.jsp

重定向:redirect: /index.jsp

2.2. 返回 ModelAndView 对象

示例代码

com.yourname.controller.UserController

/**
 * @author gregperlinli
 */
@Controller
@RequestMapping(value = "/user")
public class UserController &#123;
    @RequestMapping(value = "/quick", method = RequestMethod.GET, params = &#123;"username"&#125;)
    public String save() &#123;
        System.out.println("Controller save running");
        return "success.jsp";
    &#125;
    @RequestMapping(value = "/quick2")
    public ModelAndView save2() &#123;
        /*
            Model: Encapsulate data
            View: Display data
         */
        ModelAndView modelAndView = new ModelAndView();
        // Set model data
        modelAndView.addObject("username", "gregPerlinLi");
        // Set view name
        modelAndView.setViewName("../success.jsp");
        return modelAndView;
    &#125;
    @RequestMapping(value = "/quick3")
    public ModelAndView save3(ModelAndView modelAndView) &#123;
        modelAndView.addObject("username", "gregPerlinLi");
        modelAndView.setViewName("../success.jsp");
        return modelAndView;
    &#125;
    @RequestMapping(value = "/quick4")
    public String save4(Model model) &#123;
        model.addAttribute("username", "gregPerlinLi");
        return "../success.jsp";
    &#125;
    @RequestMapping(value = "/quick5")
    public String save5(HttpServletRequest request, HttpServletResponse response) &#123;
        request.setAttribute("username", "gregPerlinLi");
        return "../success.jsp";
    &#125;
&#125;

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Success</title>
    <style type="text/css">
        body &#123;
            font-family: Futura, "PingFang SC", Helvetica, Arial, sans-serif;
        &#125;
    </style>
</head>
<body>
    <h1>Success! $&#123;username&#125;</h1>
</body>
</html>

3. 回写数据

3.1. 直接返回字符串

Web 基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要用

response.getWriter().print("Hello world!");

而在 Controller 中,使用如下方式回写

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

@RequestMapping("/quick")
public void quickMethod(HttpServletRequest request, HttpServletResponse response) &#123;
  response.getWriter.rping("Hello world!");
&#125;

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

@RequestMapping("/quick")
@ResponseBody // Tell the spring MVC framework not to jump the view, but to respond directly to the data
public String quickMethod(HttpServletRequest request, HttpServletResponse response) &#123;
  return "Hello gregPerlinLi!";
&#125;

3.2. 返回对象或集合

通过 SpringMVC 帮助我们对对象进或集合进行 JSON 字符串的转换并回写,为处理器适配器配置消息转换参数,指定使用 Gson 进行对象或集合的转换,因此需要在 spring-mvc.xml 中进行如下配置

<!-- Configure processor mapper -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter">
              
              </bean>
        </list>
    </property>
</bean>

但是,在方法上添加 @ResponseBody 就可以返回 JSON 字符串的配置比较麻烦,配置的代码较多,因此,我们可以使用 MVC 的注解驱动代替上述配置。

<!-- Annotation driven MVC -->
<mvc:annotation-driven/>

在 SpringMVC 中,处理器映射器处理器适配器视图解析器称为 SpringMVC 的三大组件。使用 <mvc:annotation-driven> 自动加载 RequestMappingHandlerMapping(处理器映射器)和 RequestMappingHandlerAdapter(处理器适配器),可用在 spring-mvc.xml 配置文件中使用 <mvc:annotation-driven> 替代注解处理器和适配器的配置

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

示例代码:

com.yourname.controller.UserController

@RequestMapping(value = "/quick9")
@ResponseBody
public String save9() throws Exception &#123;
    User user = new User("gregPerlinLi", 20);
    // Use the JSON conversion tool to convert the object into a string in JSON format and then return it
    Gson gson = new Gson();
    String json = gson.toJson(user);
    return json;
&#125;

@RequestMapping(value = "/quick10")
@ResponseBody
public User save10() throws Exception &#123;
    User user = new User("gregPerlinLi", 20);
    return user;
&#125;

4. 知识要点

SpringMVC 的数据响应方式

  1. 页面跳转
    • 直接返回字符串
    • 通过 ModelAndView 返回
  2. 回写数据
    • 直接返回字符串
    • 返回对象集合


文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录