基於springmvc的json傳值
阿新 • • 發佈:2019-02-06
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]. 取值