Java - 过滤器(Filter)的使用

过滤器大家都不陌生,这里直接写出如何创建一个过滤器,用于记录。

一、新建一个类并实现Filter接口
package com.wmli.family.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 com.wmli.family.admin.entity.Admin;

public class AdminJSPFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		Admin admin = (Admin) httpRequest.getSession().getAttribute("adminInfo");
		String requestURL = httpRequest.getRequestURI();
		if (admin == null && requestURL.indexOf("admin/") != -1) {
			httpResponse.sendRedirect("/index");
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}


二、配置web.xml
<filter>
	<filter-name>AdminJSPFilter</filter-name>
	<filter-class>com.wmli.family.filter.AdminJSPFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>AdminJSPFilter</filter-name>
	<url-pattern>*.jsp</url-pattern>
</filter-mapping>

你可能感兴趣的:(java,jsp,Web,xml,servlet)