一、导入架包和配置web.xml
除了导入SPringMVC的基本架包外还需要导入以下几个架包
web.xml配置详情见SpringMVC的web.xml配置
二、在适配器中配置信息转换器,对异步处理
在适配器中配置信息转换器,对异步处理出错后的信息处理(注意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注解
@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){……内容……})
}
)