Vi. interacting with JSON

Source: Internet
Author: User

1. Two modes of interaction

  

Shows the two formats for requesting data from a client, one that requests JSON data directly, and the other is Key/value data. But no matter what kind of data the request is, it is convenient to parse the result on the front page. Eventually we all convert to JSON data format.

Back to Top 2, import the corresponding jar package (see source for details)

Back to Top 3. Configure the JSON converter in the Springmvc.xml file

  The first method:

1 <mvc:annotation-driven ></mvc:annotation-driven>

The second method:

12345678910111213141516171819 <!-- 用于将对象转换为 JSON  --> <bean id="stringConverter"    class="org.springframework.http.converter.StringHttpMessageConverter"    <property name="supportedMediaTypes"        <list>             <value>text/plain;charset=UTF-8</value>         </list>     </property> </bean> <bean id="jsonConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"    <property name="messageConverters"        <list>             <ref bean="stringConverter"/>             <ref bean="jsonConverter"/>         </list>     </property> </bean>

  

Back to top 4, request for JSON data test

Here we need to take note of two annotations:

  @ResponseBody convert the background Pojo to a JSON object and return to the page.

@RequestBody accept the foreground JSON data and automatically encapsulate the JSON data Pojo.

①, JSP page

1234567891011121314151617181920212223242526272829303132333435 <%@ page language="java"contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>SpringMVC和 json 交互</title><script type="text/javascript"src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js"></script><script type="text/javascript">    var dataJson = {            ‘username‘:‘Bob‘,            ‘sex‘:‘男‘    };    function requestJson(){        $.ajax({            type:"POST",            url:"${pageContext.request.contextPath}/requestJson",            //指定数据格式为 json            contentType:"application/json;charset=UTF-8",            data:JSON.stringify(dataJson),            dataType:"json",            success:function(data){                console.log(data.username);                console.log(data.sex);            }        });    }    </script><body>    <button onclick="requestJson()"value="请求是json,返回json">请求是json,返回json</button>    </body>

  

②, Controller

123456789101112131415161718192021222324 packagecom.ys.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody; importcom.ys.po.User;@ControllerpublicclassUserController {            //请求为json,返回json    @RequestMapping("/requestJson")    //@RequestBody将请求信息的json串转成user对象    //@ResponseBody将user对象转成json输出    @ResponseBody    publicUser requestJson(@RequestBodyUser user) throwsException{        System.out.println(user);        returnuser;//由于@ResponseBody注解,将user转成json格式返回    }    }

③, testing

We visit the JSP page above and click on the button to enter the Controller

  

Then we look at the returned data:

  

Back to top 5, request for Key/value data test

①, JSP page

②, Controller

12345678 //请求为key/value,返回json    @RequestMapping("/requestKeyValue")    //@RequestBody将请求信息的json串转成user对象    @ResponseBody    publicUser requestKeyValue(User user) throwsException{        System.out.println(user);        returnuser;    }

③, testing

  

Then return the data:

  

Back to top 6, problems encountered

  ①, the following code, because we use Ajax submissions, we introduced a jquery file on the JSP page, found that no matter the absolute path or relative path, the system will always find this file?

1 <script type="text/javascript"src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js"></script>

Cause: Because you are in the Web. xml file, the configuration for the filter is to intercept all requests. So a file similar to *.js, or *.CSS, is intercepted, so it can't be accessed.

  

Workaround:

The first approach: we can use the interceptor configured above to intercept only *.do, or *.action, instead of "/". Then the SPRINGMVC container will not intercept files such as *.JS,*.CSS. But this style does not support Restful, it is recommended not to adopt.

Second method: Configure the Interceptor's filtering request in Web. xml

123456789 <!--要写在DispatcherServlet的前面, 让 defaultServlet先拦截请求,这样请求就不会进入Spring了,我想性能是最好的吧。-->     <servlet-mapping>         <servlet-name>default</servlet-name>         <url-pattern>*.css</url-pattern>     </servlet-mapping>     <servlet-mapping>         <servlet-name>default</servlet-name>         <url-pattern>*.js</url-pattern>     </servlet-mapping> 

Third approach: Configure non-filtering of static resources in Spingmvc.xml

123 <!-- 配置静态文件过滤器 -->    <mvc:resources location="/WEB-INF/css/"mapping="/css/**"/>    <mvc:resources location="/WEB-INF/js/"mapping="/js/**"/>

  

  ②, is also more prone to make mistakes 415

  

  

There are many reasons for this error. We need a step-by-Step troubleshooting:

The first step: you must ensure that the imported Jackson-related jar packages are full.

The second step: the configuration of the JSON converter in the Springmvc.xml file must not be missing, how to view this blog's 3rd

Step three: When writing an AJAX request. ContentType: "Application/json;charset=utf-8", do not write ContentType this attribute

Fourth step: Ajax to the background do not pass the string directly, to convert to JSON, that is data:JSON.stringify (Datajson),

Vi. interacting with JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.