Spring MVC中的注解在开发中起到了简化配置和提高开发效率的作用。下面介绍一些常用的注解。
-
@Controller :用于标识一个类为Spring MVC的Controller,
处理请求并返回响应。 -
@RequestMapping:用于映射请求URL到处理器方法,可以用在类级别和方法级别。
-
@RequestParam :用于
绑定请求参数到方法参数,可以指定参数名和是否必需等属性。 -
@PathVariable:用于绑定URL模板变量到方法参数。
-
@ResponseBody :用于将方法的返回值直接作为HTTP响应的内容返回,而
不是通过视图解析器解析为视图。 -
@ModelAttribute:用于将方法的返回值绑定到Model中,使其在视图中可以访问。
-
@SessionAttributes :用于指定哪些模型属性需要
存储到会话中,通常与@ModelAttribute一起使用。 -
@InitBinder:用于初始化数据绑定器,通常用于自定义数据绑定规则。
-
@ExceptionHandler :用于处理Controller中的异常,可以指定
处理特定异常类型的方法。 -
@ResponseStatus :用于指定响应的
HTTP状态码和原因。 -
@CrossOrigin:用于处理跨域请求,指定允许跨域访问的域名。 -
@Valid:用于开启参数验证,结合JSR-303/JSR-380标准的验证注解使用。
-
@RequestBody:用于绑定请求体到方法参数,常用于接收JSON格式的请求数据。
-
@RequestHeader :用于
绑定请求头信息到方法参数。 -
**
@CookieValue**:用于绑定Cookie值到方法参数。 -
@RestController:结合@Controller和@ResponseBody的功能,用于标识一个类为RESTful风格的Controller。
代码如下:
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring MVC!");
return "hello";
}
@RequestMapping(value = "/greet", method = RequestMethod.POST)
@ResponseBody
public String greet(@RequestParam("name") String name) {
return "Hello, " + name + "!";
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String getById(@PathVariable("id") Long id, Model model) {
// 根据id获取数据
return "details";
}
@ModelAttribute
public void commonModelAttributes(Model model) {
model.addAttribute("commonAttribute", "This is a common attribute");
}
}
原文链接: https://blog.csdn.net/2401_82884096/article/details/137997035