Javaにおける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の使い方の完全なコード例のすべての内容です。興味のある方は引き続き当駅の他のテーマを参照してください。友達のサポートに感謝します。