java - Spring框架中 `name`注解的 `RequestMapping`属性有哪些用例?

标签 java spring spring-mvc

抱歉,如果你觉得这个问题很愚蠢......我是 Spring 框架的新手。我花了几个小时寻找答案......

根据 Spring Framework 官方文档,您可以使用 name 属性为 RequestMapping 注释分配名称。

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#name--

所以问题是给路由映射命名有什么意义?

在Symfony框架中,我们可以使用映射名称来生成URL。

class BlogController
{
    /**
     * @Route(name="BlogComments", path="blog/{blog}/comments/{page}")
     */
    public function listBlogComments(Blog blog, page)
    {
        ...
    }
}

然后我们可以根据路由名称生成一个 URL。

// This will generate a string "blog/27/comments/1".
$url = $this->generateUrl('BlogComments', [
    'blog' => 27,
    'page' => 1
]);

这要归功于 Symfony\Component\Routing\Router 组件。

在Spring框架中 Controller 类可以像下面这样编写。

@Controller
@ResponseBody
class BlogController {

    @RequestMapping(name="BlogComments", path="blog/{blog}/comments/{page}")
    public List<Comment> listBlogComments(@PathVariable Blog blog, @PathVariable Long page) {
        ...
    }
}

现在如何根据映射名称(在本例中为 "BlogComments")生成 URL?是否有像 Symfony 框架中那样可用的 Spring 组件或服务?还有哪些其他可能的用例?

最佳答案

来自文档:

public abstract String name

Assign a name to this mapping. Supported at the type level as well as at the method level! When used on both levels, a combined name is derived by concatenation with "#" as separator.

关键时刻是在两个级别上使用时

因此,您还应该为 Controller 指定一个名称,它应该开始工作。

@Controller
@ResponseBody
@RequestMapping(name = "AdminController")
class BlogController {

    @RequestMapping(name="BlogComments", path="blog/{blog}/comments/{page}")
    public List<Comment> listBlogComments(@PathVariable Blog blog, @PathVariable Long page) {
        ...
    }
}

然后你可以使用#访问URL

<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>

<a href="${s:mvcUrl('AdminController#BlogComments').arg("1","123").build()}">Get Person</a>

Applications can build a URL to a controller method by name with the help of the static method MvcUriComponentsBuilder#fromMappingName or in JSPs through the "mvcUrl" function registered by the Spring tag library.

关于java - Spring框架中 `name`注解的 `RequestMapping`属性有哪些用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61152283/

相关文章:

java - 如何在不将对象作为字段包含在内的情况下使项目中的所有类都可以使用该对象?

java - 使用扩展类

java.lang.UnsupportedOperationException 在 javax.faces.context.FacesContext.isReleased(FacesContext.java :609)

java - 尽管以表单形式发送 CSRF token ,但不支持 Spring Security CSRF 405 方法 POST

hibernate 异常 : Connection Pool exhausted error after Spring upgrade

JavaFX JDK 9.0.4 ListView celFactory 添加空单元格

java - 朝向触摸点旋转对象

java - 接受 GET 时未接受 POST 请求

java - Spring、Hibernate、JUnit 带注释的实体

spring-mvc - 如何使用 Feign 客户端设置请求头?