Spring mvc Controller层与前端JSON数据交互

纯记录贴:
1、pom.xml:

  <dependency>  
        <groupId>org.codehaus.jackson</groupId>  
        <artifactId>jackson-core-asl</artifactId>  
        <version>1.9.13</version>  
    </dependency>       
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>

2、dispatcher-servlet.xml配置

    <!-- mvc JSON格式化 start-->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >   
        <property name="order" value="0" />   
    </bean>

    <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/> 
            </list>
        </property>
    </bean>

    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
            <!-- JSON数据日期格式化 -->
        <property name="objectMapper">       
            <bean class="com.bi.common.util.XSSObjectMapper">
                <property name="dateFormat">
                    <bean class="java.text.SimpleDateFormat">
                        <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!-- mvc JSON格式化 end-->

3、XSSObjectMapper.class

package com.bi.common.util;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.springframework.web.util.HtmlUtils;

public class XSSObjectMapper extends ObjectMapper {
    private static final long serialVersionUID = -3448961813323784217L;

    public XSSObjectMapper() {
        SimpleModule module = new SimpleModule("HTML XSS Serializer",
                new Version(1, 0, 0, ""));
        module.addSerializer(new JsonHtmlXssSerializer(String.class));
        this.registerModule(module);
    }

    class JsonHtmlXssSerializer extends JsonSerializer<String> {

        public JsonHtmlXssSerializer(Class<String> string) {
            super();
        }

        public Class<String> handledType() {
            return String.class;
        }

        public void serialize(String value, JsonGenerator jsonGenerator,
                SerializerProvider serializerProvider) throws IOException,
                JsonProcessingException {
            if (value != null) {
                String encodedValue = HtmlUtils.htmlEscape(value.toString());
                jsonGenerator.writeString(encodedValue);
            }
        }
    }
}

4.1、前端发JSON请求:
http://biancheng.dnbcw.info/java/452027.html
4.2、Controller接收:

5.1 Controller层返回JSON数据;

@RequestMapping("/getUserList")
    @ResponseBody
    public Map<String,Object> getUserList() {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<User> userList = getUsers();
        resultMap.put("users", userList);
        return resultMap;
    }

5.2 前端接收JSON数据;

<script type="text/javascript"> $(document).ready(function(){ $("#button_getUser").click(function(){ //异步请求json数据 $.ajax({ type:"POST", url:"${pageContext.request.contextPath}/user/getUserList", success:function(data){ //迭代返回的json数据 $.each(data,function(i,user){ $("#results").append(user.userName+"---"+user.password+"<br>"); }); }, error:function(e) { alert("出错:"+e); } }); }); }); </script>

你可能感兴趣的:(spring,mvc,json,前端)