转发:https://www.iteye.com/blog/wiselyman-2214290

3.1 REST

  • REST:Representational State Transfer;
  • REST是一种数据导向web service,相对于SOAP是一种操作操作和处理导向的web service;
  • Spring为对REST的支持提供了@RestController;
    • 在没有@RestController可以通过@Controller,@ResponseBody组合实现REST控制器;
    • 但是我们经常会使用@ResponseBody这样很麻烦,且易忘记;
    • 使用@RestController替代@Controller,我们就不用使用@ResponseBody;
  • REST支持的http method(通过@RequestMapping的method属性控制)
    • POST:新增
    • GET:读取
    • PUT/PATCH:更新
    • DELETE:删除
  • produces的内容是指定返回的媒体类型让浏览器识别

    • 如返回text/plain的话,浏览器上的js回掉拿到的是字符串,需要自己转换对象;
    • 如返回application/json的话,浏览器上的js拿到的就是js对象而不是字符串,就不需要进行转换;
  • 本例演示向控制器提交json数据,返回结果分别为json和xml格式;

3.2 示例

3.2.1 @RestController源码

从@RestController看出,@RestController是一个元注解,组合了@Controller,@ResponseBody,相当于同时使用了@Controller @ResponseBody

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Controller
  5. @ResponseBody
  6. public @interface RestController {
  7.  
  8. /**
  9. * The value may indicate a suggestion for a logical component name,
  10. * to be turned into a Spring bean in case of an autodetected component.
  11. * @return the suggested component name, if any
  12. * @since 4.0.1
  13. */
  14. String value() default "";
  15.  
  16. }

3.2.2 代码

  • 添加jackson依赖

jackson-dataformat-xml依赖jackson-bind,这样我们能同时返回xml和json

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.dataformat</groupId>
  3. <artifactId>jackson-dataformat-xml</artifactId>
  4. <version>2.5.3</version>
  5. </dependency>

若只需返回json数据(大多数项目都是这样),将上面依赖更换为

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.5.3</version>
  5. </dependency>
  • 传值对象
  1. package com.wisely.web;
  2.  
  3. public class DemoObj {
  4. private Long id;
  5. private String name;
  6. //此处一定要有空构造,不然会有400 bad request,主要是jackson将json参数转换为对象需要
  7. public DemoObj() {
  8. super();
  9. }
  10. public DemoObj(Long id, String name) {
  11. super();
  12. this.id = id;
  13. this.name = name;
  14. }
  15. public Long getId() {
  16. return id;
  17. }
  18. public void setId(Long id) {
  19. this.id = id;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27.  
  28. }
  • DemoMVCConfig注册静态资源
  1. // 静态资源映射
  2. @Override
  3. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  4. registry.addResourceHandler("/js/**").addResourceLocations("/js/");
  5. }
  • 控制器
  1. package com.wisely.web;
  2.  
  3. import org.springframework.web.bind.annotation.RequestBody;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6.  
  7. @RestController
  8. @RequestMapping("/api")
  9. public class RESTController {
  10. @RequestMapping(value = "/getjson",produces={"application/json;charset=UTF-8"})
  11. public DemoObj getjson(@RequestBody DemoObj obj){
  12. return new DemoObj(obj.getId()+1, obj.getName()+"yy");
  13. }
  14. @RequestMapping(value = "/getxml",produces={"application/xml;charset=UTF-8"})
  15. public DemoObj getxml(@RequestBody DemoObj obj){
  16. return new DemoObj(obj.getId()+1, obj.getName()+"yy");
  17. }
  18.  
  19. }
  • 页面代码
  1. <script type="text/javascript" src="<c:url value="/js/jquery.js" />"></script>
  2. <script type="text/javascript">
  3. var json = {"id":456,"name":"phy"};
  4.  
  5. $.ajax({
  6. url: "api/getjson",
  7. data: JSON.stringify(json),
  8. type:"POST",
  9. contentType:"application/json",
  10. success: function(data){
  11. console.log(data);
  12. }
  13. });
  14. $.ajax({
  15. url: "api/getxml",
  16. data: JSON.stringify(json),
  17. type:"POST",
  18. contentType:"application/json",
  19. success: function(data){
  20. console.log(data);
  21. }
  22. });
  23. </script>
  • 结果

03点睛Spring MVC 4.1-REST的更多相关文章

  1. 02点睛Spring MVC 4.1-@RequestMapping

    转发地址:https://www.iteye.com/blog/wiselyman-2213907 2.1 @RequestMapping @RequestMapping是SpringMVC的核心注解 ...

  2. 01点睛Spring MVC 4.1-搭建环境

    转发:https://www.iteye.com/blog/wiselyman-2213906 1.1 简单示例 通篇使用java config @Controller声明bean是一个控制器 @Re ...

  3. 06点睛Spring MVC 4.1-文件上传

    6.1 文件上传 在控制器参数使用@RequestParam("file") MultipartFile file接受单个文件上传; 在控制器参数使用@RequestParam(& ...

  4. 05点睛Spring MVC 4.1-服务器端推送

    转发:https://www.iteye.com/blog/wiselyman-2214626 5.1 服务器端推送 SSE(server send event)是一种服务器端向浏览器推送消息的技术, ...

  5. 04点睛Spring MVC 4.1-拦截器

    转发地址:https://www.iteye.com/blog/wiselyman-2214292 4.1 拦截器 拦截器实现了对每一个请求处理之前和之后进行相关的处理,类似于Servlet的filt ...

  6. 08点睛Spring MVC4.1-Spring MVC的配置(含自定义HttpMessageConverter)

    8.1 配置 Spring MVC的配置是通过继承WebMvcConfigurerAdapter类并重载其方法实现的; 前几个教程已做了得配置包括 01点睛Spring MVC 4.1-搭建环境 配置 ...

  7. 07点睛Spring MVC4.1-ContentNegotiatingViewResolver

    转发地址:https://www.iteye.com/blog/wiselyman-2214965 7.1 ContentNegotiatingViewResolver ContentNegotiat ...

  8. Spring MVC学习总结(2)——Spring MVC常用注解说明

        使用Spring MVC的注解及其用法和其它相关知识来实现控制器功能. 02     之前在使用Struts2实现MVC的注解时,是借助struts2-convention这个插件,如今我们使 ...

  9. 09点睛Spring MVC4.1-异步请求处理(包含兼容浏览器的服务器端推送)

    转发地址:https://www.iteye.com/blog/wiselyman-2215852 9.1 异步请求处理 Servlet 3开始支持异步请求处理 Spring MVC 3.2开始支持S ...

随机推荐

  1. python -- 连接 orclae cx_Oracle的使用

    # 如果报错参考的资料 https://blog.csdn.net/white_xuqin/article/details/82878860 场景再现: python-cx_oracle报错" ...

  2. 洛谷 P1199 三国游戏 题解

    每日一题 day18 打卡 Analysis 贪心 假如小A先选最大的[5,4],虽然电脑必须选一个破坏, 我们可以理解为5和4都属于小A的,假如后面未被破坏的最大值无论是和5相关还是和4相关,必然还 ...

  3. 执行DTS包将excel导入数据库

    利用ssms生成dtsx文件,必须以32bit执行,到路径执行C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn > dtexec ...

  4. Vim初学

    实现G++编译 1,首先下载安装MinGW,下载地址在http://sourceforge.net/projects/mingw/.这个是边下载边安装的,下载完成即安装完成.我的安装目录是G:\Min ...

  5. ArcGIS Enterprise 10.7.1新特性:批量发布服务

    ArcGIS Enterprise 10.7.1提供了批量发布GIS服务的功能,能大大简化GIS系统管理员的工作量. 作为发布人员和管理人员,支持向Portal for ArcGIS添加云存储.文件共 ...

  6. LeetCode之打家劫舍

    1. 问题 在一条直线上,有n个房屋,每个房屋中有数量不等的财宝,有一个盗 贼希望从房屋中盗取财宝,由于房屋中有报警器,如果同时从相邻的两个房屋中盗取财宝就会触发报警器.问在不触发报警器的前提下,最多 ...

  7. VMware虚拟机找不到USB设备该怎么办?

    VMware虚拟机找不到USB设备该怎么办?打开虚拟机发现竟然找不到usb设备,键盘和鼠标都是usb的,这该怎么办呢?出现这个问题是因为VMUSBArbService服务没有开启,下面分享开启的方法 ...

  8. Chapter One

    spring-boot-starter-parent spring-boot-starter-parent是一个特殊的Starter,提供了Maven的默认配置,同时还提供了dependency-ma ...

  9. T-MAX-冲刺总结

    T-MAX-冲刺总结 这个作业属于哪个课程 班级链接 这个作业要求在哪里 作业要求的链接 团队名称 T-MAX 这个作业的目标 冲刺总结 作业的正文 T-MAX-冲刺总结 其他参考文献 面向B站,百度 ...

  10. http code 有的意思

      http code 有的意思,发现了一个图,感觉挺有意思的.   文章来源:刘俊涛的博客 欢迎关注公众号.留言.评论,一起学习. _________________________________ ...