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

Java web项目中四个常用的过虑器Filter

阅读更多
一、使浏览器不缓存页面的过滤器
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;

/**
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面<p>
* 配置参数<p>
* checkSessionKey 需检查的在 Session 中保存的关键字<br/>
* redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath<br/>
* notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath<br/>
*/
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;
   }*/
}
}

分享到:
评论

相关推荐

    Java-web旅游项目实战案例(四个)IDEA项目源码

    Java-web旅游项目实战案例(四个)IDEA项目源码; 4 技术选型 4.1 Web层 a) Servlet:前端控制器 b) html:视图 c) Filter:过滤器 d) BeanUtils:数据封装 e) Jackson:json序列化工具 4.2 Service层 f) Javamail:...

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

    此外,本书的配套光盘还免费提供了价值人民币330元的java教学视频,对java语言进行了全面讲解,帮助一些不会java语言的读者快速地从java基础知识的学习中过渡到java web的学习与开发上. 第1部分 xml篇. 第1章 xml...

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

    此外,本书的配套光盘还免费提供了价值人民币330元的java教学视频,对java语言进行了全面讲解,帮助一些不会java语言的读者快速地从java基础知识的学习中过渡到java web的学习与开发上. 第1部分 xml篇. 第1章 xml...

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

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

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

    此外,本书的配套光盘还免费提供了价值人民币330元的java教学视频,对java语言进行了全面讲解,帮助一些不会java语言的读者快速地从java基础知识的学习中过渡到java web的学习与开发上. 第1部分 xml篇. 第1章 xml...

    Java EE常用框架.xmind

    Java EE常用框架 WebService 介绍 基于Web的服务。它使用Web(HTTP)方式,接收和响应外部系统的某种请求。从而实现远程调用 术语 XML. Extensible Markup Language -扩展性标记语言 WSDL – ...

    使用Filter针对Xss攻击,sql注入,服务器访问白名单,以及csrf进行安全校验

    5,文章会分享出整个Filter文件包,包含四个java文件: 5.1,public class CrosXssFilter implements Filter 5.2,public class CrosXssFilterConfig implements WebMvcConfigurer 5.3,public class ...

    《MyEclipse 6 Java 开发中文教程》前10章

    8.7 创建Filter(过滤器) 152 8.8 创建数据库访问层(DAO) 155 8.9 修改Servlet调用后台类 158 8.10 发布,重新发布,运行和测试应用 159 8.11 调试JSP应用 160 8.12 向现有Web项目添加Web开发功能 161 8.13高级设置 ...

    java考试系统

    1.下面四个选项目,( )最适合用作专业的商用J2EE服务器 (A)Tomcat (B)Weblogic (C)Jetty (D)Jboss ~ 2.下列说法中描述错误的是( ) (A) struts2-core-2.x.x.jar 包是Struts 2框架的核心类库 (B) struts框架是...

    xmljava系统源码-simple-oauth2:一个简单oauth2应用服务,为第三方应用提供用户登录和授权

    xml java系统源码 1. 简介 这是一个简单的OAuth2.0的服务器,实现了OAuth ...可以应用于纯前端项目、纯后端项目、后端Web项目、前后端分离项目,提供最佳实践 提供简单的java客户端、spring filter、网关组件,实

    购物商场实现

    购物商城项目搭建。 第一步:创建项目 第二步:拷jar包(mybatis、mysql驱动、jstl) 放到WEB-INF/lib/下面 第三步:分层(创建包) 公司的域名反写 + 项目名称 www.fkjava.org org.fkjava.ec org.fkjava.ec....

    asp.net知识库

    也论该不该在项目中使用存储过程代替SQL语句 如何使数据库中的表更有弹性,更易于扩展 存储过程——天使还是魔鬼 如何获取MSSQLServer,Oracel,Access中的数据字典信息 C#中利用GetOleDbSchemaTable获取数据库内表信息...

    JSP2.0技术手册pdf(带示例源码).zip

    9-2 窗体中常见的输入类型 9-3 JSP 处理窗体 9-4 文件上传—— Oreilly 上传组件 9-5 jspSmartUpload ——上传和下载 9-6 本文区输入类型(Textarea) 第十章 Session Tracking 10-1 Stateful & Stateless 10-2 ...

    J2EE中文版指南 CHM格式 带全文检索

    增加一个Web组件到WAR文件中 150 配置Web客户 151 应用级配置 151 WAR级的配置 151 组件及配置 151 部署网络客户 152 运行网络客户 152 更新网络客户 152 国际化网络客户 152 第10章 Java Servlet技术 153 什么是...

    spring security 参考手册中文版

    第四部分 Web应用程序安全 112 13.安全过滤器链 112 13.1 DelegatingFilterProxy 112 13.2 FilterChainProxy 113 13.2.1绕过滤网链 115 13.3过滤器排序 115 13.4请求匹配和HttpFirewall 116 13.5与其他基于过滤器的...

    新版Android开发教程.rar

    ----------------------------------- Android 编程基础 1 封面----------------------------------- Android 编程基础 2 开放手机联盟 --Open --Open --Open --Open Handset ...• 多媒体支持 包括常见的音频、视频和...

    jpivot学习总结.doc

    memberReaderClass 设定一个成员读取器,默认情况下 Hierarchy 都是从关系型数据库里读取的,如果你的数据不在 RDBMS 里面的话,你可以通过自定义一个 member reader 来表现一个 Hierarchy 。 3.5. Level 级别 , ...

    Sosoo 1.0网络爬虫程序.doc

    用户可以把自己过滤器加入FilterChain中。 你可以实现DocumentFilter接口定制自己的功能,系统实现提供了一个LinkLocalizer实现,用于替换相对连接。 FilterChain filters=new FilterChain(); DocumentFilter ...

    测试培训教材

    项目管理员可以使用QC的Excel插件工具来执行需求的批量导入,进行导入之前请先确认已经访问过MQC主页,并安装了QCMSExcelAddin.exe插件。 插件下载地址: http://updates.merc-int.com/qual ... /msexcel/index.html...

Global site tag (gtag.js) - Google Analytics