博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

SpringMVC - 02SpringMVC数据响应

Posted on 2020-11-21 22:32  Kingdomer  阅读(105)  评论(0)    收藏  举报

SpringMVC - 02SpringMVC数据响应

SpringMVC数据响应方式

   > 页面跳转:  1. 直接返回字符串   2. 通过ModelAndView对象返回

   > 回写数据:  1. 直接返回字符串   2. 返回对象或集合

 

(1)页面跳转 - 返回字符串形式

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

    @RequestMapping(value = "/quick")
    public String save(){
        System.out.println("Controller save running......");
        return "success";
    }
    <!--配置内部资源视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

转发资源地址: /jsp/success.jsp

返回带有前缀的字符串: 转发: forward:/jsp/success.jsp    重定向: redirect:/jsp/success.jsp

 

(2)页面跳转 - 返回ModelAndView对象

(2.1) 返回ModelAndView对象

    @RequestMapping("/quick2")
    public ModelAndView save2(){
        // Model: 模型,封装数据
        // View:  视图,展示数据
        ModelAndView modelAndView = new ModelAndView();
        // 设置模型数据 addObject
        modelAndView.addObject("username","bearpx2");
        // 设置视图名称 setViewName
        modelAndView.setViewName("success");

        return modelAndView;
    } 
<body>
     <h1>成功!!!${username}</h1>
     <hr/>
</body>

(2.2) 传入ModelAndView, 设置属性后返回

    @RequestMapping("/quick3")
    public ModelAndView save3(ModelAndView modelAndView){
        // 设置模型数据
        modelAndView.addObject("username","bearpx3");
        // 设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
    }

(2.3)传入Model对象,返回字符串形式

    @RequestMapping("/quick4")
    public String save4(Model model){
        // 设置模型数据  addAttribute
        model.addAttribute("username","bearpx4");
        return "success";
    }

(2.4)传入HttpServletRequest,返回字符串

    @RequestMapping("/quick5")
    public String save5(HttpServletRequest request){
        request.setAttribute("username","newRequest");
        return "success";
    }

  

(3)回写数据 - 直接返回字符串

Web基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要使用response.getWriter().print("hello bearpx")即可。

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

    @RequestMapping("/quick6")
    public void save6(HttpServletResponse response) throws IOException {
        response.getWriter().print("hello beaxpx");
    }

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

    @RequestMapping("/quick7")
    @ResponseBody   // 告知SpringMVC框架,不进行视图跳转,直接进行数据响应
    public String save7()  {
        return "hello world!!!";
    }

 

(4) 回写数据 - 返回对象或集合

(4.1)返回json格式数据

    @RequestMapping("/quick8")
    @ResponseBody
    public String save8()  {
        return "{\"username\":\"zhangsan\",\"age\":\"18\"}";
    }

(4.2) 使用jackson转换json字符串

    @RequestMapping("/quick9")
    @ResponseBody
    public String save9() throws Exception {
        System.out.println("进入save9方法中......");
        User user = new User();
        user.setUsername("zhangzhang");
        user.setAge(11);
        // 使用json的转换工具将对象转换成json格式字符串,然后返回
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        System.out.println(json);
        return json;
    }

引入坐标

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.10.5</version>
        </dependency>

故障:找不到JSON转换类,引入的坐标没有起作用

 在IDEA - Project Structure - Artifacts  将需要引入的jar包 右键  Put into /WEB-INF/lib

(4.3)返回对象 

    @RequestMapping("/quick10")
    @ResponseBody
    public User save10() throws Exception {
        User user = new User();
        user.setUsername("zhangzhang");
        user.setAge(11);
        return user;
    }

期望SpringMVC自动将User 转换成json格式的字符串 // 配置处理器映射器

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
            </list>
        </property>
    </bean>

(4.4)设置mvc注解驱动

在方法上添加@ResponseBody就可以返回json格式的字符串,但是配置比较繁琐,代码较多。因此可使用mvc的注解驱动替代上述配置。

引入mvc的命名空间和约束地址。

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

<mvc:annotation-driven />

 

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

使用<mvc:annotation-driven>自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter(处理适配器),

可用在Spring-mvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。

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