多年经验大佬用2000字透彻解析SpringMVC的常用注解及相关示例

360影视 动漫周边 2025-04-28 13:42 2

摘要:Spring MVC框架提供了大量的注解,如请求注解、参数注解、响应注解及跨域注解等。这些注解提供了解决HTTP请求的方案。本节主要讲解Spring MVC的常用注解及相关示例。

Spring MVC框架提供了大量的注解,如请求注解、参数注解、响应注解及跨域注解等。这些注解提供了解决HTTP请求的方案。本节主要讲解Spring MVC的常用注解及相关示例。

请求注解声明在类或者方法中用于声明接口类或者请求方法的类型。

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})。

参数注解可以对方法的请求参数进行注解,用于获取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代码如下:

language="java" %>

Title

hi ,${name}

有时接口请求的业务处理逻辑会产生异常,为了全局统一异常处理,返回同一个异常页面,可以使用@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页面的示例代码如下:

language="java" %>

Title

hi,error

后台服务器如果要满足多个客户端的访问,则需要设置跨域访问。@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);

}

}

请求跳转可以分为“主动跳转”“被动跳转”,其中,“被动跳转”又称为“重定向”。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";

}

}

来源:大数据架构师

相关推荐