web.xml에서 로그인 필터를 설정하는 방법

2822 단어

1.web.xml 설정


    login_filter
    
            cn.com.trueway.sys.filter.LoginFilter
    
    
      skip
      /loginController/*.do
    
  
  
    login_filter
    *.do
  

2. 필터 코드

package cn.com.trueway.sys.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 cn.com.trueway.sys.entity.SysUser;
import cn.com.trueway.sys.util.ConstantUtil;

public class LoginFilter implements Filter {

	private String skip;
	
	public String getSkip() {
		return skip;
	}
	public void setSkip(String skip) {

		this.skip = skip;
	}

	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.setSkip(filterConfig.getInitParameter("skip"));
	}
    
    @Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
		String[] skips = null;
		if (skip != null) {
			skips = skip.split(";");
		}
		String url = httpServletRequest.getServletPath();
		boolean flag = true;
		if (skips != null) {
			for (int i = 0; i < skips.length; i++) {
				String sk = skips[i];
				if (sk.indexOf("*") != -1) {
					//    *   
					if (sk.startsWith("*")) {
						if (url.endsWith(sk.replace("*", ""))) {
							flag = false;
							break;
						}
					} else if (sk.endsWith("*.do")) {
						if (url.startsWith(sk.replace("*.do", ""))) {
							flag = false;
							break;
						}
					}
				} else {
					//       
					if (sk.equals(url)) {
						flag = false;
						break;
					}
				}
			}
		}
		if (flag) {
			SysUser user = (SysUser) httpServletRequest.getSession().getAttribute(ConstantUtil.LOGIN_USER);
			if (user != null) {
				filterChain.doFilter(servletRequest, servletResponse);
			} else {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/loginController/login.do");
			}
		} else {
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}
  	@Override
	public void destroy() {
		this.setSkip(null);
	}
}

좋은 웹페이지 즐겨찾기