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

Java中filter用法完整代码示例

程序员文章站 2023-12-09 19:09:33
本文研究的主要是java中filter过滤器的相关用法,具体实现代码如下。 filter过滤器主要使用于前台向后台传递数据是的过滤操作。程度很简单就不说明了,直接给几个已...

本文研究的主要是java中filter过滤器的相关用法,具体实现代码如下。

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
  {
  }
}

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

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 com.qwserv.itm.pfl.log.svr;
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 java.text.simpledateformat;
import javax.servlet.http.httpservletrequest;
import com.qwserv.itm.api.pfl.sm.vo.person;
import java.sql.*;
import com.qwserv.itm.api.serviceaccess;
import com.qwserv.itm.util.toolkit.debugutil;
public class observefilter implements filter {
	protected static debugutil log = debugutil.getinstances("pfl-log", observefilter.class);
	public void destroy() {
	}
	public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception,
	  servletexception {
		//记录用户的访问操作
		httpservletrequest request1 = (httpservletrequest)request;
		stringbuffer url = request1.getrequesturl();
		//对url进行过滤,如果是js/css/image则不进行处理
		if (judgefile(url.tostring())){
			string opertime = new simpledateformat("yyyy-mm-dd hh:mm:ss").
			          format(new java.util.date());
			string hostip = request.getremoteaddr();
			string sessionid = request1.getrequestedsessionid();
			string userid = "";
			person person = (person)request1.getsession().getattribute("userobj");
			if (null != person && null != person.getuser()){
				userid = person.getuser().getid();
			}
			string querystring = request1.getquerystring();
			if (null != querystring) {
				url.append('?');
				url.append(querystring);
			}
			//保存到数据库中
			savetodb(userid,hostip,sessionid,url.tostring(),opertime,"");
		}
		// pass control on to the next filter
		chain.dofilter(request, response);
	}
	public void init(filterconfig filterconfig) throws servletexception {
	}
	public boolean judgefile(string url){
		if (url.endswith(".gif") || url.endswith(".jpg") || url.endswith(".png")
		        || url.endswith(".bmp") || url.endswith(".css") || url.endswith(".js")
		        || url.endswith(".jsx")){
			return false;
		} else {
			return true;
		}
	}
	public int savetodb(string userid, string hostip,string sessionid,string url,
	      string opertime,string desc){
		//将报表任务数据保存到数据库中
		connection conn = null;
		statement st = null;
		try {
			//构造sql表达式,将数据插入数据库
			conn = serviceaccess.getsystemsupportservice().getdefaultconnection();
			st = conn.createstatement();
			string sql = "insert into log_observe_history(userid,url,detail,sessionid,hostname,startdate)  values('"+
			          userid + "','" + url + "','" + desc + "','" + sessionid
			          + "','" + hostip + "','" + opertime + "')";
			if (serviceaccess.getsystemsupportservice().getconnectiontype(conn)==serviceaccess.getsystemsupportservice().jca_type_oracle){
				sql = "insert into log_observe_history(id,userid,url,detail,sessionid,hostname,startdate) values(log_observe_seq.nextval,'"+
				            userid + "','" + url + "','" + desc + "','" + sessionid
				            + "','" + hostip + "',to_date('" + opertime
				            + "','yyyy-mm-dd hh24:mi:ss'))";
			}
			st.executeupdate(sql);
		}
		catch (exception e) {
			e.printstacktrace();
			log.error("--------------------the url string is:" + url + "-------------------------------");
			return 1;
			//表示操作失败
		}
		finally {
			if (null != st)
			      {
				try{
					st.close();
				}
				catch(exception e)
				        {
					e.printstacktrace();
				}
				st = null;
			}
			if (conn != null) {
				try {
					conn.close();
				}
				catch (exception e) {
					e.printstacktrace();
				}
				conn = null;
			}
		}
		return 0;
		//表示操作成功
	}
}
<filter>
<filter-name>observefilter</filter-name>
<filter-class>com.qwserv.itm.pfl.log.svr.observefilter</filter-class>
</filter>
<filter-mapping>
<filter-name>observefilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

五.filter防止用户访问一些未被授权的资源

package com.drp.util.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 javax.servlet.http.httpsession;
public class authfilter implements filter {
	public void destroy() {
	}
	public void dofilter(servletrequest servletrequest, servletresponse servletresponse,  
	      filterchain filterchain) throws ioexception, servletexception {
		//1,dofilter方法的第一个参数为servletrequest对象。此对象给过滤器提供了对进入的信息(包括表单数据、cookie和http请求头)的完全访问。第二个参数为servletresponse,通常在简单的过滤器中忽略此参数。最后一个参数为filterchain,此参数用来调用servlet或jsp页。  
		httpservletrequest request = (httpservletrequest)servletrequest;
		//;//如果处理http请求,并且需要访问诸如getheader或getcookies等在servletrequest中无法得到的方法,就要把此request对象构造成httpservletrequest  
		httpservletresponse response = (httpservletresponse)servletresponse。  
		        string currenturl = request.getrequesturi();
		//取得根目录所对应的绝对路径:  
		string targeturl = currenturl.substring(currenturl.indexof("/", 1), currenturl.length());
		//截取到当前文件名用于比较  
		httpsession session = request.getsession(false);
		if (!"/login.jsp".equals(targeturl)) {
			//判断当前页是否是重定向以后的登录页面页面,如果是就不做session的判断,防止出现死循环  
			if (session == null || session.getattribute("user") == null) {
				//*用户登录以后需手动添加session  
				system.out.println("request.getcontextpath()=" + request.getcontextpath());
				response.sendredirect(request.getcontextpath() + "/login.jsp");
				//如果session为空表示用户没有登录就重定向到login.jsp页面  
				return;
			}
		}
		//加入filter链继续向下执行  
		filterchain.dofilter(request, response);
		//.调用filterchain对象的dofilter方法。filter接口的dofilter方法取一个filterchain对象作为它的一个参数。在调用此对象的dofilter方法时,激活下一个相关的过滤器。如果没有另一个过滤器与servlet或jsp页面关联,则servlet或jsp页面被激活。
	}
	public void init(filterconfig filterconfig) throws servletexception {
	}
}

html

<filter>
<filter-name>authfilter</filter-name>
<filter-class>com.drp.util.filter.authfilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authfilter</filter-name>
<url-pattern>*.jsp</url-pattern>//表示对所有jsp文件有效
</filter-mapping>

总结

以上就是本文关于java中filter用法完整代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!