1. Unified character encoding on the entire site
The configuration parameter charset indicates which character encoding is used to handle the Chinese problem of Html Form request parameters
package me.gacl.web.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.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;/*** @ClassName: CharacterEncodingFilter* @Description: This filter is used to solve the problem of Chinese garbled in the entire site*/ public class CharacterEncodingFilter implements Filter { private FilterConfig filterConfig = null; //Set the default character encoding private String defaultCharset = "UTF-8"; public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String charset = filterConfig.getInitParameter("charset"); if(charset==null){ charset = defaultCharset; } request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); response.setContentType("text/html;charset="+charset); MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request); chain.doFilter(requestWrapper, response); } public void init(FilterConfig filterConfig) throws ServletException { //Get the initialization configuration information of the filter this.filterConfig = filterConfig; } public void destroy() { }}/*1. Implement the same interface as the enhanced object 2. Define a variable Remember the enhanced object 3. Define a constructor to receive the enhanced object 4. Overwrite the methods that need to be enhanced 5. For methods that do not want to be enhanced, directly call the method of the enhanced object (target object) */ class MyCharacterEncodingRequest extends HttpServletRequestWrapper{ private HttpServletRequest request; public MyCharacterEncodingRequest(HttpServletRequest request) { super(request); this.request = request; } /* Rewrite getParameter method* @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) */ @Override public String getParameter(String name) { try{ //Get the parameter's value String value= this.request.getParameter(name); if(value==null){ return null; } //If the data is not submitted in get, directly return the obtained value if(!this.request.getMethod().equalsIgnoreCase("get")) { return value; }else{ //If the data is submitted in get, the obtained value is transcoded value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding()); return value; } }catch (Exception e) { throw new RuntimeException(e); } }} The configuration in the web.xml file is as follows:
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>me.gacl.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2. The browser is prohibited from cached all dynamic pages
There are 3 HTTP response header fields that can prohibit the browser from cacheing the current page. The example code in the Servlet is as follows:
Not all browsers can fully support the above three response headers, so it is best to use the above three response headers at the same time.
package me.gacl.web.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;/*** @ClassName: NoCacheFilter* @Description: Browser is prohibited from cached all dynamic pages* @author: Lonely Canglang* @date: 2014-8-31 11:25:40 pm**/ public class NoCacheFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //Forcing ServletRequest to HttpServletRequest HttpServletRequest request = (HttpServletRequest) req; //Forcing ServletResponse to HttpServletResponse HttpServletResponse response = (HttpServletResponse) resp; //Forcing ServletResponse to HttpServletResponse response = (HttpServletResponse) resp; //Forbid browsers to cache all dynamic pages response.setDateHeader("Expires", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } public void destroy() { }} The configuration in the web.xml file is as follows:
<filter> <filter-name>NoCacheFilter</filter-name> <filter-class>me.gacl.web.filter.NoCacheFilter</filter-class> </filter> <filter-mapping> <filter-name>NoCacheFilter</filter-name> <!--Intercept only Jsp requests--> <servlet-name>*.jsp</servlet-name> </filter-mapping>
3. Control static resources in browser cache pages
Some dynamic pages refer to some pictures or css files to modify the page effect. These pictures and css files are often unchanged, so to relieve the pressure on the server, you can use filter to control the browser to cache these files to improve the performance of the server.
package me.gacl.web.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;/*** @ClassName: CacheFilter* @Description: filter*/ public class CacheFilter implements Filter { private FilterConfig filterConfig; public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; //1. Get the resource that the user wants to access String uri = request.getRequestURI(); //2. Get the suffix name of the resource that the user wants to access String ext = uri.substring(uri.lastIndexOf(".")+1); //Get the time when the resource needs to be cached String time = filterConfig.getInitParameter(ext); if(time!=null){ long t = Long.parseLong(time)*3600*1000; //Set the cache response.setDateHeader("expires", System.currentTimeMillis() + t); } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void destroy() { }} The configuration in the web.xml file is as follows:
<!-- Configure cache filter --> <filter> <filter-name>CacheFilter</filter-name> <filter-class>me.gacl.web.filter.CacheFilter</filter-class> <!-- Configure the web resources to be cached and the cache time in hours --> <init-param> <param-name>css</param-name> <param-value>4</param-value> </init-param> <init-param> <param-name>jpg</param-name> <param-value>1</param-value> </init-param> <init-param> <param-name>js</param-name> <param-value>4</param-value> </init-param> <init-param> <param-name>png</param-name> <param-value>4</param-value> </init-param> </filter> <!-- Configure the suffix of the web resource to be cached --> <filter-mapping> <filter-name>CacheFilter</filter-name> <url-pattern>*.jpg</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CacheFilter</filter-name> <url-pattern>*.css</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CacheFilter</filter-name> <url-pattern>*.js</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CacheFilter</filter-name> <url-pattern>*.png</url-pattern> </filter-mapping>
4. Realize automatic login for users
The idea is as follows:
1. After the user logs in successfully, send a cookie with the name user to the client. The value of the cookie is the user name and the encrypted password of md5.
2. Write an AutoLoginFilter. This filter checks whether the user has a cookie named user. If so, call dao to check whether the user name and password of the cookie match the database. If the match is done, the user object (i.e. the user login mark) is stored in the session to achieve automatic login.
The core code is as follows:
Controller handling user login: LoginServlet
package me.gacl.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import me.gacl.dao.UserDao;import me.gacl.domain.User;import me.gacl.util.WebUtils;public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); UserDao dao = new UserDao(); User user = dao.find(username, password); if(user==null){ request.setAttribute("message", "The user name or password is incorrect!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } request.getSession().setAttribute("user", user); //Send an automatic login cookie to the client browser to store sendAutoLoginCookie(request, response,user); request.getRequestDispatcher("/index.jsp").forward(request, response); } /** * @Method: sendAutoLoginCookie * @Description: Send an automatic login cookie to the client browser* @param request * @param response * @param user */ private void sendAutoLoginCookie(HttpServletRequest request, HttpServletResponse response, User user) { if (request.getParameter("logintime")!=null) { int logintime = Integer.parseInt(request.getParameter("logintime")); //Create a cookie, the name of the cookie is autologin, the value is the user name and password of the user login, and it is used between the user name and password. It is divided. The password is encrypted by md5. Cookie = new Cookie("autologin",user.getUsername() + "." + WebUtils.md5(user.getPassword())); //Set the validity period of the cookie cookie.setMaxAge(logintime); //Set the valid path of the cookie cookie.setPath(request.getContextPath()); //Write the cookie to the client browser response.addCookie(cookie); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }} Filters that handle user automatic login: AutoLoginFilter
package me.gacl.web.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.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import me.gacl.dao.UserDao;import me.gacl.domain.User;import me.gacl.util.WebUtils;public class AutoLoginFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; //If you have logged in, directly chain.doFilter(request, response) release if(request.getSession().getAttribute("user")!=null){ chain.doFilter(request, response); return; } //1. Get the cookie of the authlogin brought by the user String value = null; Cookie cookies[] = request.getCookies(); for(int i=0;cookies!=null && i<cookies.length;i++){ if(cookies[i].getName().equals("autologin")){ value = cookies[i].getValue(); } } //2. Get the username and password in the cookie if(value!=null){ String username = value.split("//.")[0]; String password = value.split("//.")[1]; //3. Call dao to get the corresponding password of the user UserDao dao = new UserDao(); User user = dao.find(username); String dbpassword = user.getPassword(); //4. Check whether the password of md5 brought by the user matches the password in the database. If it matches, it will automatically log in if(password.equals(WebUtils.md5(dbpassword))){ request.getSession().setAttribute("user", user); } } chain.doFilter(request, response); } public void destroy() { } public void init(FilterConfig filterConfig) throws ServletException { }} If you want to cancel the automatic login, you can delete the automatic login cookie when the user logs out. The core code is as follows:
package me.gacl.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class CancelAutoLoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Remove user request.getSession().removeAttribute("user"); //Remove the cookie that is automatically logged in removeAutoLoginCookie(request,response); //Remove to the login page after logging out request.getRequestDispatcher("/login.jsp").forward(request, response); } /** * @Method: removeAutoLoginCookie * @Description: Delete the automatic login cookie, * The way to delete the cookie in JavaWeb is to create a new cookie, the newly created cookie has the same name as the cookie to be deleted, * Set the validity period of the newly created cookie to 0, and the valid path is the same as the valid path of the cookie to be deleted* @param request * @param response */ private void removeAutoLoginCookie(HttpServletRequest request, HttpServletResponse response) { //Create a cookie with the name autologin Cookie cookie = new cookie("autologin","); //Set the validity period of the cookie to 0 and command the browser to delete the cookie cookie.setMaxAge(0); //Set the path cookie.setPath(request.getContextPath()); response.addCookie(cookie); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}The above are several common application scenarios of filters, and I hope they will be helpful to everyone's learning.