strtus2过滤器实现用户登录验证

过滤器代码:userLoginFilter.java

package com.gifer.action;

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;

import org.apache.log4j.Logger;

public class userLoginFilter implements Filter {

	private static Logger log = Logger.getLogger(AuthenticationFilter.class);

	private static String LOGIN_PAGE = "/login.jsp";

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		if (log.isDebugEnabled()) {
			log.info("权限过滤器初始化完成。");
		}
	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;

		HttpServletResponse res = (HttpServletResponse) response;

		// 当前访问路径
		String currentUrl = req.getRequestURI();

		// 获取session
		HttpSession session = req.getSession();

		// 如果不是登录页面,就要进行身份认证
		if (currentUrl.indexOf(LOGIN_PAGE) == -1) {
			if (log.isDebugEnabled()) {
				log.info("正在对请求进行权限认证," + "请求URL:" + currentUrl);
			}
			// 如果session为空,或者用户没有登录,则重定向输出登录页面
			if (session == null || session.getAttribute("user") == null) {
				res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
				return;
			}
		}

		// 过滤完成,filter链继续向下执行
		chain.doFilter(request, response);
	}

}

 web.xml

    

<!-- 自定义权限过滤器 -->
	<filter>
		<filter-name>authFilter</filter-name>
		<filter-class>com.gifer.action.userLoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>authFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

你可能感兴趣的:(strtus2)