2.2 Spring MVC 注解
Spring MVC 框架提供了大量的注解,如请求注解、参数注解、响应注解及跨域注解等。这些注解提供了解决 HTTP 请求的方案。本节主要讲解 Spring MVC 的常用注解及相关示例。
2.2.1 请求注解
请求注解声明在类或者方法中用于声明接口类或者请求方法的类型。
1. @Controller 注解
@Controller 注解声明在类中,表示该类是一个接口类。@RestController 也是声明接口类,它是一个组合注解,由 @Controller 与 @ResponseBody 注解组合而成。
2. @RequestMapping 注解
@RequestMapping 注解声明在类或者方法中,可以指定路径、方法(GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS 或 TRACE 等)或参数等。根据不同的请求方法,Spring MVC 还提供了一些更简单的注解,具体如下:
- @GetMapping:相当于 @RequestMapping(method = {RequestMethod.GET})。
- @PostMapping:相当于 @RequestMapping(method = {RequestMethod.POST})。
- @PutMapping:相当于 @RequestMapping(method = {RequestMethod.PUT})。
- @DeleteMapping:相当于 @RequestMapping(method = {RequestMethod.DELETE})。
- @PatchMapping:相当于 @RequestMapping(method = {RequestMethod.PATCH})。
2.2.2 参数注解
参数注解可以对方法的请求参数进行注解,用于获取 HTTP 请求中的属性值。常用的参数注解如下:
- @PathVariable:URL 路径参数,用于将 URL 路径中的参数映射到对应方法的参数中。
- @RequestBody:可以映射请求的 Body 对象。
- @RequestHeader:请求 Header 的映射。
- @CookieValue:用于获取 Cookie 的属性值。
- @SessionAttribute:用于获取 Session 的属性值。
下面给出一个请求注解与参数注解的示例:
//定义 HiController
@RestController
@RequestMapping("/hi")
public class HiController {
//请求路径/hi/mvc/{id}
@RequestMapping("/mvc/{id}")
public ModelAndView sayHi(@PathVariable Integer id){
System.out.println(id);
//定义视图模型
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("say");
modelAndView.addObject("name","mvc");
return modelAndView;
}
}对应的 say.jsp 代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hi ,${name}
</body>
</html>2.2.3 异常注解
有时接口请求的业务处理逻辑会产生异常,为了全局统一异常处理,返回同一个异常页面,可以使用 @ExceptionHandler 注解。@ExceptionHandler 注解声明在方法中,用于提供统一的异常处理。具体的示例代码如下:
public class BaseController {
//统一异常处理
@ExceptionHandler
public String exceptionHandler(HttpServletRequest request,
Exception ex){
request.setAttribute("ex", ex);
return "error";
}
}在以上代码中,用 @ExceptionHandler 声明 exceptionHandler() 方法,如果接口处理有异常,则跳转到 error.jsp 页面。其他接口类继承 BaseController 类的示例代码如下:
@RestController
@RequestMapping("/hi")
public class TestExceptionController extends BaseController {
@RequestMapping("/error")
public ModelAndView sayHi(){
throw new RuntimeException("testExceptionHandler");
}
}为了方便测试,处理方法直接抛出异常,则浏览器跳转到 error.jsp 页面。error.jsp 页面的示例代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hi,error
</body>
</html>2.2.4 跨域注解
后台服务器如果要满足多个客户端的访问,则需要设置跨域访问。@CrossOrigin 注解提供了跨域访问的可能性,它可以声明在类中,也可以声明在方法中。代码如下:
//声明在类中的跨域注解
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
//声明在方法中的跨域注解
@CrossOrigin("https://domain2.com")
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
...
}
}如果要全局配置跨域,则需要实现 WebMvcConfigurer 接口的 addCorsMappings() 方法,代码如下:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//全局配置跨域属性
registry.addMapping("/api/**")
.allowedOrigins("https://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true)
.maxAge(3600);
}
}2.2.5 请求跳转
请求跳转可以分为“主动跳转”“被动跳转”,其中,“被动跳转”又称为“重定向”。Spring MVC 提供了 forword 和 redirect 关键字用于实现主动跳转和重定向,示例代码如下:
@RestController
@RequestMapping("/hi")
public class HiController {
@RequestMapping("/forward")
public String testForward(){
//请求 forward 跳转
return "forward:/hi/error";
}
@RequestMapping("/redirect")
public String testRedirect(){
//请求 redirect 跳转
return "redirect:/hi/error";
}
}绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论