`
royzhou1985
  • 浏览: 250545 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

web.xml配置五个有用的过滤器

    博客分类:
  • Java
阅读更多
一、使浏览器不缓存页面的过滤器  
Java代码
import javax.servlet.*;      
import javax.servlet.http.HttpServletResponse;      
import java.io.IOException;      
     
/**  
* 用于的使 Browser 不缓存页面的过滤器  
*/     
public class ForceNoCacheFilter implements Filter {       
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException  {      
		((HttpServletResponse) response).setHeader("Cache-Control","no-cache");      
		((HttpServletResponse) response).setHeader("Pragma","no-cache");      
		((HttpServletResponse) response).setDateHeader ("Expires", -1);      
		filterChain.doFilter(request, response);      
	}      
		 
	public void destroy() {      
	}      
		 
	public void init(FilterConfig filterConfig) throws ServletException {      
	}      
}     

 
二、检测用户是否登陆的过滤器  
Java代码
  
import javax.servlet.*;      
import javax.servlet.http.HttpServletRequest;      
import javax.servlet.http.HttpServletResponse;      
import javax.servlet.http.HttpSession;      
import java.util.List;      
import java.util.ArrayList;      
import java.util.StringTokenizer;      
import java.io.IOException;      
     
/**  
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面   
* 配置参数  
* checkSessionKey 需检查的在 Session 中保存的关键字   
* redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath   
* notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath  
*/     
public class CheckLoginFilter implements Filter {      
     protected FilterConfig filterConfig = null;      
     private String redirectURL = null;      
     private List notCheckURLList = new ArrayList();      
     private String sessionKey = null;      
     
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException  {      
		HttpServletRequest request = (HttpServletRequest) servletRequest;      
		HttpServletResponse response = (HttpServletResponse) servletResponse;      
		 
		 HttpSession session = request.getSession();      
	   if(sessionKey == null)      
		{      
		 filterChain.doFilter(request, response);      
		return;      
		}      
	   if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)      
		{      
		 response.sendRedirect(request.getContextPath() + redirectURL);      
		return;      
		}      
		filterChain.doFilter(servletRequest, servletResponse);      
	}      
     
	public void destroy() {      
		notCheckURLList.clear();      
	}      
		 
	private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {      
		String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());      
	   return notCheckURLList.contains(uri);      
	}      
     
	public void init(FilterConfig filterConfig) throws ServletException  {      
		this.filterConfig = filterConfig;      
		redirectURL = filterConfig.getInitParameter("redirectURL");      
		sessionKey = filterConfig.getInitParameter("checkSessionKey");      
		 
		String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");      
		 
		if(notCheckURLListStr != null) {      
			StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");      
			notCheckURLList.clear();      
			while(st.hasMoreTokens()) {      
				notCheckURLList.add(st.nextToken());      
			}      
		}      
	}      
}     
 

   
三、字符编码的过滤器  
Java代码
import javax.servlet.*;      
import java.io.IOException;      
     
/**  
* 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题  
*/     
public class CharacterEncodingFilter implements Filter {      
	protected FilterConfig filterConfig = null;      
	protected String encoding = "";      
     
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {      
		if(encoding != null)      
			servletRequest.setCharacterEncoding(encoding);      
		filterChain.doFilter(servletRequest, servletResponse);      
	}      
		 
	public void destroy() {      
		filterConfig = null;      
		encoding = null;      
	}      
		 
	public void init(FilterConfig filterConfig) throws ServletException {      
		this.filterConfig = filterConfig;      
		this.encoding = filterConfig.getInitParameter("encoding");      
	}      
}     


四、资源保护过滤器  
 
  Java代码
package catalog.view.util;      
     
import javax.servlet.Filter;      
import javax.servlet.FilterConfig;      
import javax.servlet.ServletRequest;      
import javax.servlet.ServletResponse;      
import javax.servlet.FilterChain;      
import javax.servlet.ServletException;      
import javax.servlet.http.HttpServletRequest;      
import java.io.IOException;      
import java.util.Iterator;      
import java.util.Set;      
import java.util.HashSet;         
import org.apache.commons.logging.Log;      
import org.apache.commons.logging.LogFactory;      
     
/**  
* This Filter class handle the security of the application.  
*  
* It should be configured inside the web.xml.  
*  
* @author Derek Y. Shen  
*/     
public class SecurityFilter implements Filter {      
	//the login page uri      
	private static final String LOGIN_PAGE_URI = "login.jsf";      
     
	//the logger object      
	private Log logger = LogFactory.getLog(this.getClass());      
     
	//a set of restricted resources      
	private Set restrictedResources;      
     
	/**  
	* Initializes the Filter.  
	*/     
	public void init(FilterConfig filterConfig) throws ServletException {      
	  this.restrictedResources = new HashSet();      
	  this.restrictedResources.add("/createProduct.jsf");      
	  this.restrictedResources.add("/editProduct.jsf");      
	  this.restrictedResources.add("/productList.jsf");      
	}      
     
	/**  
	* Standard doFilter object.  
	*/     
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)      
	   throws IOException, ServletException {      
		this.logger.debug("doFilter");      
			
		String contextPath = ((HttpServletRequest)req).getContextPath();      
		String requestUri = ((HttpServletRequest)req).getRequestURI();      
			
		this.logger.debug("contextPath = " + contextPath);      
		this.logger.debug("requestUri = " + requestUri);      
			
		if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {      
			this.logger.debug("authorization failed");      
			((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);      
		} else {      
			this.logger.debug("authorization succeeded");      
			chain.doFilter(req, res);      
	    }      
	}      
		 
	public void destroy() {}      
		 
	private boolean contains(String value, String contextPath) {      
		Iterator ite = this.restrictedResources.iterator();      
			
		while (ite.hasNext()) {      
			String restrictedResource = (String)ite.next();      			 
			if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {      
				return true;      
			}      
		}      
			
		return false;      
	}      
		 
	private boolean authorize(HttpServletRequest req) {      
		 
		//处理用户登录      
		UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);  
		if (user != null && user.getLoggedIn()) {  
			//user logged in  
			return true;  
		} else {  
			return false;  
		}
	}      
}    


五 利用Filter限制用户浏览权限
Java代码
在一个系统中通常有多个权限的用户。不同权限用户的可以浏览不同的页面。使用Filter进行判断不仅省下了代码量,而且如果要更改的话只需要在Filter文件里动下就可以。  
以下是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;      
     
public class RightFilter implements Filter {      
     
    public void destroy() {      
    }      
     
    public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException, ServletException {      
		// 获取uri地址      
		HttpServletRequest request=(HttpServletRequest)sreq;      
		String uri = request.getRequestURI();      
		String ctx=request.getContextPath();      
		uri = uri.substring(ctx.length());      
		//判断admin级别网页的浏览权限      
        if(uri.startsWith("/admin")) {      
            if(request.getSession().getAttribute("admin")==null) {      
                request.setAttribute("message","您没有这个权限");      
                request.getRequestDispatcher("/login.jsp").forward(sreq,sres);      
                return;      
            }      
         }      
        //判断manage级别网页的浏览权限      
        if(uri.startsWith("/manage")) {          
        }      
        //下面还可以添加其他的用户权限,省去。      
     
     }      
	 
	 public void init(FilterConfig arg0) throws ServletException {          
     }      
     
}  




Xml代码
<!-- 判断页面的访问权限 -->    
  <filter>    
     <filter-name>RightFilter</filter-name>    
      <filter-class>cn.itkui.filter.RightFilter</filter-class>    
  </filter>    
  <filter-mapping>    
      <filter-name>RightFilter</filter-name>    
      <url-pattern>/admin/*</url-pattern>    
  </filter-mapping>    
  <filter-mapping>    
      <filter-name>RightFilter</filter-name>    
      <url-pattern>/manage/*</url-pattern>    
  </filter-mapping>   

<!-- 判断页面的访问权限 --> 
<filter> 
<filter-name>RightFilter</filter-name> 
<filter-class>cn.itkui.filter.RightFilter</filter-class> 
</filter> 
<filter-mapping> 
<filter-name>RightFilter</filter-name> 
<url-pattern>/admin/*</url-pattern> 
</filter-mapping> 
<filter-mapping> 
<filter-name>RightFilter</filter-name> 
<url-pattern>/manage/*</url-pattern> 
</filter-mapping> 

在web.xml中加入Filter的配置,如下:
Xml代码
<filter>    
<filter-name>EncodingAndCacheflush</filter-name>    
<filter-class>EncodingAndCacheflush</filter-class>    
<init-param>    
<param-name>encoding</param-name>    
<param-value>UTF-8</param-value>    
</init-param>    
    </filter>    
    <filter-mapping>    
        <filter-name>EncodingAndCacheflush</filter-name>    
        <url-pattern>/*</url-pattern>    
    </filter-mapping>   
<filter> 
<filter-name>EncodingAndCacheflush</filter-name> 
<filter-class>EncodingAndCacheflush</filter-class> 
<init-param> 
<param-name>encoding</param-name> 
<param-value>UTF-8</param-value> 
</init-param> 
</filter> 
<filter-mapping> 
<filter-name>EncodingAndCacheflush</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping> 

要传递参数的时候最好使用form进行传参,如果使用链接的话当中文字符的时候过滤器转码是不会起作用的,还有就是页面上

form的method也要设置为post,不然过滤器也起不了作用。
分享到:
评论

相关推荐

    web.xml中配置过滤器

    介绍了在web.xml配置文件中如何配置过滤器。

    Filter过滤器的代码及其web.xml配置代码

    Filter过滤器的代码及其web.xml配置代码 很好的解决网页乱码问题,很方便,只要按照名字添加就可以了

    web.xml配置详解

    web.xml配置详解、过滤器配置、监听器配置

    Tomcat中用web.xml控制Web应用详解

    filter 元素用于配置过滤器。过滤器可以在请求处理过程中执行一些操作,例如身份验证、日志记录等。容器将创建 filter 中的类实例,并将其作为过滤器。filter-mapping 配置节用于指定过滤器的映射关系。 Servlet ...

    web.xml完整配置文件

    很实用的web.xml配置,里面包括过滤器,防止乱码,配置默认页,配置404或其它异常等错误页,开发项目时直接复制进去,完全搞定

    tomcat配置文件web.xml与server.xml解析

    在 Web 应用程序中,事件监听器和过滤器可以在 web.xml 文件中进行配置,例如: &lt;listener-class&gt;com.example.MyServletContextListener&lt;/listener-class&gt; 在上面的配置中,定义了一个名为 ...

    J2EE中关于web.xml文件的配置

    通过 web.xml 文件,我们可以对 Web 应用进行配置,例如设置应用程序的名称、描述、过滤器、监听器、Servlet、会话超时等等。 以下是 web.xml 文件中的一些常用元素: 1. `&lt;web-app&gt;`:web.xml 文件的根元素,用于...

    JSPservlet中web.xml详细配置指南(包含所有情况)

    其中,context-param 配置节用于提供应用程序上下文信息,listener 配置节用于定义事件监听程序,filter 配置节用于定义过滤器,而 servlet 配置节用于定义 servlet。 context-param 配置节 --------------------- ...

    web.xml详细说明

    用于 web.xml 配置详解。例如: &lt;web-app&gt; &lt;display-name&gt;&lt;/display-name&gt;定义了WEB应用的名字 &lt;description&gt;&lt;/description&gt; 声明WEB应用的描述信息 &lt;context-param&gt;&lt;/context-param&gt; context-param元素声明应用...

    Web后端开发-使用Filter过滤器技术,实现访问量统计-方法二使用web.xml配置的方式

    Web后端开发-使用Filter过滤器技术,实现访问量统计-方法二使用web.xml配置的方式

    防止XSS攻击解决办法

    防止XSS攻击简单实用的解决办法,直接复制两个过滤器,然后配置web.xml即可实现

    web.xml标签说明.docx

    6. `&lt;filter&gt;` 元素:用于在 Web 应用程序中声明一个过滤器。包括 `&lt;description&gt;`, `&lt;display-name&gt;`, `&lt;icon&gt;`, `&lt;filter-name&gt;`, `&lt;filter-class&gt;`, `&lt;init-param&gt;`, `&lt;param-name&gt;`, `&lt;param-value&gt;`。 `...

    JAVA WEB 开发详解:XML+XSLT+SERVLET+JSP 深入剖析与实例应用.part3

    全书一共被压缩为5个rar,这是第三个!!!! 其他的请看ID:ljtt123(本人分享) 本博客提供的所有教程的资源原稿均来自于互联网,仅供学习交流之用,切勿进行商业传播。同时,转载时不要移除本申明。如产生任何...

    如何配置Filter过滤器处理JSP中文乱码

    配置Filter过滤器处理...1.在项目web.xml文件添加过滤器标记和; 2.实现过滤器代码; 3.对Tomcat服务器conf目录里的Server.xml文件配置URIEncoding; 4.前台页面设置contentType的charset值与web.xml里设置的值一致。

    spring mvc xml配置拦截器

    NULL 博文链接:https://hw1287789687.iteye.com/blog/2046621

    完整的struts2框架应用实例.docx

    web.xml 文件主要是配置 Struts 的过滤器,使整个 Web 的流程转入到 Struts 框架中,而 struts.xml 是 Struts 框架的核心配置文件,在项目开发过程中,需要在此文件中进行大量的配置。 二、Struts2 框架所需要的两...

    jsp中过滤器配置实现所有过滤

    web.xml中简单的过滤器配置,实现所有过滤

    spring+shiro+ehcache例子

    在web.xml中配置shiro过滤器 4:项目post乱码处理 在web.xml中配置字符过滤器 5:项目运行信息查看 在web.xml中配置log4j信息打印 (需要自己将log4j的配置文件给打开) 三: 配置文件 查看/src/config/ ...

    Servlet过滤器使用

    在这个方法中可以读取web.xml文件中Servlet过滤器的初始化参数。 b、doFilter(ServletRequest,ServletResponse,FilterChain): 这个方法完成实际的过滤操作,当客户请求访问于过滤器关联的URL时,Servlet容器将先...

    Web配置详解

    jsp的web.xml配置说明 Web.xml常用元素&lt;web-app&gt;&lt;display-name&gt;&lt;/display-name&gt;定义了WEB应用的名字&lt;description&gt;&lt;/description&gt; 声明WEB应用的描述信息&lt;context-param&gt;&lt;/context-param&gt; context-param元素声明应用...

Global site tag (gtag.js) - Google Analytics