抱歉,如果你觉得这个问题很愚蠢......我是 Spring 框架的新手。我花了几个小时寻找答案......
根据 Spring Framework 官方文档,您可以使用 name
属性为 RequestMapping
注释分配名称。
所以问题是给路由映射命名有什么意义?
在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/