当前位置:网站首页>Listener and filter (monitor and interceptor) in Servlet
Listener and filter (monitor and interceptor) in Servlet
2022-06-21 18:50:00 【LvhaoIT】
Monitors and interceptors
seventeen 、Servlet Specification extension ---- Monitor interface
1. Introduce :
1) One group comes from Servlet Interface under specification , share 8 Interface . stay Tomcat There is servlet-api.jar package
2) The listener interface needs to be implemented by developers ,Http Provided by the server jar Package has no corresponding implementation class
3) The listener interface is used to monitor 【 When the scope object life cycle changes 】 as well as 【 When the data shared by the scope object changes moment 】
2. Scope object :
1) stay Servlet Specification , It is considered that there can be two in the server memory under some conditions Servlet Provide... Between
Object of data sharing scheme , go by the name of 【 Scope object 】
2)Servlet Scope object under specification :
ServletContext: Global scope object
HttpSession : Session scope object
HttpServletRequest: Request scope object
3. Listener interface implementation class development specification : The three step
1) According to the actual situation of monitoring , Select the corresponding listener interface for implementation
2) Rewrite the listener interface declaration 【 Listening event handling method 】
3) stay web.xml File registers the listener interface implementation class to Http The server
4.ServletContextListener Interface :
1) effect : This interface is used to legally detect the initialization time and destruction time of global scope objects
2) Listening event handling method :
public void contextInitlized() : At the global scope, the object is Http Server initialization is called
public void contextDestory(): At the global scope, the object is Http The call is triggered when the server is destroyed
5.ServletContextAttributeListener Interface :
1) effect : This interface is used to legally detect the change time of shared data of global scope objects
2) Listening event handling method :
public void contextAdd(): Add shared data to the global scope object
public void contextReplaced(): Update shared data in global scope objects
public void contextRemove(): Delete shared data in global scope object
6. When the data shared by global scope objects changes
ServletContext application = request.getServletContext();
application.setAttribute("key1",100); // Add shared data
application.setAttribute("key1",200); // Update shared data
application.removeAttribute("key1"); // Delete shared data
7. Use the listener interface to speed up the database CURD
principle : Common packaging DAO Class , No data operation was performed , All need to be sealed JDBC Medium Connection a Time creation and destruction , This is a waste of time .
terms of settlement : Use the listener when the server starts running , establish 20 A global Connection The object of , For all in the program Data operations to use , Until the server shuts down , Unified creation and unified destruction .
1. Create a listener class , Realization ServletContextListener Interface
/** * Created by IntelliJ IDEA. * User: LvHaoIT (asus) * Date: 2021/5/7 * Time: 15:00 */ public class OneListener implements ServletContextListener { // stay tomcat Startup time , establish 20 individual connection, stay useradd Method execution , take //connection Object to add Methods use @Override public void contextInitialized(ServletContextEvent sce) { JdbcUtil util = new JdbcUtil(); Map map = new HashMap<>(); for (int i = 1; i <= 20; i++) { Connection con = util.createCon(); System.out.println(" When the server starts , Create Connection object " + con + "(" + i + ")"); map.put(con, true);//true Indicates that the channel is idle ,false The channel is being used } // In order to be in http While the server is running , It can be used all the time 20 individual Connection, So will connection Save to global scope object ServletContext application = sce.getServletContext();// Get the global scope object application.setAttribute("key1", map);// Put into global variables } /** * stay http When the server shuts down , We need to put this 20 individual connection To destroy * * @param sce */ @Override public void contextDestroyed(ServletContextEvent sce) { ServletContext application = sce.getServletContext(); Map map = (Map) application.getAttribute("key1"); Iterator it = map.keySet().iterator();// take map Put the data in set aggregate , Then use the iterator to do a sort // Ergodic iterator /** * 1、hasNext() : This method is used to determine whether there is an element at the index position pointed to by the iterator object * 2、next() : Gets the element at the current index position of the iterator object and moves the index subscript to the next element * 3、remove() : Delete the specified element in the parameter */ while (it.hasNext()) { Connection con = (Connection) it.next(); if (con != null) { try { System.out.println("Connection object " + con + " Ready to be destroyed "); con.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }2. In order to implement the opening and closing principles of program development , We will overload several of these methods
JdbcUtil In the tool class
//-------------------- Through the global scope alignment, we get Connetion---------------start public Connection createCon(HttpServletRequest request) { //1. Get the global scope object by requesting the object ServletContext application = request.getServletContext(); //2. Get a collection of objects Map map = (Map) application.getAttribute("key1"); //3. from map Get an idle... In Connection Iterator it = map.keySet().iterator(); while (it.hasNext()) { conn = (Connection) it.next(); if ((boolean) map.get(conn)) { // Determine if it is available map.put(conn, false);// It needs to be closed break; } } return conn; } //-------------------- Through the global scope alignment, we get Connetion---------------end //----------------==== Overload operation ps--------------------------------Statr public PreparedStatement createStatement(HttpServletRequest request, String sql) { try { ps = createCon(request).prepareStatement(sql); } catch (SQLException throwables) { throwables.printStackTrace(); } return ps; } //--------------------- heavy load --------------------------- //------------------ heavy load close Method ----------------------Srart public void close(HttpServletRequest request) { try { if (ps != null) ps.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } ServletContext application = request.getServletContext();// Get global Map map = (Map) application.getAttribute("key1"); map.put(conn, true);// Indicates that it can be used again } //------------------ heavy load close Method ----------------------end3. Get into UserDao Class , Continue to reload add Method
//------------------------------ heavy load add public int add(Users user, HttpServletRequest request) { int result = 0; String sql = "insert into users(userName,password,sex,email) values(?,?,?,?)"; // compile sql frame PreparedStatement ps = this.util.createStatement(request, sql); // Insert value try { ps.setString(1, user.getUserName()); ps.setString(2, user.getPassword()); ps.setString(3, user.getSex()); ps.setString(4, user.getEmail()); // perform sql sentence result = ps.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { this.util.close(request); } return result; } //-------------------------------------------4. The last to enter UserAddServlet in , Modify the corresponding code , To call the overloaded method
new UserDao().add(new Users(userName, password, sex, email), request); // The request object request Transfer the past , Used to get the global scope objectThis can greatly reduce CURD Operation time of .
eighteen 、Servlet Specification extension ----Filter Interface ( Filter interface )
1. Introduce :
1) From Servlet Interface under specification , stay Tomcat There is in servlet-api.jar package
2)Filter The interface implementation class is provided by the developer ,Http The server is not responsible for providing
3)Filter Interface in Http Before the server calls the resource file , Yes Http The server intercepts
2. Specific role :
1) Intercept Http The server , help Http The server detects the validity of the current request
2) Intercept Http The server , Enhance the current request
3.Filter Interface implementation class development steps : The three step
1) Create a Java Class implementation Filter Interface
2) rewrite Filter Interface doFilter Method
3)web.xml Register the filter interface implementation class to Http The server
4.Filter Intercept address format
1) Command format :
<filter-mapping>
<filter-name>oneFilter</filter-name>
<url-pattern> Intercept address </url-pattern>
</filter-mapping>
2) Command function :
Intercept address notifications Tomcat You need to call... Before calling what resource file OneFilter Filter to intercept
3) requirement Tomcat Before calling a specific file , To call OneFilter Intercept
<url-pattern>/img/mm.jpg</url-pattern>
4) requirement Tomcat Before calling all the resource files in a folder , To call OneFilter Intercept
<url-pattern>/img/*</url-pattern>
5) requirement Tomcat Before calling some type of file in any folder , To call OneFilter Intercept
<url-pattern>*.jpg</url-pattern>
6) requirement Tomcat When calling any file in the web site , To call OneFilter Intercept
<url-pattern>/*</url-pattern>
Using examples
1. Using interceptors to enhance methods , Set all character sets to utf-8
Interceptor TwoFilter
public class TwoFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest, servletResponse);
}
}
web.xml
<filter>
<filter-name>twoFilter</filter-name>
<filter-class>com.filter.TwoFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>twoFilter</filter-name>
<url-pattern>/*</url-pattern><!-- notice tomcat Before calling all resource files, you need to call twoFilter-->
</filter-mapping>
This allows the browser to request each resource , Change the character set of the request object to utf-8( It's not messy )
2. Malicious login ( Direct access to resources )
The first method : Token mode
Schematic diagram :

By opening up a block for the user when logging in session, Subsequent access to resources , Determine whether this user exists sessio
// First, in the loginServlet The token will be sent after the login is successful if (flag == 1) { // Users exist , Legal users , Send multiple tokens HttpSession session = request.getSession(); response.sendRedirect("/demo1/index.html"); } else { response.sendRedirect("/demo1/login_error.html"); } // And then in the subsequent verification Servlet Internal utilization request.getSession(false) == null // Determine if you have a token , If not, no service will be providedDisadvantages of this approach :
1. Increase development difficulty ( Because more than one resource file needs to be protected from malicious access )
2. Cannot protect static resource files
The second method : Using filters
Schematic diagram :

By using interceptors , Intercept and judge each request resource , Except for the default request, login request and normal login , All illegal operations cannot be passed .
OneFilter Interceptor
package com.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: LvHaoIT (asus) * Date: 2021/5/7 * Time: 22:59 */ public class OneFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //ServletRequest Under no getSession Method , This method is in its sub interface ,( Move down ) HttpServletRequest request = (HttpServletRequest) servletRequest; // Call the request object to read the request package URI, Know who the resource file is accessed by the user String URI = request.getRequestURI();//[/ Website name / Resource name ] // If this request file is related to user login , Or the default request Release unconditionally if (URI.indexOf("login") != -1 || "/demo1/".equals(URI)) { //indexof, Find the first position where the string appears , Return if not found -1 filterChain.doFilter(servletRequest, servletResponse); return; } // HttpServletResponse response = (HttpServletResponse) servletResponse; if (request.getSession(false) == null) { // The user is illegal , Just send it away ( Redirect ) request.getRequestDispatcher("/login_error.html").forward(servletRequest, servletResponse); return; } else { filterChain.doFilter(servletRequest, servletResponse); return; } } }web.xml Configuration in
<!-- Login interceptor --> <filter> <filter-name>oneFilter</filter-name> <filter-class>com.filter.OneFilter</filter-class> </filter> <filter-mapping> <filter-name>oneFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>This approach solves all the shortcomings of the previous token approach !
(Servlet End )
边栏推荐
猜你喜欢
随机推荐
Global installation of node
Module import method of node
Inheritance of typescript
Lei Jun's hundreds of billions of mistakes?
Day20Qt多个窗体的切换思路2021-10-31
基于mitmproxy的录制回放接口测试工具
产品图文列表说明布局样式
JDBC 笔记
协同过滤(Collaborative Filtering)
URL module of node
Day19QPushButton的使用2021-10-30
Compound type of typescript
数据库面试总结
8.取目录函数/取文件函数 -dir / -notdir
剑指 Offer 28. 对称的二叉树
Disclose the design idea of MVVM framework supporting Baidu search, feed and applet, and San core personnel have made great efforts to build it
TypeScript编译生成文件对比
Node的url模块
C language__ attribute__ (packed) attribute (learn)
Day15Qt中字符串的常用操作2021-10-20








![[HCTF 2018]WarmUp](/img/b0/6baee8ac76b56378230c2218f15734.png)