JavaEE中的访问控制

在过滤器Filter中:

 

package 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.HttpSession;
import org.apache.log4j.Logger;
import entity.Users;

/**
 * 访问控制
 * @author miao
 *
 */
public class AuthenticationFilter implements Filter {
	
	// Log4j,记录日志
	private static Logger log = Logger.getLogger(AuthenticationFilter.class);

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		//如下地址不用经过过滤器
		if (path.endsWith("/Login") || path.endsWith("/login.jsp") || path.endsWith(".css") || path.endsWith(".js")) {
			chain.doFilter(request, response);
		} else {
			HttpSession session = req.getSession();
			Users user = (Users) session.getAttribute("loginUser");
			if (user == null) {
				log.debug("用户在会话中不存在");
				req.getRequestDispatcher("login.jsp").forward(request, response);
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	public void init(FilterConfig config) throws ServletException {
		
	}	
	
}

 

 

在web.xml配置文件中:

 

<filter>
  	<display-name>访问控制</display-name>
  	<filter-name>AuthenticationFilter</filter-name>
  	<filter-class>filter.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>AuthenticationFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

 

 

你可能感兴趣的:(javaee)