最直接的Ajax处理
Controller示例
@RequestMapping(value = "/hello")
public ModelAndView handleRequest(usermodel um,HttpServletResponse response) throws IOException {
response.setCharacterEncoding("utf-8");
response.getWriter().println("{uuid:'"+um.getUuid()+"',name:'"+um.getName()+"'}");
return null;
}
客户端示例,使用jQuery
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script language="javascript" src="/mvcexample/static/js/jquery-1.3.2.min.js"></script>
<script language="javascript">
$().ready(function(){
$.getJSON('/mvcexample/hello',{uuid:'1',name:'test'},function(data){
alert(data.uuid+","+data.name);
});
});
</script>
</html>
然后就可以启动服务器测试了。
数据绑定@RequestBody/@ResponseBody
@RequestBody
例子:
@RequestMapping(value = "/hello")
public byte[] handleRequest(@RequestBody String body)
@ResponseBody
例子:
@RequestMapping(value = “/hello")
@ResponseBody
public byte[] handleRequest(@RequestBody String body)
注意:他们都只能访问报文体,不能访问报文头
使用@RequestBody/@ResponseBody来支持Ajax
n同时也可以使用@ResponseBody,把要返回的对象自动拼成JSON的格式返回
n当然,需要加入几个jackson的包,这里加入了:
jackson-core-2.1.2.jar、jackson-annotations-2.1.2.jar、jackson-databind-2.1.2.jar
n测试使用的Controller的方法:
@RequestMapping(value = "/hello")
@ResponseBody
System.out.println("the reqBody="+reqBody);
um.setName(um.getName()+",server");
return um;
}
n测试使用的页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html><head><Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script language="javascript" src="/mvcexample/static/js/jquery-1.3.2.min.js"></script>
<script language="javascript">
$().ready(function(){
$.getJSON('/mvcexample/hello',function(data){
alert(data.uuid+","+data.name);
});
});
</script>
n测试使用的Controller方法
@RequestMapping(value = "/hello")
@ResponseBody
System.out.println("the reqBody="+reqBody);
um.setName(um.getName()+",server");
list.add(um);
um2.setUuid("22");
um2.setName("222");
list.add(um2);
return list;
}
n测试使用的页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html><head><Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<script language="javascript" src="/mvcexample/static/js/jquery-1.3.2.min.js"></script>
<script language="javascript">
$().ready(function(){
$.getJSON('/mvcexample/hello',function(data){
$.each(data,function(index,v){
alert("tr="+v.uuid+",v="+v.name);
});
});
});
</script>
使用httpentity/ResponseEntity来支持Ajax
n使用httpentity/ResponseEntity不但能访问到报文体,还可以访问报文头
@RequestMapping(value = "/hello")
public
ResponseEntity<List<usermodel>>handleRequest(httpentity<String> req,usermodel um) {
System.out.println("req headers="+req.getHeaders()+",reqBody="+req.getBody());
um.setName(um.getName()+",server");
list.add(um);
um2.setUuid("22");
um2.setName("222");
list.add(um2);
return ret;
}
对Ajax返回xml的支持
示例的Controller方法
@RequestMapping(value = "/hello")
@ResponseBody
System.out.println("req headers="+req.getHeaders()+",reqBody="+req.getBody());
um.setName(um.getName()+",server");
PhoneNumberModel pnm = new PhoneNumberModel("123","321");
PhoneNumberModel pnm2 = new PhoneNumberModel("2222","333");
List<PhoneNumberModel> tempList = new ArrayList<PhoneNumberModel>();
tempList.add(pnm2);
tempList.add(pnm);
um.setPm(tempList);
return um;
}
n示例的页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html><head><Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<script language="javascript" src="/mvcexample/static/js/jquery-1.3.2.min.js"></script>
<script language="javascript">
$().ready(function(){
$.ajax({
url:'/mvcexample/hello',
type: 'POST',
dataType: 'xml',
data: {uuid:'1',
timeout: 1000,
error: function(){ alert('Error loading XML document'); },
success: function(xml){
$(xml).find("testxml").children("pm").each(function(i){
var uuid=$(this).children("areaCode").text();
var name=$(this).children("phoneNumber").text();
alert("uuid="+uuid+",name="+name);
}); } }); });
</script>
n返回的xml形如
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testxml>
<age>0</age>
<name>test,server</name>
<pm>
<areaCode>2222</areaCode>
<phoneNumber>333</phoneNumber>
</pm>
<pm>
<areaCode>123</areaCode>
<phoneNumber>321</phoneNumber>
</pm>
<uuid>1</uuid>
</testxml>
HttpMessageConverter
n比如前面学的@RequestBody是将Http请求正文插入方法中,其实它就会使用适合的HttpMessageConverter将请求体写入某个对象
n比如前面学的@ResponseBody是将内容或对象作为Http响应正文返回,使用@ResponseBody将会跳过视图处理部分,直接调用合适的HttpMessageConverter,将返回值写入输出流
n现在只要你开启了<mvc:annotation-driven />,它会给AnnotationMethodHandlerAdapter初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter类的getMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>,默认开启的有:
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter<T>
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
Spring是如何寻找最佳的HttpMessageConverter呢?
最基本的方式就是通过请求的accept里面的格式来匹配,如果accept=application/json之类的,就使用json的HttpMessageConverter,如果accept=application/xml之类的,就使用xml的HttpMessageConverter,
内容协商
n什么是内容协商
简单点说,就是同一资源,可以有多种表现形式,比如xml、json等,具体使用哪种表现形式,是可以协商的。
一:根据Http请求的header中的Accept属性的值来判读,比如:
Accept: application/xml 将返回xml格式数据
Accept: application/json 将返回json格式数据
优点:是这种方式是理想的标准方式
缺点:是由于浏览器的差异,导致发送的Accept Header头可能会不一样,从而导致服务器不知要返回什么格式的数据
二:根据扩展名来判断,比如:
/mvc/test.xml 将返回xml格式数据
/mvc/test.json 将返回json格式数据
/mvc/test.html 将返回html格式数据
缺点:丧失了同一URL的多种展现方式。在实际环境中使用还是较多的,因为这种方式更符合程序员的习惯
三:根据参数来判断
/mvc/test?format=xml 将返回xml数据
/mvc/test?format=json 将返回json数据
缺点:需要额外的传递format参数,URL变得冗余繁琐,缺少了REST的简洁风范
n
n需要在spring的配置文件中做配置,示例如下:
<!--1、检查扩展名(如my.pdf);2、检查Parameter(如my?format=pdf);3、检查Accept Header-->
<bean id=
"contentNegotiationManager"class=
"org.springframework.web.accept.ContentNegotiationManagerfactorybean">
<!-- 扩展名至mimeType的映射,即 /user.json => application/json -->
<property name=
"favorPathExtension"value=
"true"/>
<!-- 用于开启 /userinfo/123?format=json 的支持 -->
<property name=
"favorParameter"value=
"true"/>
<property name=
"parameterName"value=
"format"/>
<!-- 是否忽略Accept Header -->
<property name=
"ignoreAcceptHeader"value=
"false"/>
<property name=
"mediaTypes"> <!--扩展名到MIME的映射;favorPathExtension,favorParameter是true时起作用 -->
<value>
ccjson=application/json
ccxml=application/xml
html=text/html
</value>
</property>
<!-- 默认的content type -->
<property name=
"defaultContentType"value=
"text/html"/>
</bean>
<!-- ========================= VIEW定义 ========================= -->
<!-- 内容协商视图解析器;根据客户端不同的请求决定不同的view进行响应 -->
<bean class=
"org.springframework.web.servlet.view.ContentNegotiatingViewResolver"p:order=
"0">
<!-- 内容协商管理器 用于决定media type -->
<property name=
"contentNegotiationManager"ref=
"contentNegotiationManager"/>
<!-- 默认视图 放在解析链最后 -->
<property name=
"defaultviews">
<list>
<bean class=
"org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
<bean class=
"org.springframework.web.servlet.view.xml.MarshallingView">
<property name=
"marshaller">
<bean class=
"org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name=
"packagesToScan"value=
"cn.javass"></property>
</bean>
</property>
</bean>
</list>
</property>
</bean>
<!-- bean name view resolver-->
<bean class=
"org.springframework.web.servlet.view.BeanNameViewResolver"p:order=
"1"/>
<bean id=
"defaultviewResolver"class=
"org.springframework.web.servlet.view.InternalResourceViewResolver"p:order=
"2">
<property name=
"viewClass"value=
"org.springframework.web.servlet.view.JstlView"/>
<property name=
"contentType"value=
"text/html"/>
<property name=
"prefix"value=
"/WEB-INF/jsp/"/>
<property name=
"suffix"value=
".jsp"/>
</bean>
n在mvc:annotation-driven里面配置使用内容协商
<mvc:annotation-driven
validator=
"validator"
conversion-service=
"conversionService"
content-negotiation-manager="contentNegotiationManager"
>
</mvc:annotation-driven>
原文地址:https://www.jb51.cc/ajax/163296.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。