通过session设置登录权限
新建类继承javax.servlet.Filter;
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpServletResponse response=(HttpServletResponse)servletResponse;
//取得根目录所对应的绝对路径:
String currentURL=request.getRequestURI();
//截取到当前文件名用于比较
String targetURL=currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
HttpSession session = request.getSession(false);
if(!"/userenter.jsp".endsWith(targetURL)){//判断当前页是否是重定向以后的登录页面页面,如果是就不做session的判断,防止出现死循环
if(session==null||session.getAttribute("enterUser")==null){
response.sendRedirect(request.getContextPath()+"/userenter.jsp");
return;
}
}
filterChain.doFilter(request, response);
}
?
在web.xml中初始化
<filter>
? <filter-name>loginFilter</filter-name>
? <filter-class>com.zfy.service.loginFilter</filter-class>
? </filter>
? <filter-mapping>
? <filter-name>loginFilter</filter-name>
? <url-pattern>*.jsp</url-pattern>
? </filter-mapping>