我正在尝试实现servlet过滤器来调整Web应用程序中的autharization。但是没有调用过滤器,我找不到原因。
这是我的过滤器实现:
public class LoginFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
LoginBean session = (LoginBean) req.getSession().getAttribute("LoginBean");
String url = req.getRequestURI();
if(session == null || !session.isLogged) {
if(!(url.indexOf("/home/index.xhtml") >= 0)){
resp.sendRedirect(req.getServletContext().getContextPath() + "/home/index.xhtml");
}
else{
chain.doFilter(request, response);
}
} else {
if(session.role == 1) {
if(url.indexOf("/admin/*") >= 0 || url.indexOf("/home/index.xhtml") >=0){
resp.sendRedirect("/user/index.xhtml");
} else if (url.indexOf("/home/logout.xhtml") >= 0){
req.getSession().removeAttribute("LoginBean");
resp.sendRedirect(req.getServletContext().getContextPath() + "/home/index.xhtml");
}
else{
chain.doFilter(request, response);
}
} else {
if(url.indexOf("/user/*") >= 0 || url.indexOf("/home/index.xhtml") >=0){
resp.sendRedirect(req.getServletContext().getContextPath() + "/admin/index.xhtml");
} else if (url.indexOf("/home/logout.xhtml") >= 0){
req.getSession().removeAttribute("LoginBean");
resp.sendRedirect(req.getServletContext().getContextPath() + "/home/index.xhtml");
}
else{
chain.doFilter(request, response);
}
}}}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
此外,这里是过滤器映射:
<filter>
<filter-name>LoggingFilter</filter-name>
<filter-class>com.ibm.club.data.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LogginFilter</filter-name>
<url-pattern>/user/*</url-pattern>
</filter-mapping>
答案 0 :(得分:0)
在尝试了很多东西并进行调试之后,我终于找到了为什么我的servlet过滤器无法正常工作。首先,正如@Ben所提到的,在web.xml文件中应该是“/ ”而不是“/ user / ”。另一个错误是@tt_emrah声明过滤器名称值在web.xml中不匹配。主要错误是由于我对函数“.indexOf()”的误解。我应该使用url.indexOf(“/ admin”)而不是使用url.indexOf(“/ admin / *”)。谢谢大家帮助我。