如何设置 Spring 3 MVC 控制器以映射到除以 css/、js/ 或 img/ 开头的任何 URI

发布于 2025-01-04 07:03:50 字数 516 浏览 1 评论 0原文

在我当前的项目中,我们使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾城°AllureLove 2025-01-11 07:03:50

解决方案是将 @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.

来日方长 2025-01-11 07:03:50

我不确定这是否有效,但您可以尝试为每种文件类型(*.js、*.css 等)添加类似的内容:

<servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.js</url-pattern>
</servlet-mapping>

I'm not sure if this will work, but you could try adding something like this for each file type (*.js, *.css, etc.):

<servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.js</url-pattern>
</servlet-mapping>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文