首页 > 代码库 > servlet拦截器
servlet拦截器
servlet拦截未登录的用户请求
java代码:
package com.gavin.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;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 LoginFilter implements Filter { public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletResponse response = (HttpServletResponse) resp; HttpServletRequest request = (HttpServletRequest) req; HttpSession session = request.getSession(true); String username = (String) session.getAttribute("username");// String url = request.getRequestURI(); if (username == null || username.equals("")) { // 判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转 if (url != null && !url.equals("") && (url.indexOf("Login") < 0 && url.indexOf("login") < 0)) { response.sendRedirect("login.jsp"); return; } } // 已通过验证,用户访问继续 chain.doFilter(req, resp); } public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub }}
web.xml配置
<filter> <filter-name>loginFilter</filter-name> <filter-class>com.gavin.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。