一、導入架包和配置web.xml
除了導入SPringMVC的基本架包外還需要導入以下幾個架包
二、在適配器中配置信息轉換器,對異步處理
在適配器中配置信息轉換器,對異步處理出錯後的信息處理(注意Spring3和Spring4的類名不同,架包也不同)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
<!-- 配置掃描器 -->
<context:component-scan base-package="com.mingde"></context:component-scan>
<!-- 配置映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<!-- 配置適配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!-- 配置信息轉換器,對異步處理出錯的信息處理(信息轉換處理) -->
<property name="messageConverters">
<list>
<!-- 映射json的信息轉換 -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
</beans>
三、控制層
public @ResponseBody List<Student> query(@RequestBody student stu)throws Exception{
內容返回需要的內容,如集合
}
若用的是ajax則用上面的方法,若用的是post請求則用下面的方法(少了個@RequestBody)
public @ResponseBody List<Student> query(student stu)throws Exception{
內容返回需要的內容,如集合
}
post異步,服務端只需使用@Response註解,將java對象轉成json串返回給客戶端即可,因爲在客戶端是使用key/value的形式傳數據的,而不是json串,所以不需要@Request註解
@RequestBody:將頁面對象的json對象轉換爲java對象傳給後臺
@ResponseBody:將後臺的java對象轉換爲json對象響應給頁面
四、JSP頁面
SpringMVC的異步加載分爲2種,一種是$.ajax({})另一種是$.post()
①$.ajax({})
客戶端用json字符串傳送數據到服務端
$.ajax({
type:'post',
data:'{"sname":"張三","性別":"男"}', //注意:這裏的json字符串外面必須定義爲單引號,否則無法正常使用 '{"":""}'
url:"地址路徑",
contentType:"application/json;charset=utf-8",
success:function(data){
$.each(data,function(i,v){……內容……})
}
})
②$.post()
客戶端用key/value鍵值對傳送數據到服務端
$.post(
'地址路徑',
"sname="+sname+"&sex="+sex+"&age=18", //如果有多個參數則用&號
function(data){
$.each(data,function(i,v){……內容……})
}
)