`
iorit2003
  • 浏览: 140883 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

五个过滤器

    博客分类:
  • j2ee
阅读更多
五个有用的过滤器
一、使浏览器不缓存页面的过滤器
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
{
}
}

二、检测用户是否登陆的过滤器

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());
}
}
}
}

三、字符编码的过滤器

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");

}
}

四、资源保护过滤器


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限制用户浏览权限

在一个系统中通常有多个权限的用户。不同权限用户的可以浏览不同的页面。使用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 {

}

}

<!-- 判断页面的访问权限 -->
<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的配置,如下:
<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,不然过滤器也起不了作用。
分享到:
评论

相关推荐

    servlet过滤器实例经典过滤器

    本教程将深入讲解如何配置和使用Servlet过滤器,以及介绍五个经典的过滤器实例。 首先,让我们理解Servlet过滤器的基本概念。根据Java Servlet规范,过滤器(Filter)是一个实现了javax.servlet.Filter接口的类,它...

    4899过滤器4899过滤器4899过滤器4899过滤器

    这个标题和描述虽然重复,但我们可以从中推测这个话题主要围绕一个名为"4899过滤器"的软件或技术。以下是根据提供的标签和文件名,对相关知识点的详细解释: 1. **网络过滤器**:4899过滤器可能是用于网络内容筛选...

    java中五种常用的过滤器

    以上五个过滤器涵盖了常见的Web开发需求,如缓存控制、登录验证、字符编码、数据压缩和URL重写。熟练掌握这些过滤器的使用,可以显著提升Java Web应用的功能性和性能。在实际项目中,可以根据需求灵活组合和定制过滤...

    过滤器图形符号(标准图形)

    - **说明**: 双筒过滤器由两个过滤器组成,其中一个处于工作状态,另一个作为备用或正在维护中。这样的设计可以在不停机的情况下切换过滤器进行清洁或更换,特别适合于对连续性和可靠性要求较高的场合。 #### 应用...

    过滤器链的一个小Demo

    5. 目标资源处理完请求后,响应会沿着过滤器链反向返回,每个过滤器都有机会对响应进行修改。 6. 最终,响应被发送回客户端。 在"FilterChainDemo"这个例子中,我们可能会有两个过滤器,例如FilterA和FilterB,它们...

    java 过滤器(附代码)

    下面我们将详细介绍五个有用的过滤器,每个过滤器都有其特定的作用和实现方式。 一、使浏览器不缓存页面的过滤器 这个过滤器的作用是使浏览器不缓存页面,从而确保每次访问页面时都可以获取最新的内容。实现这个...

    DirectShow过滤器-获取过滤器图事件过滤器

    本过滤器获取过滤器图事件,将事件代码及参数以列表形式显示在窗口中。 参见本过滤器的介绍文章:https://blog.csdn.net/h3974/article/details/134534847 过滤器名称:事件 过滤器GUID:{380338B5-4292-4DB3-826C...

    servlet 过滤器做的简单登陆demo

    Servlet过滤器是Java Web开发中的一个重要概念,它允许开发者在请求到达目标Servlet之前或之后对请求和响应进行处理。在这个“servlet过滤器做的简单登陆demo”中,我们将探讨如何利用过滤器实现一个基础的登录验证...

    管道过滤器(软件体系结构)

    首先使用一个过滤器进行图像加载,然后通过另一个过滤器进行颜色空间转换,接着是噪声滤除、边缘检测等多个过滤器。每个过滤器专注于完成特定的任务,最终通过管道连接起来形成完整的处理流程。 #### 结论 管道...

    过滤器.zip

    5. **FilterChain对象**:在doFilter方法中,我们通常会调用FilterChain的doFilter方法,将请求传递给下一个过滤器或目标资源。如果不调用,请求会被阻塞。 6. **多过滤器协作**:通过调整过滤器声明的顺序,可以...

    wireshark捕获过滤器与显示过滤器

    为了解决这个问题,Wireshark提供了两种类型的过滤器:**捕获过滤器**和**显示过滤器**。 - **捕获过滤器**:在捕获过程中应用的一种过滤方式,决定了哪些数据包会被记录下来。这种过滤器需要在开始捕获之前设置。 ...

    过滤器的使用过滤器的使用

    在Java Web开发中,过滤器(Filter)是一个非常重要的组件,它允许我们在数据处理的各个环节进行拦截、修改或增强处理。本篇文章将深入探讨Java中的过滤器使用技术,旨在帮助开发者理解和掌握这一核心技术。 首先,...

    过滤器的编写

    在一个Web应用中,可以有多个过滤器,它们会形成一个过滤器链。当请求到达时,每个过滤器按照配置的顺序依次执行其`doFilter()` 方法。过滤器之间是串行的,一个过滤器处理完后再传递给下一个。 5. **常见应用** ...

    JAVAEE过滤器的使用

    5. **过滤器链的执行** 当请求匹配到一个过滤器链时,每个过滤器的`doFilter()`方法都会按顺序执行。只有当所有过滤器都成功处理后,请求才会到达目标Servlet。同样,响应也会经过过滤链返回。 6. **Filter的级联*...

    JAVA过滤器标准代码

    总之,JAVA过滤器作为Java Web开发中的一个重要组成部分,提供了强大的功能和灵活性,可以用于解决多种实际问题,包括但不限于编码处理、权限验证、日志记录、异常处理、数据格式转换和缓存优化等。理解和掌握过滤器...

    过滤器笔记整理

    #### 五、过滤器应用场景 - **编码过滤**:用于解决客户端提交的数据编码问题,确保字符集的一致性。 - **权限过滤**:检查用户是否已登录,以及是否有权限访问特定资源。 - **日志记录**:记录用户的访问日志,...

    几个有用的过滤器 小技巧

    5. **CORS跨域资源共享过滤器**: 当前端和后端不在同一域名下时,CORS过滤器可以处理跨域请求的问题。通过设置响应头,允许特定的源(Origin)访问服务端资源。 6. **静态资源缓存过滤器**: 对于不会频繁更改的...

    多介质过滤器设计规范

    5. **应用案例**:该过滤器已经在钢铁厂的浊水净化、净循环水系统的旁滤处理等多个场合得到应用,并且经过长期运行验证,效果满意,证明了其稳定性和实用性。 6. **技术资料与标准**:虽然未详细列出,但设计规范应...

    管道过滤器程序,主要用java实现

    5. **过滤器的应用场景**:在Web开发中,过滤器常用于认证、授权、日志记录、数据转换等任务。例如,`HttpServletFilter`是Servlet API中定义的一个基础过滤器类型,可以拦截HTTP请求和响应。 6. **配置过滤器**:...

    JAVA Web中过滤器

    5. **过滤器的链式处理** 多个过滤器可以组成一个过滤器链,它们按照在web.xml中的配置顺序依次执行。如果一个请求匹配多个过滤器,那么这些过滤器会按照声明的顺序依次执行doFilter()方法。 6. **常见应用场景** ...

Global site tag (gtag.js) - Google Analytics