您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。