欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

过滤器(filter)实现用户登录拦截

程序员文章站 2022-05-01 22:52:02
...

过滤器(filter)实现用户登录拦截

 

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.

蕃薯耀 2015年8月25日 16:20:47 星期二

http://fanshuyao.iteye.com/

 

一、增加一个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 星期二

http://fanshuyao.iteye.com/

 

 

 

上一篇: 严格模式

下一篇: 严格模式