欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一个简单的过滤器(filter)

程序员文章站 2022-03-10 13:11:36
...

有关于自己目前的对于filter的用法吧

 

备注,之下所写代码,不是测试代码,是直接把之前代码copy下来的,并不能直接运行,只是拿来当个借鉴

 

首先,是有关filter在web.xml配置文件中的配置

<filter>
		<filter-name>loginFilter</filter-name>
		<filter-class>filter.loginFilter</filter-class>
		<init-param>
			<param-name>ex</param-name>
			<param-value>login.jsp,.css,.eot,.woff,.ttf,.png,.jpg,Activity_User/login,Activity_Operator/login,.js,img</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>loginFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

接下来

public class loginFilter implements Filter{
	private Set<String> prefixIignores = new HashSet<String>();
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest req1, ServletResponse resp1, FilterChain fc)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req=(HttpServletRequest) req1;
		HttpServletResponse resp=(HttpServletResponse) resp1;
		if (canIgnore(req)) {
			fc.doFilter(req, resp);
			return;
		}
		if(req.getSession().getAttribute("operator")!=null||req.getSession().getAttribute("user")!=null) {
			fc.doFilter(req, resp);
		}
		else {
			resp.sendRedirect("http://localhost:8080/activity/login.jsp");
		}
	}

	public void init(FilterConfig c) throws ServletException {
		
		String ex = c.getInitParameter("ex");
		String[] ignoreArray = ex.split(",");
		for (String s : ignoreArray) {
			prefixIignores.add(s);
		}
	}
	private boolean canIgnore(HttpServletRequest request) {
		String url = request.getRequestURI();
		for (String ignore : prefixIignores) {
			if (url.endsWith(ignore)) {
				return true;
			}
		}
		return false;
	}


}

 

 

相关标签: filter