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>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值