@RequestMapping的使用以及其中的name属性解释

  • 接受前端发送的post请求
    //发送请求方式为post请求,则可以正常映射
//    @RequestMapping(value = "/user/login",method = {RequestMethod.POST})
    @PostMapping(value={"/user/login"})
    public String userLogin(){
        System.out.println("处理登录业务");
        return "ok";
    }

@RequestMapping(value = "/user/login",method = {RequestMethod.POST})等价与@PostMapping(value={"/user/login"})
因为@PostMapping,使用该注解时,不需要指定method属性,因为它默认采用的就是POST处理方式;类似的还用
GetMapping:要求前端必须发送get请求
PutMapping:要求前端必须发送put请求
DeleteMapping:要求前端必须发送delete请求
PatchMapping:要求前端必须发送patch请求

  • 前端html代码
***
<body>
<!--发送POST请求-->
<form th:action="@{/user/login}" method="post">
    用户名: <input type="text" name="username"/><br>
    密码: <input type="password" name="password"/><br>
    <input type="submit" value="登录">
</form>
</body>
</html>


在Spring MVC中,@RequestMapping注解用于映射web请求到特定的处理方法。这个注解有多个属性,其中之一就是name。name属性通常用于为映射提供一个名称,这个名称可以在日志、文档或其他需要引用这个映射的地方使用。
在Spring MVC的上下文中,这允许你为特定的@RequestMapping映射指定一个名称,例如:

@RequestMapping(value = "/hello", method = RequestMethod.GET, name = "helloEndpoint")
public String hello() {
    // ...
    return "hello";
}

在这个例子中,/hello的GET请求被映射到hello()方法,并且这个映射有一个名为helloEndpoint的名称。

然而,需要注意的是,name属性在Spring MVC的@RequestMapping注解中并不是核心功能的一部分,并且在所有场景下都不一定被使用或支持。在某些情况下,它可能只是用于内部引用或日志记录。

此外,由于@RequestMapping可以映射到不同的HTTP方法(如GET、POST、PUT等),Spring团队还创建了特定的注解(如@GetMapping、@PostMapping等)作为@RequestMapping的简化版本。这些特定的注解通常没有name属性,因为它们的用途更加明确,并且通常不需要额外的名称来区分。但是,你仍然可以使用@RequestMapping并提供name属性,如果你认为这样做有帮助的话。

  • @RequestMapping注解的method属性是一个RequestMethod类型的数组,用于指定该映射应该匹配哪些HTTP方法。如果你不提供这个属性,那么默认的行为是匹配所有的HTTP方法。
posted @ 2024-07-01 10:20  文采杰出  阅读(3)  评论(0编辑  收藏  举报