返回json用“@responsebody”注解,“@responsebody”是作用在方法上的,“@responsebody”表示该方法的返回结果直接写入“http response body”中。
本篇文章将介绍两种示例进行json返回注解方式演示。
示例1
@responsebody是作用在方法上的,@responsebody 表示该方法的返回结果直接写入 http response body 中,一般在异步获取数据时使用【也就是ajax】,在使用 @requestmapping后,返回值通常解析为跳转路径,但是加上 @responsebody 后返回结果不会被解析为跳转路径,而是直接写入 http response body 中。 比如异步获取 json 数据,加上 @responsebody 后,会直接返回 json 数据。@requestbody 将 http 请求正文插入方法中,使用适合的 httpmessageconverter 将请求体写入某个对象。
下面的部分位于spring-mvc.xml或者dispatcherservlet-servlet.xml中 (spring 3.0中servletname-servlet.xml替代了spring-mvc.xml)
<!-- 用于将对象转换为 json --> <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.method.annotation.requestmappinghandleradapter"> <property name="messageconverters"> <list> <ref bean="stringconverter" /> <ref bean="jsonconverter" /> </list> </property> </bean>
在对应的controller中:
@requestmapping(value=/login,method=requestmethod.post) public @responsebody user login(string username,string password){ user user = userservice.login(username, password); return user; }
这里我使用的jackson包:
(1)jackson-core 2.5.0
(2)jackson-databind 2.5.0
(3)jackson-annotations 2.5.0
导入后build path;
警告:若用hibernate等orm工具生成的pojo类,一对一,对多等关系可能会输出无限循环的json:
需要使用在pojo类中导入com.fasterxml.jackson.annotation.jsonignore,并为需要屏蔽的类添加@jsonignore注解,这样被注解的属性就不会出现在json中了。
示例2
@responsebody @requestmapping(value = /login) public modelandview ajaxlogin(model model,user user,httpservletrequest request, httpsession session){ string errormessage=logincommon(model, user, request, session); map map=new hashmap(); if(valuewidget.isnullorempty(errormessage)){ map.put(constant2.ajax_login_result, success); }else{ map.put(constant2.ajax_login_result, failed); } map.put(error, errormessage); model.addattribute(user, null); return new modelandview(new mappingjacksonjsonview(),map); }
或者
model.addattribute(user, user1);
运行结果:
以上就是返回json用什么注解的详细内容。