基于springmvc的json传值

1 导入jackson jar包
jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
2 配置json转换器
在对应的mvc.xml中配置

 <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> 

3 后台

@Controller
public class JsonTest {
    @RequestMapping("/jsontest")
    @ResponseBody//表示返回的是个json对象会经过配置文件转换
    public User sd() throws Exception {
                User user = new User();
                user.setUsername("李贤");
            return user;
            }

}

4 前台

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
    <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>

    <script type="text/javascript">
        $(function(){
            alert("123")
            $("#btn").click(function(){
                $.ajax({
                    type:"POST",
                    url:"jsontest",
                    success:function(data){
                        alert("成功");//不是list不用写为data[0]
                        alert(data.username);
                    },
                    error:function(jqXHR,textStatus,errorThrown){
                        alert("error");
                        }
                });
            });
        });
    </script>
</head>
<body>
    <input id="btn" type="button" value="getvalue">
</body>
</html>

可传值list

public List<User> showUser(){
List list = new ArrayList();
User u1=new User("1","zhangsan");
User u2=new User("1","zhangsan");
list.add(u1);
list.add(u2);
return list;
}

取值是data[index]. 取值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值