Examples of complete code for filter usage in Java

  • 2021-01-14 05:58:54
  • OfStack

This paper mainly studies the relevant usage of filter filter in Java, and the specific implementation code is as follows.

filter filters are mainly used in the foreground to pass data to the background filter operation. The degree is very simple, but it is not clear, directly to a few already written code:

1. Filters that make the browser not cache pages


import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 *  Used to make  Browser  Filters for pages are not cached 
 */
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
  {
  }
}

2. Filters that check if the user is logged in


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

3. Filters for character encoding


import javax.servlet.*;
import java.io.IOException;
/** 
 *  Used to set the  HTTP  Request the character encoding of the filter through the filter parameter encoding Specifies which character encoding to use , To deal with Html Form Chinese problem with request parameters  
 */
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");
	}
}

4. Record the user's access operator


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 {
		// Record the user's access operations 
		HttpServletRequest request1 = (HttpServletRequest)request;
		StringBuffer url = request1.getRequestURL();
		// right url Filter if it is js/css/image It is not processed 
		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);
			}
			// Save it to the database 
			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){
		// Save the report task data to the database 
		Connection conn = null;
		Statement st = null;
		try {
			// structure sql Expression to insert data into the database 
			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;
			// Indicates operation failed 
		}
		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;
		// That means the operation was successful 
	}
}

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

5.Filter prevents users from accessing some unauthorized resources


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 Methods the first 1 The parameters for ServletRequest Object. This object provides the filter with information about incoming information (including form data, cookie and HTTP Full access to the request header. The first 2 The parameters for ServletResponse This parameter is usually ignored in simple filters. The last 1 The parameters for FilterChain This parameter is used to call servlet or JSP Page.   
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		//;// If handled HTTP Request, and need access to such as getHeader or getCookies Such as in ServletRequest The method that cannot be obtained in, is to put this request Object is constructed as HttpServletRequest  
		HttpServletResponse response = (HttpServletResponse)servletResponse .   
		        String currentURL = request.getRequestURI();
		// Gets the absolute path to the root directory :  
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
		// Intercepted to the current filename for comparison   
		HttpSession session = request.getSession(false);
		if (!"/login.jsp".equals(targetURL)) {
			// Determine whether the current page is the login page after redirection, if it is, do not do session To prevent the occurrence of an infinite loop   
			if (session == null || session.getAttribute("user") == null) {
				//* After the user logs in, it needs to be added manually session  
				System.out.println("request.getContextPath()=" + request.getContextPath());
				response.sendRedirect(request.getContextPath() + "/login.jsp");
				// if session Null indicates that the user is redirected to without logging in login.jsp page   
				return;
			}
		}
		// join filter The chain continues down   
		filterChain.doFilter(request, response);
		//. call FilterChain The object's doFilter Methods. Filter Of the interface doFilter methods 1 a FilterChain Object as its 1 A parameter. During the call to this object doFilter Method, activate it 1 Three related filters. If there is no other 1 Filter and servlet or JSP Page association, then servlet or JSP The page is activated. 
	}
	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>// Indicates that all jsp File is valid 
</filter-mapping>

conclusion

That is all of the complete code examples for filter usage in Java in this article. I hope you will find them helpful. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: