关于Spring MVC中@spring4 responsebodyy怎么知道我需要什么类型

springmvc课堂笔记 2_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
springmvc课堂笔记 2
上传于||暂无简介
阅读已结束,如果下载本文需要使用
想免费下载本文?
下载文档到电脑,查找使用更方便
还剩25页未读,继续阅读
你可能喜欢spring mvc如何实现不使用@ResponseBody注解接收前端ajax请求?-问答-最代码广告加载中,请稍后...&&完spring mvc如何实现不使用@ResponseBody注解接收前端ajax请求?如题, 在controller中的一个方法 &是ajax请求的方法 &无返回值的方法&如果不加@ResponseBody 会提示 xxxx.jsp找不到, 只有加了@ResponseBody springmvc才会认为这是一个ajax请求 &而非需要跳转页面。 &有没有什么办法不使用这个注解在springmvc中还可以使用ajax(在无返回值的方法中)下面是视图解析配置:
&!-- freemarker 视图解析器 --&
&bean id=&freemarkerConfig& class=&org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer&&
&property name=&templateLoaderPath& value=&/WEB-INF/ftl/pages&/&
View resolvers can also be configured with ResourceBundles or XML files. If you need
different view resolving based on Locale, you have to use the resource bundle resolver.
&bean id=&viewResolver& class=&org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver&&
&property name=&cache& value=&true&/&
&property name=&prefix& value=&&/&
&property name=&suffix& value=&.ftl&/&
&property name=&contentType& value=&text/ charset=utf-8& /&
&!-- jsp视图解析器 --&
&bean class=&org.springframework.web.servlet.view.InternalResourceViewResolver&&
&property name=&prefix& value=&/WEB-INF/jsp/&/&
&property name=&suffix& value=&.jsp& /&
&/bean&5个牛币所有回答列表(5)&LV4有2种方式。1.在spring mvc的controller中设置http响应头content type类型为json格式response.setContentType(&application/charset=utf-8&)然后在response中输出json的字符串。此时的controller的方法可以不需要@ResponseBody注解返回json,可以是void2.在spring mvc的view层设置响应头content type类型为json格式,比如jsp中的语法&%@ page language=&java& contentType=&application/ charset=UTF-8& pageEncoding=&UTF-8&%&然后在view中输出json的字符串。其他view层技术大同小异,自己搜索下语法即可最佳答案可以通过获取response对象,然后使用response.write()方法输出,不懂追I问&LV2
//no cache
response.setHeader(&Cache-Control&, &no-cache&);
response.setHeader(&Expires&, &0&);
response.setHeader(&Pragma&, &No-cache&);
byte[] bytes = anyString.getBytes(encoding);
//fixed firefox3 未组织好的错误
response.setContentType(&text/plain&);
response.setContentType(&application/charset=utf-8&);
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
catch (Exception e)
e.printStackTrace();
}&@RepsonseBody 是基于Ognl表达式的,那么你在前台就需要用 '.属性' 如'member.name'的方式来访问,这样造成代码不易维护,改动一点代码,可能造成很难维护的后果所以不用,简单的单体对象可以用return null等等等完等完等等等等完等最热搜索问答话题编程语言基础Web开发数据库开发客户端开发脚本工具游戏开发服务器软硬件开源组件类库相关问答等等完等完完完完等等等等最近浏览暂无贡献等级暂无贡献等级暂无贡献等级暂无贡献等级暂无贡献等级暂无贡献等级暂无贡献等级暂无贡献等级暂无贡献等级扫描二维码关注最代码为好友"/>扫描二维码关注最代码为好友Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable - Snowolf的意境空间! - ITeye技术网站
博客分类:
最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服!
相关参考:
SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。再也不用为了组装协议而劳烦辛苦了!
一、Spring注解@ResponseBody,@RequestBody和HttpMessageConverter
Spring 3.X系列增加了新注解@ResponseBody,@RequestBody
@RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
@ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。
HttpMessageConverter接口,需要开启&mvc:annotation-driven& /&。
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List&HttpMessageConverter&
引用ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
可以理解为,只要有对应协议的解析器,你就可以通过几行配置,几个注解完成协议——对象的转换工作!
PS:Spring默认的json协议解析由Jackson完成。
二、servlet.xml配置
Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置:
&context:component-scan base-package="org.zlex.json.controller" /&
&context:annotation-config /&
&mvc:annotation-driven /&
三、pom.xml配置
闲言少叙,先说依赖配置,这里以Json+Spring为参考:
pom.xml
&dependency&
&groupId&org.springframework&/groupId&
&artifactId&spring-webmvc&/artifactId&
&version&3.1.2.RELEASE&/version&
&type&jar&/type&
&scope&compile&/scope&
&/dependency&
&dependency&
&groupId&org.codehaus.jackson&/groupId&
&artifactId&jackson-mapper-asl&/artifactId&
&version&1.9.8&/version&
&type&jar&/type&
&scope&compile&/scope&
&/dependency&
&dependency&
&groupId&log4j&/groupId&
&artifactId&log4j&/artifactId&
&version&1.2.17&/version&
&scope&compile&/scope&
&/dependency&
主要需要spring-webmvc、jackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于log4j,我还是需要看日志嘛。
包依赖图:
至于版本,看项目需要吧!
四、代码实现
public class Person implements Serializable {
public Person() {
// do nothing
这里需要一个空构造,由Spring转换对象时,进行初始化。
@ResponseBody,@RequestBody,@PathVariable
@Controller
public class PersonController {
* 查询个人信息
* @param id
@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)
public @ResponseBody
Person porfile(@PathVariable int id, @PathVariable String name,
@PathVariable boolean status) {
return new Person(id, name, status);
* @param person
@RequestMapping(value = "/person/login", method = RequestMethod.POST)
public @ResponseBody
Person login(@RequestBody Person person) {
备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}与@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。 这是restful式风格。
如果映射名称有所不一,可以参考如下方式:
@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)
public @ResponseBody
Person porfile(@PathVariable("id") int uid) {
return new Person(uid, name, status);
GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
@ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。
做个页面测试下:
JS
$(document).ready(function() {
$("#profile").click(function() {
profile();
$("#login").click(function() {
function profile() {
var url = 'http://localhost:8080/spring-json/json/person/profile/';
var query = $('#id').val() + '/' + $('#name').val() + '/'
+ $('#status').val();
alert(url);
$.get(url, function(data) {
alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "
+ data.status);
function login() {
var mydata = '{"name":"' + $('#name').val() + '","id":"'
+ $('#id').val() + '","status":"' + $('#status').val() + '"}';
alert(mydata);
type : 'POST',
contentType : 'application/json',
url : 'http://localhost:8080/spring-json/json/person/login',
processData : false,
dataType : 'json',
data : mydata,
success : function(data) {
alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "
+ data.status);
error : function() {
alert('Err...');
&td&id&/td&
&td&&input id="id" value="100" /&&/td&
&td&name&/td&
&td&&input id="name" value="snowolf" /&&/td&
&td&status&/td&
&td&&input id="status" value="true" /&&/td&
&td&&input type="button" id="profile" value="Profile——GET" /&&/td&
&td&&input type="button" id="login" value="Login——POST" /&&/td&
四、简单测试
Get方式测试:
Post方式测试:
五、常见错误
POST操作时,我用$.post()方式,屡次失败,一直报各种异常:
引用 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-charset=UTF-8' not supported
直接用$.post()直接请求会有点小问题,尽管我标识为json协议,但实际上提交的ContentType还是application/x-www-form-urlencoded。需要使用$.ajaxSetup()标示下ContentType。
function login() {
var mydata = '{"name":"' + $('#name').val() + '","id":"'
+ $('#id').val() + '","status":"' + $('#status').val() + '"}';
alert(mydata);
$.ajaxSetup({
contentType : 'application/json'
$.post('http://localhost:8080/spring-json/json/person/login', mydata,
function(data) {
alert("id: " + data.id + "\nname: " + data.name
+ "\nstatus: " + data.status);
}, 'json');
效果是一样!
详见附件!
相关参考:
下载次数: 1664
浏览 174804
& 上一页 1
浏览: 2476275 次
来自: 北京
keytool -import -alias www.zlex ...
首都师大引用[align=left][/align]
关闭的时候容易误杀其他的tomcat 修改成 pid=`ps
System.out.println(Base64. ...&&国之画&&&&&&
版权所有 京ICP备号-2
迷上了代码!随笔 - 896&
评论 - 100&
&&&&&&&&&&&
Spring的@RequestBody非常牛x,可以将提交的json直接转换成POJO对象。
正好今天有这样的需求,使用一下,结果一直报415,十分头疼。
HTTP 415 错误&&&不支持的媒体类型(Unsupported media type)
我的angularJs是这样写的
$http({method: "POST",
headers: {'Content-type': 'application/charset=UTF-8'},
data: scope.$modelValue})
.success(function(data, status) {
// success handle code
.error(function(data, status) {
// error handle code
url与scope.$modelValue都是项目中的代码,在这里占个坑,scope.$modelValue是一个js对象,会被angularJs转换成json字符串,
反复看angularJs的文档,又抓包分析,确认js没有问题。
在网上一查貌似是Spring的问题,有的网友说需要在*-servlet.xml中增加&mvc:annotation-driven /&,一看我的项目没加,立刻加上。
当然还需要加上mvc的xml命名空间,否则该配置无法解析。
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
&mvc:annotation-driven /&会自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdapter的getMessageConverts()方法来获取转换器的一个集合 List&HttpMessageConverter&
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
对于json的解析就是通过MappingJacksonHttpMessageConverter转换器完成的。
只添加&mvc:annotation-driven /&还不行,需要在classpath环境中能找到Jackson包,用maven配置如下
&dependency&
&groupId&org.codehaus.jackson&/groupId&
&artifactId&jackson-mapper-asl&/artifactId&
&version&1.9.8&/version&
&type&jar&/type&
&scope&compile&/scope&
&/dependency&
至此问题解决,附上Spring代码
@RequestMapping(value = "/testjson", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public void testJson(@RequestBody JsonInfo jsonInfo,
HttpServletRequest request, HttpServletResponse response)
//handle jsonInfo object instance
&从下文得到帮助,对作者表示感谢:)
/blog/1628861
阅读(...) 评论()

我要回帖

更多关于 spring responsebody 的文章

 

随机推荐