如何设置 Spring 3 MVC 控制器以映射到除以 css/、js/ 或 img/ 开头的任何 URI
在我当前的项目中,我们使用 Spring 3 MVC,并且需要实现干净的 URL - 例如 /category/subcategory/id。因此,我们将 DispatchServlet 映射到任何 URL,如下所示:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
我们希望对此应用程序的所有请求现在都通过一个控制器的一种方法。因此,该方法作为注释,例如:
@RequestMapping("/**")
然而,这实际上映射了所有内容(当然),包括对静态资源的请求,例如 img/、js/ 和 css/ 中的内容。有没有一种方法可以排除这些包含目录的静态资源,同时使用一个 @RequestMapping 注释捕获其他任何内容?
On my current project we're using Spring 3 MVC and have a requirement to implement clean URLs - something like /category/subcategory/id. So we've mapped the DispatchServlet to any URL like this:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
We'd like all requests to this application to go through one method of one controller for now. So that method as an annotation like:
@RequestMapping("/**")
However this literally maps everything (of course), including requests to what should be static resources, like things in img/, js/ and css/. Is there a way we can exclude these static resource containing directories while capturing anything else with the one @RequestMapping annotation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案是将 @RequestMapping 注释移至类级别,而不是方法级别。然后使控制器实现控制器,并将控制器的逻辑转移到所需的handleRequest方法。
无论出于何种原因,这都可以正常工作。我对 Spring MVC 的内部逻辑还没有足够的了解,无法准确理解它为何有效,但它确实有效。我本来希望有一种更透明和“Spring”的方式来做到这一点。
The solution turned out to be to move the @RequestMapping annotation to the class level, as opposed to the method. The Controller was then made to implement Controller and the controller's logic was shifted to the required handleRequest method.
For whatever reason this works fine. I don't yet understand enough about Spring MVCs internal logic to understand exactly why it works but it does. I'd have hoped there'd be a more transparent and "Spring" way to do it.
我不确定这是否有效,但您可以尝试为每种文件类型(*.js、*.css 等)添加类似的内容:
I'm not sure if this will work, but you could try adding something like this for each file type (*.js, *.css, etc.):