SpringMVC注解(@RequestMapping,@ResponseBody,@RequestBody等)

SpringMVC注解

2021/5/8 周六

学习内容:@RequestMapping,@GetMapping,@PostMapping,@PathVariable,@ResponseBody,@RestController,@RequestBody等。

如有错误,欢迎在评论区指出,非常感谢!


一、@RequestMapping

@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。

  • 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;
  • 用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法。

最常用是标注在方法上,表明哪个具体的方法来接受处理某次请求。

1. 分类
@GetMapping

@GetMapping用于将HTTP的GET请求映射到特定处理程序方法的注释。

具体来说,@GetMapping是一个作为快捷方式的组合注释,相当于@RequestMapping(method = RequestMethod.GET)。

@PostMapping

@PostMapping用于将HTTP的POST请求映射到特定处理程序方法的注释。

@PostMapping也是一个作为快捷方式的组合注释,相当于@RequestMapping(method = RequestMethod.POST)。

2. 具体用法
@RequestMapping("/system/user")
public class UserController extends BaseController{
	...
	@PostMapping("/list")
	public TableDataInfo list(User user){...}
	...
}

浏览器请求的url为:http://localhost:80/system/user/list 时就会用这个list()方法来处理.

@RequestMapping的value值前后是否有“/”对请求的路径没有影响,即value=“list” 、"/list"、"/list/"其效果是一样的。

2. 属性

@RequestMapping注解有六个属性,下面分成三类进行说明:

  • (1) value & method

value:指定请求的实际url地址,指定的地址可以是URI Template 模式;

method:指定请求的method类型, GET、POST、PUT、DELETE等;

  • (2) consumes & produces

consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

  • (3) params & headers

params: 指定request中必须包含某些参数值时,才让该方法处理。

例:

@RequestMapping(params="action=del")

表示请求参数需包含“action=del”,如:http://localhost:8080/book?action=del 时才处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

例:

@RequestMapping(value="/header/id", headers = "Accept=application/json")

表示请求的URL必须为“/header/id”,且请求头中必须有“Accept =application/json”参数即可匹配。

二、@PathVariable

@PathVariable用于方法参数绑定(绑定URI模板变量值),即将请求URL中的模板变量映射到功能处理方法的参数上。

用在方法的参数列表上。

如:

@GetMapping("/edit/{userId}")
public String edit(@PathVariable("userId") Long userId, ModelMap mmap){
    List<Role> roles = roleService.selectRolesByUserId(userId);
    mmap.put("user", userService.selectUserById(userId));
    mmap.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
    mmap.put("posts", postService.selectPostsByUserId(userId));
    return prefix + "/edit";
}

其实就是取出URI模板中的变量userId作为方法的参数使用。
(URI 模板就是在URI中给定一个变量,然后在映射的时候动态的给该变量赋值。)

三、@ResponseBody

当 Controller 返回的不是html标签的页面,而是其他某种格式的数据时(如json、xml等),使用 @ResponseBody 注解,表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中

一般是在异步获取json数据时使用,用在方法上,通常是在使用 @RequestMapping 后。

@PostMapping("/list")
@ResponseBody
public TableDataInfo list(User user){
    ...
}

使用 @RequestMapping时,返回值通常解析为跳转路径,如果加上 @Responsebody,则返回结果不会被解析为跳转路径,而是通过适当的HttpMessageConverter转换为指定格式后,直接写入Response对象的body数据区。

还有一种常见的情况,就是整个Controller例都没有控制页面跳转的逻辑,只负责传递数据,则可直接在整个Controller前加上 @RestController ,相当于:@RestController = @ResponseBody + @Controller

四、@RequestBody

@RequestBody也是用于方法参数绑定(绑定固定格式的数据xml或json)

可以以String、简单对象、复杂对象,接收前端传递给后端的json字符串中的数据(即请求体中的数据)。

用在方法的参数列表上。

过程:读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析(数据编码格式由header部分的Content-Type指定),然后把相应的数据绑定到要返回的对象上;再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

需要注意

  1. 因为GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交
  2. @RequestBody是通过 无参构造器 new的对象,然后通过set方法设置,如果在实体类中添加了有参构造器,没加无参构造器,接收参数时会出现异常。

主要参考文章
1.https://blog.csdn.net/dingzfeng/article/details/47394441
2.https://www.cnblogs.com/cjeandailynotes/p/10469377.html

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二、实验步骤 1、创建Maven项目并添加SpringMVC依赖 2、在web.xml中配置DispatcherServlet 3、创建Controller类并添加@RequestMapping注解 4、编写业务逻辑方法 5、使用@RequestParam,@RequestBody,@ResponseBody,@PathVariable注解获取请求参数或返回结果 6、启动Tomcat服务器并测试 三、实验代码 1、pom.xml文件中添加SpringMVC依赖 ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.9.RELEASE</version> </dependency> ``` 2、web.xml中配置DispatcherServlet ```xml <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` 3、Controller类中添加@RequestMapping注解 ```java @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/add", method=RequestMethod.POST) @ResponseBody public String addUser(@RequestBody User user){ System.out.println("添加用户:"+user.getName()); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) @ResponseBody public User getUser(@PathVariable int id){ User user = new User(id, "张三", 20); return user; } @RequestMapping(value="/list", method=RequestMethod.GET) public ModelAndView getUserList(){ List<User> userList = new ArrayList<User>(); userList.add(new User(1, "张三", 20)); userList.add(new User(2, "李四", 22)); userList.add(new User(3, "王五", 24)); ModelAndView mav = new ModelAndView(); mav.addObject("userList", userList); mav.setViewName("userList"); return mav; } } ``` 4、编写业务逻辑方法 ```java public class User { private int id; private String name; private int age; //getter和setter方法省略 } ``` 5、使用@RequestParam,@RequestBody,@ResponseBody,@PathVariable注解获取请求参数或返回结果 ```java @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/add", method=RequestMethod.POST) @ResponseBody public String addUser(@RequestBody User user){ System.out.println("添加用户:"+user.getName()); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) @ResponseBody public User getUser(@PathVariable int id){ User user = new User(id, "张三", 20); return user; } @RequestMapping(value="/list", method=RequestMethod.GET) public ModelAndView getUserList(){ List<User> userList = new ArrayList<User>(); userList.add(new User(1, "张三", 20)); userList.add(new User(2, "李四", 22)); userList.add(new User(3, "王五", 24)); ModelAndView mav = new ModelAndView(); mav.addObject("userList", userList); mav.setViewName("userList"); return mav; } } ``` 6、启动Tomcat服务器并测试 访问http://localhost:8080/user/list,可以看到用户列表页面。 访问http://localhost:8080/user/1,可以看到id为1的用户信息。 使用Postman发送POST请求,提交用户信息到http://localhost:8080/user/add。 四、实验总结 通过本次实验,我们学习了SpringMVC的基本使用方法,包括了配置DispatcherServlet、编写Controller类、使用注解获取请求参数或返回结果等。掌握了这些基本知识后,可以更好地进行后续的开发工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值