Spring注解学习 @ResponseBode @RequestBody @PathVariable

2024-02-23 12:08

本文主要是介绍Spring注解学习 @ResponseBode @RequestBody @PathVariable,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。再也不用为了组装协议而劳烦辛苦了!

一、Spring注解@ResponseBody,@RequestBody和HttpMessageConverter

Spring 3.X系列增加了新注解 @ResponseBody@RequestBody

  • @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
  • @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。

HttpMessageConverter接口,需要开启 <mvc:annotation-driven  />
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用 AnnotationMethodHandlerAdaptergetMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>
引用
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter


可以理解为,只要有对应协议的解析器,你就可以通过几行配置,几个注解完成协议——对象的转换工作!

PS:Spring默认的json协议解析由Jackson完成。

二、servlet.xml配置

Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置:
Xml代码   收藏代码
  1. <context:component-scan base-package="org.zlex.json.controller" />  
  2. <context:annotation-config />  
  3. <mvc:annotation-driven />  


三、pom.xml配置

闲言少叙,先说依赖配置,这里以Json+Spring为参考:
pom.xml
Xml代码   收藏代码
  1. <dependency>  
  2.         <groupId>org.springframework</groupId>  
  3.         <artifactId>spring-webmvc</artifactId>  
  4.         <version>3.1.2.RELEASE</version>  
  5.         <type>jar</type>  
  6.         <scope>compile</scope>  
  7.     </dependency>  
  8.     <dependency>  
  9.         <groupId>org.codehaus.jackson</groupId>  
  10.         <artifactId>jackson-mapper-asl</artifactId>  
  11.         <version>1.9.8</version>  
  12.         <type>jar</type>  
  13.         <scope>compile</scope>  
  14.     </dependency>  
  15.     <dependency>  
  16.         <groupId>log4j</groupId>  
  17.         <artifactId>log4j</artifactId>  
  18.         <version>1.2.17</version>  
  19.         <scope>compile</scope>  
  20.     </dependency>  

主要需要 spring-webmvcjackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于 log4j,我还是需要看日志嘛。
包依赖图:

至于版本,看项目需要吧!

四、代码实现

域对象:
Java代码   收藏代码
  1. public class Person implements Serializable {  
  2.   
  3.     private int id;  
  4.     private String name;  
  5.     private boolean status;  
  6.   
  7.     public Person() {  
  8.         // do nothing  
  9.     }  
  10. }  
public class Person implements Serializable {private int id;private String name;private boolean status;public Person() {// do nothing}
}


这里需要一个空构造,由Spring转换对象时,进行初始化。

@ResponseBody,@RequestBody,@PathVariable
控制器:
Java代码   收藏代码
  1. @Controller  
  2. public class PersonController {  
  3.   
  4.     /** 
  5.      * 查询个人信息 
  6.      *  
  7.      * @param id 
  8.      * @return 
  9.      */  
  10.     @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)  
  11.     public @ResponseBody  
  12.     Person porfile(@PathVariable int id, @PathVariable String name,  
  13.             @PathVariable boolean status) {  
  14.         return new Person(id, name, status);  
  15.     }  
  16.   
  17.     /** 
  18.      * 登录 
  19.      *  
  20.      * @param person 
  21.      * @return 
  22.      */  
  23.     @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
  24.     public @ResponseBody  
  25.     Person login(@RequestBody Person person) {  
  26.         return person;  
  27.     }  
  28. }  
@Controller
public class PersonController {/*** 查询个人信息* * @param id* @return*/@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)public @ResponseBodyPerson porfile(@PathVariable int id, @PathVariable String name,@PathVariable boolean status) {return new Person(id, name, status);}/*** 登录* * @param person* @return*/@RequestMapping(value = "/person/login", method = RequestMethod.POST)public @ResponseBodyPerson login(@RequestBody Person person) {return person;}
}


备注: @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的 {id}/{name}/{status}@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。 这是restful式风格。
如果映射名称有所不一,可以参考如下方式:

Java代码   收藏代码
  1. @RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
  2. public @ResponseBody  
  3. Person porfile(@PathVariable("id"int uid) {  
  4.     return new Person(uid, name, status);  
  5. }  
	@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)public @ResponseBodyPerson porfile(@PathVariable("id") int uid) {return new Person(uid, name, status);}


  • GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
  • POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
  • @ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。


做个页面测试下:
JS
Js代码   收藏代码
  1. $(document).ready(function() {  
  2.     $("#profile").click(function() {  
  3.         profile();  
  4.     });  
  5.     $("#login").click(function() {  
  6.         login();  
  7.     });  
  8. });  
  9. function profile() {  
  10.     var url = 'http://localhost:8080/spring-json/json/person/profile/';  
  11.     var query = $('#id').val() + '/' + $('#name').val() + '/'  
  12.             + $('#status').val();  
  13.     url += query;  
  14.     alert(url);  
  15.     $.get(url, function(data) {  
  16.         alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
  17.                 + data.status);  
  18.     });  
  19. }  
  20. function login() {  
  21.     var mydata = '{"name":"' + $('#name').val() + '","id":"'  
  22.             + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
  23.     alert(mydata);  
  24.     $.ajax({  
  25.         type : 'POST',  
  26.         contentType : 'application/json',  
  27.         url : 'http://localhost:8080/spring-json/json/person/login',  
  28.         processData : false,  
  29.         dataType : 'json',  
  30.         data : mydata,  
  31.         success : function(data) {  
  32.             alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
  33.                     + data.status);  
  34.         },  
  35.         error : function() {  
  36.             alert('Err...');  
  37.         }  
  38.     });  

Table
Html代码   收藏代码
  1. <table>  
  2.     <tr>  
  3.         <td>id</td>  
  4.         <td><input id="id" value="100" /></td>  
  5.     </tr>  
  6.     <tr>  
  7.         <td>name</td>  
  8.         <td><input id="name" value="snowolf" /></td>  
  9.     </tr>  
  10.     <tr>  
  11.         <td>status</td>  
  12.         <td><input id="status" value="true" /></td>  
  13.     </tr>  
  14.     <tr>  
  15.         <td><input type="button" id="profile" value="Profile——GET" /></td>  
  16.         <td><input type="button" id="login" value="Login——POST" /></td>  
  17.     </tr>  
  18. </table>  
	<table><tr><td>id</td><td><input id="id" value="100" /></td></tr><tr><td>name</td><td><input id="name" value="snowolf" /></td></tr><tr><td>status</td><td><input id="status" value="true" /></td></tr><tr><td><input type="button" id="profile" value="Profile——GET" /></td><td><input type="button" id="login" value="Login——POST" /></td></tr></table>


四、简单测试

Get方式测试:




Post方式测试:




五、常见错误
POST操作时,我用$.post()方式,屡次失败,一直报各种异常:


引用
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

直接用$.post()直接请求会有点小问题,尽管我标识为 json协议,但实际上提交的 ContentType还是 application/x-www-form-urlencoded。需要使用$.ajaxSetup()标示下 ContentType
Js代码   收藏代码
  1. function login() {  
  2.     var mydata = '{"name":"' + $('#name').val() + '","id":"'  
  3.             + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
  4.     alert(mydata);  
  5.     $.ajaxSetup({  
  6.         contentType : 'application/json'  
  7.     });  
  8.     $.post('http://localhost:8080/spring-json/json/person/login', mydata,  
  9.             function(data) {  
  10.                 alert("id: " + data.id + "\nname: " + data.name  
  11.                         + "\nstatus: " + data.status);  
  12.             }, 'json');  
  13. };  

效果是一样!

这篇关于Spring注解学习 @ResponseBode @RequestBody @PathVariable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/738572

相关文章

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

SpringRetry重试机制之@Retryable注解与重试策略详解

《SpringRetry重试机制之@Retryable注解与重试策略详解》本文将详细介绍SpringRetry的重试机制,特别是@Retryable注解的使用及各种重试策略的配置,帮助开发者构建更加健... 目录引言一、SpringRetry基础知识二、启用SpringRetry三、@Retryable注解

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

SpringValidation数据校验之约束注解与分组校验方式

《SpringValidation数据校验之约束注解与分组校验方式》本文将深入探讨SpringValidation的核心功能,帮助开发者掌握约束注解的使用技巧和分组校验的高级应用,从而构建更加健壮和可... 目录引言一、Spring Validation基础架构1.1 jsR-380标准与Spring整合1

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与