给 Servlet 过滤器提供多个 URL 模式

我正在我的 JSF 应用程序中使用 Servlet 过滤器。我的应用程序中有三组 Web 页面,我想在 Servlet Filter 中检查这些页面的身份验证:

我的文件夹

/Admin/ *.xhtml


/Supervisor/*.xhtml
/Employee/*.xhtml

我在写 web.xml

<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.ems.admin.servlet.LoginFilter</filter-class>
</filter>


<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/Employee/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/Admin/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/Supervisor/*</url-pattern>
</filter-mapping>

而是要求

http://localhost:8080/EMS2/faces/Html/Admin/Upload.xhtml

没有进入过滤器。

我必须为这三个文件夹提供安全保护。

如何解决这个问题?

178803 次浏览

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/faces/Html/Employee/*</url-pattern>
<url-pattern>/faces/Html/Admin/*</url-pattern>
<url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
* Filter implementation class LoginFilter
*/
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
* Servlet implementation class LoginServlet
*/
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
...