java 如何排除/重定向 web.xml 或 Guice servlet 模块中的某些 url 模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7448316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:01:22  来源:igfitidea点击:

How to exclude/redirect certain url pattern in web.xml or Guice servlet module?

javaregexguicedeployment-descriptor

提问by datauser

I need to serve my main application with the url pattern "/*"so this pattern is matched to a Servlet. The problem I am having is now all the css files and images located at "/css/all.css", "/images/" etc are going through this Servlet which is undesirable. I want these files to be directly accessed. What is the better way to handle this situation?

我需要使用 url 模式为我的主应用程序提供服务,"/*"以便此模式与 Servlet 匹配。我现在遇到的问题是位于“/css/all.css”、“/images/”等的所有 css 文件和图像都通过这个不受欢迎的 Servlet。我希望直接访问这些文件。处理这种情况的更好方法是什么?

Note: I am using Guice's Servlet Module to configure the patterns.

注意:我使用 Guice 的 Servlet 模块来配置模式。

Thanks!

谢谢!

采纳答案by Justin Morgan

We need to know specifically which requests should be routed to your servlet, so that we know how to code the rules. I can't tell whether a) all requests except CSS and images should be sent to your servlet, or b) your servlet should only handle requests to a specific set of folders/directories. You will probably want to do one of two things:

我们需要具体知道哪些请求应该路由到您的 servlet,以便我们知道如何编写规则。我不知道是否 a) 除了 CSS 和图像之外的所有请求都应该发送到您的 servlet,或者 b) 您的 servlet 应该只处理对特定文件夹/目录集的请求。您可能想要做以下两件事之一:

Exclude specific folders:

排除特定文件夹:

^/(?!css|images).*

Or include specific folders:

或包含特定文件夹:

^/myservlet/.*

You should change those *symbols to +if, as you indicated in your earlier question, you want to require at least one character after the /in the pattern.

您应该将这些*符号更改为+如果,正如您在之前的问题中所指出的,您希望/在模式中的之后至少需要一个字符。

回答by Jens

This should work for you:

这应该适合你:

Make all your image/css etc resources go through the default servlet. And make a mapping like this:

使您的所有图像/css 等资源都通过默认的 servlet。并进行这样的映射:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.xml</url-pattern>
    <url-pattern>*.html</url-pattern>
    <url-pattern>*.png</url-pattern>
    <url-pattern>*.jpg</url-pattern>
    <url-pattern>*.gif</url-pattern>
    <url-pattern>*.js</url-pattern>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>