过滤器(filter)实现用户登录拦截
过滤器(filter)实现用户登录拦截
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
蕃薯耀 2015年8月25日 16:20:47 星期二
一、增加一个Java类,实现filter接口
public class UserFilter implements Filter { @Override public void destroy() { System.out.println("userFilter destroy()"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(); //User user = (User) session.getAttribute(Conf.SESSION_USER); String user = (String) request.getAttribute("user"); if (user != null) { chain.doFilter(request, response); } else { session.setAttribute("redirect_url", req.getRequestURL().toString()); //System.out.println("req.getRequestURL().toString()="+req.getRequestURL().toString()); res.sendRedirect(req.getContextPath() + "/login?redirect_url="+URLEncoder.encode(req.getRequestURL().append("?").append(req.getQueryString()).toString(), "utf-8")); } } @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("userFilter init()"); }
二、配置web.xml文件
<filter> <filter-name>userFilter</filter-name> <filter-class>com.spring.filter.UserFilter</filter-class> </filter> <filter-mapping> <filter-name>userFilter</filter-name> <url-pattern>/user/*</url-pattern> </filter-mapping>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
蕃薯耀 2015年8月25日 16:20:47 星期二
今天越懒,明天要做的事越多。