过滤器在netctoss中的作用

过滤器在netctoss中的作用_第1张图片

通过添加LoginFilter可以判断用户是否已经登录,若没有登录则重定向到login登录界面,若登录了,则可以正常访问其他页面

package web;

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;



public class LoginFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(
			ServletRequest req, 
			ServletResponse res,
			FilterChain chain)
			throws IOException, ServletException {
		//转型
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		//有三个请求不需要过滤,排除它们
		String[] paths = new String[] {
				"/toLogin.do","/login.do","/createImg.do"
		};
		//当前路径
		String sp = request.getServletPath();
		for(String p : paths) {
			if(p.equals(sp)) {
				//若当前路径为上述三个路径之一,则不必过滤
				chain.doFilter(request, response);
				return;
			}
		}
		//从session中获取账号
		HttpSession session = request.getSession();
		String adminCode = (String)session.getAttribute("adminCode");
		//根据账号判断用户是否登录
		if(adminCode == null) {
			//重定向到登录页面
			response.sendRedirect("/netctoss/toLogin.do");
		}else {
			//已登录,请求继续执行
			chain.doFilter(request, response);
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		

	}

}
注意:要在web.xml中配置

你可能感兴趣的:(servlet&jsp)