要对后台管理文件夹下的所有管理页面进行过滤,阻止未登录的用户访问这些页面,在操作中出现了重定向死循环,经过思考,最终找到了解决办法,现在把代码贴出来。
Filter过滤器类
package dsh.bikegis.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginCheckFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(true); // 从session里取的用户名信息 String username = (String) session.getAttribute("userName"); String uri = ((HttpServletRequest) request).getRequestURI(); // 判断如果没有取到用户信息,就跳转到登陆页面 if (username != null || !("".equals(username))|| uri.endsWith("index.html") ) { chain.doFilter(request, response); } else { // 跳转到登陆页面 RequestDispatcher dispatcher = request.getRequestDispatcher("index.html"); dispatcher.forward(request, response); } } public void destroy() { } }web.xml配置过滤器: <filter>
<filter-name>yes</filter-name> <filter-class>dsh.bikegis.filter.LoginCheckFilter</filter-class> </filter> <filter-mapping> <filter-name>yes</filter-name> <url-pattern>/manage/*</url-pattern> </filter-mapping>
//登錄驗證
public String loginUser(){ if(this.us.getUser(user)!=null){ ActionContext.getContext().getSession().put("userName",user.getUsername()); return ActionSupport.SUCCESS; } this.errMesg="密碼或者用戶名錯誤,請重新輸入!"; return ActionSupport.ERROR; }
其中登录验证为 struts2中的Action,前台登录页面访问这个Action,成功的话就把用户名放入session中;在Filter中获得session中存放的字符串,如果不为空,或者是登录页面(此处为index.html)的话则验证成功,就放行,让其具有访问manage目录下的所有文件。否则跳转到index.html