1. 首页
  2. 软件开发
  3. SpringMVC——相关注解汇总大全。

SpringMVC——相关注解汇总大全。

  • 发布于 2024-08-17
  • 0 次阅读

Spring MVC中的注解在开发中起到了简化配置和提高开发效率的作用。下面介绍一些常用的注解。

  1. @Controller :用于标识一个类为Spring MVC的Controller,处理请求并返回响应。

  2. @RequestMapping:用于映射请求URL到处理器方法,可以用在类级别和方法级别。

  3. @RequestParam :用于绑定请求参数到方法参数,可以指定参数名和是否必需等属性。

  4. @PathVariable:用于绑定URL模板变量到方法参数。

  5. @ResponseBody :用于将方法的返回值直接作为HTTP响应的内容返回,而不是通过视图解析器解析为视图。

  6. @ModelAttribute:用于将方法的返回值绑定到Model中,使其在视图中可以访问。

  7. @SessionAttributes :用于指定哪些模型属性需要存储到会话中,通常与@ModelAttribute一起使用。

  8. @InitBinder:用于初始化数据绑定器,通常用于自定义数据绑定规则。

  9. @ExceptionHandler :用于处理Controller中的异常,可以指定处理特定异常类型的方法。

  10. @ResponseStatus :用于指定响应的HTTP状态码和原因。

  11. @CrossOrigin :用于处理跨域请求,指定允许跨域访问的域名。

  12. @Valid:用于开启参数验证,结合JSR-303/JSR-380标准的验证注解使用。

  13. @RequestBody:用于绑定请求体到方法参数,常用于接收JSON格式的请求数据。

  14. @RequestHeader :用于绑定请求头信息到方法参数。

  15. **@CookieValue**:用于绑定Cookie值到方法参数。

  16. @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