SpringMVC处理器返回值Object

使用@Controller和@ResponseBody需要使用Http消息转换器(HttpMessageConverter),而消息转换器的开启,需要由<mvc:annotation-driven/>来完成。Spring容器初始化时<mvc:annotation-driven/>时默认创建七个HttpMessageConverter对象。

 

1.引入jar包

<!-- jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.9</version>
        </dependency>

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

  

2.创建处理器方法(返回String类型)

//返回String类型
    @RequestMapping(value = "/second",produces = "text/html;charset=utf-8")//produces设置编码格式
    @ResponseBody//设置响应主体
    public Object doSecond(){
        return "doSecond";
    }

  

(返回自定义类型)

 //返回自定义类型
    @RequestMapping("/third")//URL
    @ResponseBody//设置响应主体
    public Object doThird(){
        UserInfo u1=new UserInfo();
        u1.setUsername("离人愁");
        return u1;
    }

  

(返回集合类型)

//返回集合类型
    @RequestMapping("/four")//URL
    @ResponseBody//设置响应主体
    public Object doFour(){
        List<UserInfo> list=new ArrayList<UserInfo>();
        //创建两个对象
        UserInfo u1=new UserInfo();
        u1.setUsername("离人愁");

        UserInfo u2=new UserInfo();
        u2.setUsername("最美的期待");
        //添加到list集合当中
        list.add(u1);
        list.add(u2);
        //返回list
        return list;
    }

  

3.配置消息转换器

 <!--视图解析器-->
   <bean id="methodNameResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/"/>
       <property name="suffix" value=".jsp"/>
   </bean>

<!--http转换器开启-->
    <mvc:annotation-driven/>
    <!--扫描包下所有的被标注的类-->
    <context:component-scan base-package="cn.happy.day08Object"/>

  

4.使用Ajax接收数据

<%@page language="java" pageEncoding="utf-8" contentType="text/html; utf-8" %>
<html>
<head>
    <%--引入js--%>
    <script type="text/javascript" src="js/jQuery1.11.1.js"></script>
    <script type="text/javascript">
        $(function () {
            //注册按钮单击事件
            $("input").click(function () {
                $.ajax({
                    //请求地址
                    url:"${pageContext.request.contextPath}/four",
                    //请求方式
                    type:"POST",
                    //回调函数
                    success:function (data) {
                        //使用each方法遍历
                        $.each(data,function (i,item) {
                            alert(item.username);
                        })
                    }
                });
            })
        });
    </script>
</head>
<body>
<h2>Hello World!</h2>
    <input type="button" value="使劲点我!!!"/>

</body>
</html>

  

posted @ 2018-03-29 13:32  徐昌琦  阅读(190)  评论(0编辑  收藏  举报