Spring-mvc json 返回前端

来源:互联网 发布:pop的端口号 编辑:程序博客网 时间:2024/06/05 18:34

1. 在pom.xml中添加fastjson

      <dependency>          <groupId>com.alibaba</groupId>          <artifactId>fastjson</artifactId>          <version>1.2.7</version>      </dependency>

2. 在spring-mvc.xml中,添加以下内容

 <mvc:annotation-driven>        <mvc:message-converters>            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <constructor-arg value="UTF-8" />            </bean>            <bean                    class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">                <property name="features">                    <array value-type="com.alibaba.fastjson.serializer.SerializerFeature">                        <value>NotWriteDefaultValue</value>                        <value>DisableCircularReferenceDetect</value>                    </array>                </property>                <property name="supportedMediaTypes">                    <list>                        <value>application/json;charset=UTF-8</value>                        <value>text/html;charset=UTF-8</value>                        <value>text/plain;charset=UTF-8</value>                    </list>                </property>            </bean>        </mvc:message-converters>    </mvc:annotation-driven>

3、写测试的JAVA代码

@RequestMapping(value = "/testpost", method = { RequestMethod.GET,            RequestMethod.POST })    @ResponseBody    public Map<String,String> testpost(Model model, HttpServletRequest request, String id) {        System.out.println("testpost:id=" + id);        Map<String,String> map = new HashMap<String, String>();        map.put("id","99999");        return map;    }   

4、写JSP测试

<body>    <div>        <input id='testme' value='123'></input>        <button onclick="testpost()">测试 Post</button>    </div>    <script type="text/javascript">        function testpost(){            $.post('${basepath}/web/testpost',{id:100},function(data){                $('#testme').val(data.id);                console.log(data);            });        }    </script></body>
0 0
原创粉丝点击