SpringMVC 可以配置为处理所有请求,但排除静态内容目录吗? [英] Can SpringMVC be configured to process all requests, but exclude static content directories?

查看:39
本文介绍了SpringMVC 可以配置为处理所有请求,但排除静态内容目录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我映射我的 spring 应用程序来处理所有传入的请求 ('/*'),那么对静态内容的请求将返回 404.例如,对myhost.com/css/global.css"的请求将返回 404,即使资源存在,因为 Spring 拦截了该请求.

If I map my spring application to process all incoming requests ('/*'), then requests for static content return 404's. For example, a request for "myhost.com/css/global.css" would return a 404, even though the resource exists as Spring intercepts the request.

另一种方法是将 SpringMVC 映射到一个子目录(例如'/home/'),但在这种情况下,您必须在应用程序内的所有链接中传递该目录.有没有办法将 SpringMVC 映射到/"并从处理中排除一组目录?

The alternative is to map SpringMVC to a subdirectory (for example '/home/'), but in this case, you must pass this directory in all links within the application. Is there a way to map SpringMVC to '/' and exclude a set of directories from processing?

我当前的 web.xml 配置是:

My current web.xml configuration is:

<servlet>
    <servlet-name>springApp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springApp</servlet-name>
    <url-pattern>/home/*</url-pattern>
</servlet-mapping>

理想情况下,我希望映射如下所示:

Idealy I would like to have the mapping be something like the following:

 <servlet-mapping>
    <servlet-name>springApp</servlet-name>
    <url-pattern>/*</url-pattern>
    <exclude>/css/*,/js/*</exclude>
 </servlet-mapping>

这种事情可能吗?

推荐答案

如果你只想用 Spring 来做到这一点,这是可能的,但有点乱:

If you want to do this with Spring only, it's possible but a bit messy:

  1. 您要么需要使用 SimpleUrlHandlerMapping,您可以为其明确指定应映射到控制器的 URL 模式,或对其进行扩展以支持忽略"URL,如css/**".
  2. 您需要编写自己的HttpRequestHandler 实现基本上由getServletContext().getRequestDsipatcher().include()"调用组成,以原样返回请求的资源.
  3. 您必须将该处理程序注册为上述 SimpleUrlHandlerMapping 的 defaultHandler.
  1. You'll either need to use a SimpleUrlHandlerMapping for which you can explicitly specify URL patterns which should be mapped to controllers OR extend it to support "ignore" URLs like "css/**".
  2. You'll need to write your own HttpRequestHandler implementation that would basically consist of "getServletContext().getRequestDsipatcher().include()" call to return the requested resource as is.
  3. You'll have to register that handler as defaultHandler for the above SimpleUrlHandlerMapping.

所有这些都完成后,所有无法映射到您的控制器的请求将被转发到您的 HttpRequestHandler 并按原样"提供服务.

Once all that is done, all requests that can't be mapped to your controllers will be forwarded to your HttpRequestHandler and served "as is".

这篇关于SpringMVC 可以配置为处理所有请求,但排除静态内容目录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆