public class ForumFilter implements Filter { private static final String[] UNLOGIN_URIS = {"/index.jsp","/index.do","/login.jsp","/login/doLogin.do","/register.jsp", "/register.do","/board/listBoardTopics-","/board/listTopicPosts-"}; public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; User user = getSessionUser(request); if (user==null && !isURILogin(request.getRequestURI(),request)){ String toUrl = request.getRequestURI(); if (!StringUtils.isEmpty(request.getQueryString())){ toUrl += "?" + request.getQueryString(); } request.getSession().setAttribute(Define.LOGIN_TO_URL,toUrl); request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse); return; } filterChain.doFilter(servletRequest,servletResponse); } } protected User getSessionUser(HttpServletRequest request) { return (User) request.getSession().getAttribute(Define.UserLine); } public void destroy() { } protected boolean isURILogin(String requestURI,HttpServletRequest request){ if (request.getContextPath().equalsIgnoreCase(requestURI) || (request.getContextPath() + "/").equalsIgnoreCase(requestURI)) return true; for (String uri : UNLOGIN_URIS) { if (requestURI != null && requestURI.indexOf(uri) >= 0) { return true; } } return false; } }
实现Filter接口,重写doFilter方法。
将ServletRequest转成HttpServletRequest并且获取session中的用户。
如果存在用户或者访问的url是可以不登入就可访问的,即已经登入成功了,那就直接doFilter();
如果不存在,那就保存当前要访问的url,然后跳转到登入界面,如果登入成功再跳回此url。
在一些应用中,未登录用户请求了必须登录的资源时,提示用户登录,此时要记住用户访问的当前页面的URL,当他登录成功后根据记住的URL跳回用户最后访问的页面:
String lastAccessUrl = request.getRequestURI() + "?" + request.getQueryString();
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。