SpringMVC的数据响应


前言

接上篇SpringMVC入门,了解到在SpringMVC的支持下,开发变得更加方便和拥有更好,更简单的思路。下面开始SpringMVC的数据响应方式


一、SpringMVC的数据响应方式?

响应方式共有两种相应方式
1.页面跳转
 1.1直接返回字符串
 1.2通过ModelAndView对象返回
2.回写数据
 2.1直接返回字符串
 2.2返回对象和集合

二、页面跳转

1.直接返回字符串

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

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

通过配置和Java代码返回得到转发资源地址:/WEB-INF/views/index.jsp
返回带有前缀的字符串:
转发:forward:/WEB-INF/views/index.jsp
重定向:redirect:/index.jsp

2. 页面跳转

2.1 返回ModelAndView对象
@RequestMapping("/quick3")
public ModelAndView quickMethod3(){
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
	return modelAndView;
}

@RequestMapping(value="/quick2")
public ModelAndView save2(){
        /*
            Model:模型  作用封装数据
            View:视图  作用展示数据
         */
        ModelAndView modelAndView = new ModelAndView();
        //设置模型数据
        modelAndView.addObject("username","itcast");
        //设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
}
2.3 向request域存储数据

通过SpringMVC框架注入的request对象setAttribute()方法设置

// 请求地址  http://localhost:8080/user/quick
    @RequestMapping(value="/quick",method = RequestMethod.GET,params = {"username"})
    public String save(){
        System.out.println("Controller save running....");
        return "success";
    }

通过ModelAndView的addObject()方法设置

@RequestMapping(value="/quick3")
    public ModelAndView save3(ModelAndView modelAndView){
        modelAndView.addObject("username","itheima");
        //设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
    }

3. 回写数据

3.1 直接返回字符串

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

@RequestMapping("/quick4")
public void quickMethod4(HttpServletResponse response) throws IOException {
	response.getWriter().print("hello world");
}

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

@RequestMapping("/quick5")
@ResponseBody
public String quickMethod5() throws IOException {
	return "hello springMVC!!!";
}

在异步项目中,客户端与服务器端往往要进行json格式字符串交互,此时我们可以手动拼接json字符串返回。

    @RequestMapping(value="/quick8")
    @ResponseBody  //告知SpringMVC框架  不进行视图跳转 直接进行数据回写(重点)  //既是不进行页面跳转
    public String save8() throws IOException {
        return "{\"username\":\"zhansgan\",\"age\":18}";
    }

上述方式手动拼接json格式字符串的方式很麻烦,开发中往往要将复杂的java对象转换成json格式的字符串,我们可以使用web阶段学习过的json转换工具jackson进行转换,导入jackson坐标。

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

通过jackson转换json格式字符串,回写字符串。

    @RequestMapping(value="/quick9")
    @ResponseBody  //告知SpringMVC框架  不进行视图跳转 直接进行数据回写(重点)  //既是不进行页面跳转
    public String save9() throws IOException {
        User user = new User();
        user.setUsername("lisi");
        user.setAge(18);
        //使用json的转换工具将对象转换成json格式字符串再返回
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);

        return json;
    }
3.2 返回对象或集合

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

    <!--配置处理器映射器      跟/quick10配对     -->
    <!--<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>-->
    @RequestMapping(value="/quick10")
    @ResponseBody  //告知SpringMVC框架  不进行视图跳转 直接进行数据回写(重点)  //既是不进行页面跳转
    //期望SpringMVC自动将User转换成json格式的字符串
    public User save10() throws IOException {
        User user = new User();
        user.setUsername("lisi");
        user.setAge(18);

        return user;
    }

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

    <!--这上下两个相等,就是SpringMVC框架的强大-->
    <!--mvc的注解驱动-->
    <mvc:annotation-driven conversion-service="conversionService"/>

在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。
使用<mvc:annotation-driven >自动加载 RequestMappingHandlerMapping(处理映射器)和
RequestMappingHandlerAdapter( 处 理 适 配 器 ),可用在Spring-xml.xml配置文件中使用
<mvc:annotation-driven >替代注解处理器和适配器的配置。
同时使用<mvc:annotation-driven >默认底层就会集成jackson进行对象或集合的json格式字符串的转换。

总结

在学习SpringMVC获得数据请求的过程中,通过页面跳转增大自己的学习热情,虽然有的时候是404或者500,但是通过学习慢慢的改变自己编写代码的习惯。慢慢学的更好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

feiyunzhixia11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值