This article mainly studies the relevant usage of filter filters in Java, and the specific implementation code is as follows.
The filter filter is mainly used to pass data to the backend. The level is very simple, so I will just give a few codes that have been written:
1. Filters that make the browser not cache pages
import javax.servlet.*;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * Filter used to make Browser not cache pages*/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 to detect whether 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 checkRequestURIItNotFilterList(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. Character encoding filter
import javax.servlet.*;import java.io.IOException;/** * Filter used to set HTTP request character encoding, specify which character encoding is used to use through filter parameter encoding, which is used to handle Chinese issues of Html Form 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 user access operations HttpServletRequest request1 = (HttpServletRequest)request;StringBuffer url = request1.getRequestURL();//Filter the url, if it is js/css/image, it will not be processed if (judgeFile(url.toString())){String operaTime = 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 filterchain.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 operand,String desc){//Save report task data to the database Connection conn = null;Statement st = null;try {//Construct sql expression and 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 + "','" + operatorTime + "')";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('" + operaTime + "','YYYY-MM-DD HH24:MI:SS'))";}st.executeUpdate(sql);}catch (Exception e) {e.printStackTrace();log.error("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {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;// means the operation is 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, the first parameter of the doFilter method is the ServletRequest object. This object provides the filter with full access to incoming information, including form data, cookies, and HTTP request headers. The second parameter is ServletResponse, which is usually ignored in simple filters. The last parameter is FilterChain, which is used to call a servlet or JSP page. HttpServletRequest request = (HttpServletRequest)servletRequest;//;// If you process HTTP requests and need to access methods such as getHeader or getCookies that cannot be obtained in ServletRequest, you must construct this request object as HttpServletRequest HttpServletResponse response = (HttpServletResponse)servletResponse. String currentURL = request.getRequestURI();//Get the absolute path corresponding to the root directory: String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());//Seave the current file name to compare HttpSession session = request.getSession(false); if (!"/login.jsp".equals(targetURL)) {//Defend whether the current page is a login page page after redirection. If so, do not make session judgment to prevent a dead loop if (session == null || session.getAttribute("user") == null) {//*After the user logs in, you need to manually add session System.out.println("request.getContextPath()=" + request.getContextPath());response.sendRedirect(request.getContextPath() + "/login.jsp");//If the session is empty, it means that the user is not logged in, redirect to the login.jsp page return;}}// Join the filter chain and continue to execute filterChain.doFilter(request, response);//. Call the doFilter method of the FilterChain object. The doFilter method of the Filter interface takes a FilterChain object as its parameter. When calling the doFilter method of this object, the next related filter is activated. If no other filter is associated with the servlet or JSP page, the servlet or JSP 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>// means valid for all jsp files</filter-mapping>
Summarize
The above is the complete code example of this article about the usage of filter in Java. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!