【发布时间】:2014-10-23 04:09:41
【问题描述】:
在我的程序中,/Controller/* 形式的任何 url 都被我的 servlet 映射重定向到 Controller 类。
我尝试为身份验证添加过滤器,如果用户未登录且路径不是/Controller/RegForm,它将重定向到/Controller/RegForm。
问题是因为我的 servlet 映射重定向到 /Controller,过滤器总是将 /Controller 作为路径。
如何同时使用过滤器和 servlet 映射?
这是我的web.xml:
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/Controller/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/Controller/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
我的过滤器:
@WebFilter("/Controller/*")
public class AuthFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
// If you have any <init-param> in web.xml, then you could get them
// here by config.getInitParameter("name") and assign it as field.
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String path = ((HttpServletRequest) request).getServletPath();
if ((session != null && session.getAttribute("student") != null )||(excludeFromFilter(path))) {
chain.doFilter(req, res); // Log
}
else {
response.sendRedirect("/registration-war/Controller/RegForm"); // No logged-in user found, so redirect to login page.
}
}
private boolean excludeFromFilter(String path) {
if (path.equals("/Controller/RegForm")) {
return true; // add more page to exclude here
} else {
return false;
}
}
【问题讨论】:
-
你能告诉我们你的过滤器实现吗?
标签: java servlets filter mapping