在我的程序中,任何形式为/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;
}
}
答案 0 :(得分:1)
使用HttpServletRequest.getServletPath()
返回servlet URL(根据你的servlet映射)"/Controller"
。
您希望path info而不是servlet路径:
返回与客户端发出此请求时发送的URL关联的任何额外路径信息。额外的路径信息在servlet路径之后,但在查询字符串之前,将以&#34; /&#34;开头。字符。
例如,如果您的用户请求"/RegForm"
页面,则会返回/Controller/RegForm
。
String pathInfo = HttpServletRequest.getPathInfo();