EL&&JSTL&&Filter&&Listener
- I EL
- 1.1 general
- 1.2 use
- 1.2.1 get (in domain) value
- 1.2.2 precautions for El expression
- 1.2.3 perform operation
- 1.2.4 implicit objects
- 1.2.5 understanding
- 2 JavaBean
- II. JSTL
- Filter in three Servlet specification
- Listener in the four Servlet specification
I EL
1.1 general
EL expression, full name is Expression Language. Means Expression Language. It is a part of the Servlet specification, which is added by the JSP 2.0 specification. Its function is to get data in JSP page, so that our JSP is separated from java code block and JSP expression.
lambda expressions xml(xpath path expression) regular expression Expressions: short symbols for complex content
Function: function: get data in jsp page. Replacing and simplifying Java code in jsp pages
Syntax: ${expression content}
1.2 use
1.2.1 get (in domain) value
EL expressions are mainly used to simplify data acquisition from domain objects (4 domains)
grammar
*Standard (understanding) 1. ${pageScope. Key name} Get the value corresponding to the specified key name from the page field 2. ${requestScope. Key name} Get the value corresponding to the specified key name from the request field 3. ${sessionScope. Key name} Get the value corresponding to the specified key name from the session field 4. ${applicationScope. Key name} Get the value corresponding to the specified key name from the servletContext field *Simplify (Master) ${key name} Features: it starts from the minimum domain by default, and will be displayed directly after it is found. It will not continue to search Summary: four unique domain key names are required
Create two entity classes, User and Address**
/** * User's entity class * @author Black horse programmer * @Company http://www.itheima.com */ public class User implements Serializable{ private String name = "Black horse programmer"; private int age = 18; private Address address = new Address(); public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
/** * Entity class of address * @author Black horse programmer * @Company http://www.itheima.com */ public class Address implements Serializable { private String province = "Beijing"; private String city = "Changping District"; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
1. Get string ${key name} 2. Get object (User) ${key name. Property name} 3. Get List (Array) set ${key name [index]} 4. Get Map set ${key. Key} ${key name ["key"]} 5. Supplement No null and index corner out of bounds in el
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>demo1</title> </head> <body> <%--ELExpression concept: //It is an abbreviation of Expression Language. It is a language that replaces jsp expressions. ELSyntax of expression: ${expression} //Expression features: clear return value. ELExpression is to output the content to the page ELNote for expressions: 1.ELExpression has no null pointer exception 2.ELExpression has no array subscript out of bounds 3.ELExpression has no string concatenation ELData acquisition of expression: //It can only get data in four domain objects, and it can't get data not in four domain objects. The way to get it is findAttribute(String name) <h3>el Expression basic syntax</h3> <br/>-----------Get object data---------------------<br/> <% //1. Store user information in the domain User user = new User(); pageContext.setAttribute("u",user); %> ${u}===============The output is the memory address<%--It's like calling this line of code<%=pageContext.findAttribute("u")%> --%><br/> ${u.name}<%--It's like calling this line of code<% User user = (User) pageContext.findAttribute("u");out.print(user.getName());%> --%><br/> ${u.age} <br/>-----------Get associated object data------------------<br/> ${u.address}==========Output address Address of the object<br/> ${u.address.province}${u.address.city}<br/> ${u["address"]['province']} <br/>-----------Get array data---------------------<br/> <% String[] strs = new String[]{"He","llo","Expression","Language"}; pageContext.setAttribute("strs", strs); %> ${strs[0]}==========The subscript of the array is0Elements of<br/> ${strs[3]} ${strs[5]}===========If the subscript of the array is exceeded, nothing is displayed<br/> ${strs["2"]}=========Will automatically convert to subscript for us<br/> ${strs['1']} <br/>-----------obtain List Aggregate data-----------------<br/> <% List<String> list = new ArrayList<String>(); list.add("AAA"); list.add("BBB"); list.add("CCC"); list.add("DDD"); pageContext.setAttribute("list", list); %> ${list}<br/> ${list[0] }<br/> ${list[3] }<br/> <br/>-----------obtain Map Aggregate data------------------<br/> <% Map<String,User> map = new HashMap<String,User>(); map.put("aaa",new User()); pageContext.setAttribute("map", map); %> ${map}<br/> ${map.aaa}<%--obtain map Of value,Yesget(Key) --%><br/> ${map.aaa.name}${map.aaa.age}<br/> ${map["aaa"].name } </body> </html>
1.2.2 precautions for El expression
When we use EL expression, it helps us to do some processing, so that we can avoid some mistakes when we use it. It has no null pointer exception, no array subscript out of bounds, no string splicing.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> Notes on < title > El expression < / Title > </head> <body> Three of the <% -- El expressions have no --% > First: no null pointer exception < br / > <% String str = null; request.setAttribute("testNull",str); %> ${testNull} <hr/> Second: no array subscript is out of range < br / > <% String[] strs = new String[]{"a","b","c"}; request.setAttribute("strs",strs); %> Take the first element: ${strs[0]} Take the sixth element: ${strs[5]} <hr/> Third: no string splicing < br / > <%--${strs[0]+strs[1]}--%> ${strs[0]}+${strs[1]} </body> </html>
1.2.3 perform operation
However, there are two special operators, which are used as follows:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="com.itheima.domain.User" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ELTwo special operators</title> </head> <body> <%--empty Operator: It will determine whether the object isnull,Whether the string is empty, and whether the elements in the collection are0individual --%> <% String str = null; String str1 = ""; List<String> slist = new ArrayList<String>(); pageContext.setAttribute("str", str); pageContext.setAttribute("str1", str1); pageContext.setAttribute("slist", slist); %> ${empty str}============When the object isnullreturntrue<br/> ${empty str1 }==========When the string is empty, the string is returnedtrue(Note: it does not call trim()method)<br> ${empty slist}==========When the elements in the collection are0Hour, yestrue <hr/> <%--Ternary operator condition?really:false --%> <% request.setAttribute("gender", "female"); %> <input type="radio" name="gender" value="male" ${gender eq "male"?"checked":""} >male <input type="radio" name="gender" value="female" ${gender eq "female"?"checked":""}>female </body> </html>
1.2.4 implicit objects
Introduction to implicit objects
EL expressions also provide implicit objects for us to use directly without declaration. Eleven objects are shown in the following table. It should be noted that they are not the same as JSP implicit objects:
1. pageContext It is one of the nine built-in objects of jsp. This man can get eight other built-in objects 2. cookie Can get the value of the cookie name specified by the browser
Implicit objects in EL | type | Corresponding JSP implicit object | remarks |
---|---|---|---|
PageContext | Javax.serlvet.jsp.PageContext | PageContext | It's exactly the same |
ApplicationScope | Java.util.Map | No, | Application layer range |
SessionScope | Java.util.Map | No, | Session scope |
RequestScope | Java.util.Map | No, | Request scope |
PageScope | Java.util.Map | No, | Page layer range |
Header | Java.util.Map | No, | Request header key, value is value (one) |
HeaderValues | Java.util.Map | No, | Request message header key, the value is array (multiple values for one header) |
Param | Java.util.Map | No, | Request parameter key, value is value (one) |
ParamValues | Java.util.Map | No, | Request parameter key, the value is array (multiple values with one name) |
InitParam | Java.util.Map | No, | Global parameter, key is the parameter name, value is the parameter value |
Cookie | Java.util.Map | No, | Key is the name of the cookie and value is the cookie object |
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>demo4</title> </head> <body> <h3>el Implicit object..</h3> ${pageContext.request.contextPath} Dynamic get: project name (virtual path) <br> ${cookie.JSESSIONID.value} Get specified cookie Value of name... <br> </body> </html>
1.2.5 understanding
*jsp supports el expression by default In the servlet 2.3 specification, el expressions are not supported by default *If you want to ignore el expressions 1) Ignore all el expressions in the current jsp page Set the: isELIgnored="true" attribute in the page instruction in jsp 2) Ignore single el expression ${expression}
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>demo4</title> </head> <body> <h3>el Implicit object..</h3> ${pageContext.request.contextPath} Dynamic get: project name (virtual path) <br> \${cookie.JSESSIONID.value} Get specified cookie Value of name... <br> </body> </html>
2 JavaBean
So a javaBean is a java standard class that conforms to a specific specification
Specification for use
- All fields (member variables) are private (it is better to use reference type, such as int - > integer)
- Provide public nonparametric construction method
- Provide methods of getter and setter
- Implement serializable interface
For example, the following User class has four fields (member variables), a parameter constructor, and a property (username)
public class User implements Serializable { private String username; private Integer age; private String gender; public User() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
II. JSTL
2.1 general
Jsp Standard Tag Library is an open source jsp tag library provided by Apache organization
Function: replace and simplify the java code in jsp page
Generally, it should be used together with EL expressions to realize that there is no java code segment in jsp.
Problem: excessive use of jsp, mixed html and java code, not conducive to reading and long-term maintenance
Writing: HTML + java - > HTML tag
Solution: Tag Library (write with tag instead of java code)
Write like html, or servlet in essence
JSTL standard tag library has five sub libraries, but with the development, its Core library is often used at present
Label Library | URI of tag library | prefix |
---|---|---|
Core | http://java.sun.com/jsp/jstl/core | c |
Internationalization (almost no use) | http://java.sun.com/jsp/jstl/fmt | fmt |
SQL (obsolete) | http://java.sun.com/jsp/jstl/sql | sql |
XML (obsolete) | http://java.sun.com/jsp/jstl/xml | x |
Functions (rarely used) | http://java.sun.com/jsp/jstl/functions | fn |
2.2 use of core label
2.2.1 use requirements
1. To use JSTL tag library, you need to import coordinates in Java Web project. First, create a lib directory in the WEB-INF directory of the project, copy the jar of JSTL to the Lib directory, right-click the jar package, and then select Add as Libary to add. As shown in the figure below:
2. The introduction of the current jsp tablib instruction
2.2.2 core label Library
① c:if tag
*Equivalent to if() {} in java grammar < C: if test = "Boolean value" > < / C: if > true: display label body content false: hide label body content Usually used with el expressions Note: this label does not have else function. If you want to achieve else effect, please reverse the condition
<%@ page import="cn.itcast.domain.User" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>demo1</title> </head> <body> <% User user = new User(); user.setUsername("jack"); request.setAttribute("user", user); %> <c:if test="${empty user}"> //Hello, please log in... </c:if> <c:if test="${not empty user}"> //Hello${user.username} </c:if> <c:choose> <c:when test="${pageScope.score eq 'A' }"> AAA </c:when> <c:when test="${pageScope.score eq 'B' }">BBB </c:when> <c:when test="${pageScope.score eq 'C' }">CCC </c:when> <c:when test="${pageScope.score eq 'D' }">DDD </c:when> <c:otherwise>other</c:otherwise> </c:choose> </body> </html>
② c:forEach label
* amount to java In for loop 1)ordinary for for(int i=1; i<=5; i++){ i } <c:forEach begin="1" end="5" step="1" var="i"> ${i} </c:forEach> begin="1" Starting value (including) end="5" End value (including) step="1" Step 1 var="i" Current output temporary variable 2)enhance for for(User user : list){ user } <c:forEach items="${list}" var="user" varStatus="vs"> ${user} </c:forEach> items="list" aggregate var="user" Temporary variable for current output varStatus="vs" Variable status index Current index starts from 0 count Counter starts at 1
<%@ page import="java.util.ArrayList" %> <%@ page import="java.util.Collections" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- 1. prefix : prefix (Differentiate between different libraries) 2. uri : Identification of the library core : java Core code -> label xml : xml grammar -> label <c:if> <x:if> --%> <html> <head> <title>Title</title> </head> <body> <!-- //Using jstl tag library 1. web-inf/lib Import jstl Two libraries 2. instructions taglib //Learn two labels 1. c:if a. Essential attributes test= el expression b. test bytrue,The content of the label body will be executed 2. c:foreach a. ordinaryforloop b. enhanceforloop --> <div> <% int n = 10; request.setAttribute("n",n); %> <% if(n > 5){ out.print("ha-ha"); } %> <c:if test="${n > 6}"> //Hee hee </c:if> </div> <hr> <div> <%-- 2. c:foreach a. ordinaryforloop var : variable Variable assigned by loop (Will be deposited pageContext In domain object,So use el Expression access) begin: Starting value end : End value step : step(Default is1) b. enhanceforloop var : ditto items : Traversed collection or array varStatus : Record the status of the current loop index : Indexes count : count --%> <% for (int i = 0; i <= 9; i+=2) { out.print(i + " "); } %> <br> <c:forEach var="i" begin="0" end="9" step="2"> ${i} </c:forEach> <br> <% ArrayList<String> list = new ArrayList<>(); Collections.addAll(list,"Zhang San","Li Si","Wang Wu"); request.setAttribute("list",list); for (String element : list) { out.print(element + " "); } %> <br> <c:forEach var="element" items="${list}" varStatus="status"> ${status.index}, ${status.count}, ${element} <br> </c:forEach> </div> </body> </html>
Three c:out output and c:set to set value in the field
<%-- Set value to domain object, default pageScope --%> <c:set var="username" value="abc"/> <%-- Sets a value to the specified domain object--%> <c:set var="username" value="bcd" scope="application"/> <%-- String splicing--%> <c:set var="username" value="${'123'.concat('456')}" scope="request"/> <%-- Get value --%> <br><br><br><br><br> username: ${username} <br> pageScope.username: ${pageScope.username} <br> requestScope.username: ${requestScope.username} <br> sessionScope.username: ${sessionScope.username} <br> applicationScope.username: ${applicationScope.username} <br>
<%-- Set value to domain object, default pageScope --%> <c:set var="username" value="abc"/> <%-- Sets a value to the specified domain object--%> <c:set var="username" value="bcd" scope="application"/> <%-- String splicing--%> <c:set var="username" value="${'123'.concat('456')}" scope="request"/> <%-- Get value --%> <br><br><br><br><br> username: ${username} <br> pageScope.username: ${pageScope.username} <br> requestScope.username: ${requestScope.username} <br> sessionScope.username: ${sessionScope.username} <br> applicationScope.username: ${applicationScope.username} <br>
Filter in three Servlet specification
3.1 three components of Java Web
assembly | effect | Implementation interface |
---|---|---|
Servlet | Small applications, mainly used as controllers in Java Web, can handle user's requests and respond | javax.servlet.Servlet |
Filter | Filter, which processes requests or responses sent by users in a centralized way to intercept requests | javax.servlet.Filter |
Listener | Listener, which is used in some frameworks (such as spring). During Web execution, events are raised to handle the corresponding events | javax.servlet.XxxListener Each event has an interface |
3.2 general
Filter, one of the three components of Java Web. The other two are Servlet and Listener.
It is an interface added to the Servlet 2.3 specification released in 2000. It is a very practical technology in Servlet specification.
It can intercept all resources in web application, and do some special operations after interception.
Common application scenarios: URL level permission control; filtering sensitive words; Chinese scrambling, etc.
Filters in life
Water purifier, air purifier, subway security inspection
Filters in the web
When the user accesses the server resource, the filter intercepts the request and completes some general operations
Application scenario
For example: login verification, unified coding, sensitive character filtering
3.3 quick start
//@WebServlet(value = {"/MyServlet"}) //@WebServlet(value = "/MyServlet") / / the array property of the annotation has only one value, and {} can be removed //@WebServlet(value = "/MyServlet") / / only one attribute of the annotation needs to be assigned, and the attribute name is value. Value = can be omitted //@WebServlet("/MyServlet") @WebServlet(value = {"/MyServlet","/MyServlet2"}) //One servlet configures multiple virtual paths public class MyServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("resources: servlet Was interviewed"); } }
3.31xml configuration
① Write java class and implement filter interface
/* * 1. Define a class to implement the Filter interface (note the package name) * 2. to configure web.xml (or note) * */ public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("Filter intercepted request"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
② Configuration web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- filter Of web.xml to configure 1. filter and filter-mapping Child tags for filter-name Must be consistent(Can be customized,Usually the same as the class name) 2. url-pattern : current filter Virtual path to intercept --> <filter> <filter-name>MyFilter</filter-name> <filter-class>com.itheima01.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/MyServlet</url-pattern> </filter-mapping> </web-app>
3.32 annotation configuration
Write java class and implement filter interface
@WebFilter(value = "/MyServlet2") public class MyFilter2 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("Filter intercept request 2"); //Release filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
3.4 working principle
1)Filter
2)FilterConfig
3)FilterChain
- Users send requests and request Web resources (including index,jsp,servlet, etc.)
- If the address of the Web resource matches the address of the filter, the request will go through the filter first and execute doFilter()
- If the doFilter() method is called chain.doFilter(), the next Web resource is released for execution.
- After accessing the Web resources, the response will go through the filter again, execute the code in the filter, and reach the browser side.
3.41 life cycle
1) Life cycle
Born alive dead
**Birth: * * instantiation and initialization methods are executed when the application is loaded.
**Alive: * * as long as the application has been providing services, the object always exists.
**Death: * * when the application is uninstalled or the server is down, the object dies.
There is only one instance object of Filter in memory. So it's a single case.
// Initialization method public void init(FilterConfig config); // Execute interception method public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain); // Destruction method public void destroy();
*Create The server starts the project loading, creates the filter object, and executes the init method (only once) *Run (filter intercept) When the user accesses the blocked target resource, execute the doFilter method *Destruction When the server closes the project uninstall, destroy the filter object and execute the destroy method (only once) *Add: Filters must be created prior to servlets and then destroyed after servlets
/* * Filter Life cycle approach to * 1. init * a. filter Is created when tomcat starts loading (prior to servlet creation) * b. This method can only be executed once, and is generally used to initialize data * 2. doFilter * a. Browser will execute every time it accesses * b. There's a way chain.doFilter(req, resp); * If not called, subsequent resources will not be executed * If called, subsequent resources execute * c. This method intercepts the request and the response * 3. destroy * a. tomcat Call this method before closing (after the servlet destroyed) * b. This method can only be executed once, and is generally used to serialize data and release resources * */ @WebFilter(urlPatterns = "/LifeServlet") public class LifeFilter implements Filter { public void init(FilterConfig config) throws ServletException { System.out.println("filter init"); } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("filter doFilter before"); /* Release: allows requests to continue to be passed back a. Similar to the previous request forwarding b. If the subsequent resource is a servlet, execute the service method */ chain.doFilter(req, resp); System.out.println("filter doFilter after"); } public void destroy() { System.out.println("filter destroy"); } }
// Load on starup: load when Tomcat starts @WebServlet(value = "/LifeServlet",loadOnStartup = 4) public class LifeServlet implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { System.out.println("servlet init"); } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("servlet service"); } @Override public void destroy() { System.out.println("servlet destroy"); } @Override public ServletConfig getServletConfig() { return null; } @Override public String getServletInfo() { return null; } }
3.42 interception path
In development, we can specify the interception path of the filter to define the scope of intercepting target resources
*Exact match The user accesses the specified target resource (/ show.jsp )When the filter intercepts *Directory matching When users access all resources in the specified directory (/ user / *), the filter intercepts them *Suffix matching When the user accesses the resource with the specified suffix name (*. html), the filter intercepts *Match all When users visit all resources of the website (/ *), the filter will intercept them
/* #Matching pattern of interception path * Exact match The user accesses the specified target resource (/ show.jsp )When the filter intercepts * Directory matching When users access all resources in the specified directory (/ user / *), the filter intercepts them * Suffix matching When the user accesses the resource with the specified suffix name (*. html), the filter intercepts * Match all When users visit all resources of the website (/ *), the filter will intercept them url Format: Protocol: / / ip:port / resource location * */ //@WebFilter(urlPatterns = "/doc/hello.html ") / / accurate interception //@WebFilter(urlPatterns = "/doc / *") / / block all resources in doc directory //@WebFilter("*.html") / / block all resources that are html //@WebFilter("/*") @WebFilter(urlPatterns = {"/doc/hello.html","/index.jsp"}) public class UrlFilter implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("Intercepted"); chain.doFilter(req, resp); } public void destroy() { } }
3.43 interception mode
In development, we can specify the filter interception method to handle different application scenarios, such as: only intercepting requests sent directly from the browser, or intercepting requests forwarded internally
There are five different interception methods in total. Here we learn two common ones 1. request (default interception method) When the browser sends the request directly, block 2. forward When requesting forwarding, intercept For example, when resource A is forwarded to resource B We can configure two to exist at the same time
① xml version
public class MethodFilter implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("method Intercepted"); chain.doFilter(req, resp); } public void destroy() { } }
<filter> <filter-name>MethodFilter</filter-name> <filter-class>com.itheima04.method.MethodFilter</filter-class> </filter> <filter-mapping> <filter-name>MethodFilter</filter-name> <url-pattern>/doc/hello.html</url-pattern> <!-- dispatcher: used to specify the interception method 1. Request (default): the request directly sent by the browser 2. FORWARD: request forwarded Can be set at the same time --> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
② Annotation version
//@WebFilter(urlPatterns = "/doc/hello.html",dispatcherTypes = {DispatcherType.FORWARD,DispatcherType.REQUEST}) @WebFilter(urlPatterns = "/doc/hello.html",dispatcherTypes = DispatcherType.FORWARD) public class MethodFilter implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("method Intercepted"); chain.doFilter(req, resp); } public void destroy() { } }
<! -- configure fi lt er -- > <filter> <filter-name>FilterDemo1</filter-name> <filter-class>com.itheima.web.filter.FilterDemo1</filter-class> <! -- configure to enable asynchronous support. When dispatcher configures ASYNC, you need to configure this line -- > <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>FilterDemo1</filter-name> <url-pattern>/ServletDemo1</url-pattern> <! -- filter request: default. > <dispatcher>REQUEST</dispatcher> <! -- filter global error page: when the global error page is called by the server, the filter works -- > <dispatcher>ERROR</dispatcher> <! -- filter request forwarding: when a request is forwarded, the filter works. > <dispatcher>FORWARD</dispatcher> <! -- filter request contains: when the request contains, the filter works. It can only filter dynamic include, and the include instruction of jsp is static include -- > <dispatcher>INCLUDE</dispatcher> <! -- filter asynchronous type, which requires us to configure enable asynchronous support in the filter tag -- > <dispatcher>ASYNC</dispatcher> </filter-mapping>
3.44 filter chain
In one request, if our request matches multiple filters, the request is equivalent to stringing these filters together to form a filter chain
*Demand User access to target resources show.jsp After filtera filterb *Filter chain execution sequence (first in first out) 1. User sends request 2. Filter a intercept and release 3. Filter B intercept and release 4. Implementation target resources show.jsp 5.FilterB enhanced response 6. Filter a enhanced response 7. Encapsulate the response message format and return it to the browser *The priority of execution in the filter chain configuration file The first to declare, the first to execute <filter-mapping> Note [not recommended] Sort according to the filter class name, execute first if the value is small FilterA filterb for comparison, FilterA first execute
//@WebFilter(urlPatterns = "/ServletA") public class FilterA implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("FilterA Executed"); /* * Release: allow the request to continue to pass later * 1. Equivalent to request forwarding * 2. If there is a filter later, execute the filter first, and then go to the resource until the filter is finished * */ chain.doFilter(req, resp); } public void destroy() { } }
//@WebFilter(urlPatterns = "/ServletA") public class FilterB implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("FilterB Executed"); chain.doFilter(req, resp); } public void destroy() { } }
<filter> <filter-name>FilterB</filter-name> <filter-class>com.itheima05.chain.FilterB</filter-class> </filter> <filter-mapping> <filter-name>FilterB</filter-name> <url-pattern>/ServletA</url-pattern> </filter-mapping> <filter> <filter-name>FilterA</filter-name> <filter-class>com.itheima05.chain.FilterA</filter-class> </filter> <filter-mapping> <filter-name>FilterA</filter-name> <url-pattern>/ServletA</url-pattern> </filter-mapping>
Order of execution of multiple filters
web.xml to configure
And the order in which the configuration files are written determines the order in which they are run. To be precise, the order in which they are mapped (top-down execution)
Annotation development
Annotation development without configuration file
According to the natural order of class names: A-B-C
If a profile exists, the profile takes precedence
3.5 filter case
3.5.1 unified website coding
demand
In Tomcat 8.5, the Chinese code of get request has been solved, but the Chinese code of post request still exists
Any request sent by the browser will be processed by the filter in a unified way
requirement analysis
code implementation
- In real-world scenarios, filters do not respond to mime types uniformly
@WebFilter(urlPatterns = "/*") // Whole station interception public class PostFilter implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; // reference type req address 0x0001 HttpServletResponse response = (HttpServletResponse) resp; String method = request.getMethod(); if("POST".equalsIgnoreCase(method)){ request.setCharacterEncoding("utf-8"); } chain.doFilter(req, resp); } public void destroy() { } }
3.5.2 illegal character interception
demand
When the user sends out illegal speech, it will prompt the user with illegal speech warning message
requirement analysis
code implementation
① Illegal Thesaurus
Pay attention to modify the format of read properties, and unify utf-8, otherwise it will be garbled
② WordsFilter
@WebFilter("/WordsServlet") public class WordsFilter implements Filter { private List<String> wordList; public void init(FilterConfig config) throws ServletException { // 1. Load configuration file /* ResourceBundle Specially read the properties configuration file under the src directory without writing the suffix */ ResourceBundle words = ResourceBundle.getBundle("words"); // 2. Read the keyword content String keyword = words.getString("keyword"); // Silly fork, uncle's, second uncle's // 3.split cutting, to list set wordList = Arrays.asList(keyword.split(",")); System.out.println("Load illegal Thesaurus:"+wordList); } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { // Downward transformation HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // 1. Get the value entered by the user String content = request.getParameter("content"); // 2. Intercept illegal content, prompt for (String word : wordList) { // Traversal illegal Thesaurus if(content.contains(word)){ // Determine whether illegal words are included response.getWriter().write("The words you input are sensitive, blocking..."); return; } } // 3. Release chain.doFilter(request, response); } public void destroy() { } }
Listener in the four Servlet specification
4.1 General
Monitor in life
Many of our shopping malls have cameras that monitor customers' every move. If the customer has illegal behavior, the mall can take corresponding measures.
Observer design pattern
Observer design pattern. Because all the monitors are the embodiment of the observer design pattern.
What is the observer design pattern?
It is an embodiment of event driven. It's like being stared at while doing something. When something is done, trigger the event.
The observer pattern usually consists of three parts:
Event source: the object that triggered the event.
Event: the triggered action, which encapsulates the event source.
Listener: what to do when an event source triggers an event. Generally, it is an interface implemented by the user.
Listener in Java Web
In our java program, sometimes we need to monitor something. Once the monitored object changes correspondingly, we should take corresponding actions.
Listen to three major web domain objects: HttpServletRequest, HttpSession, and ServletContext (create and destroy)
scene
Historical access times, statistics of online population, initialization configuration information at system startup
Interface classification of listeners
Event source | listener interface | opportunity |
---|---|---|
ServletContext | ServletContextListener | Context domain creation and destruction |
ServletContext | ServletContextAttributeListener | The operation of adding, deleting, and modifying context domain properties |
**HttpSession ** | HttpSessionListener | Session domain creation and destruction |
**HttpSession ** | HttpSessionAttributeListener | Adding, deleting and modifying session domain properties |
HttpServletRequest | ServletRequestListener | Request domain creation and destruction |
HttpServletRequest | ServletRequestAttributeListener | Operation of adding, deleting and modifying domain attribute |
4.2 quick start
The listener is used less in web development, and there is less chance to see it. Today, we use servletcontextlistener to lead you to learn about the listener, because this listener is the most frequently used one among the listeners, and the way it is used is almost the same.
We can use this listener to do something when the project is started and destroyed, such as loading the configuration file when the project is started.
Step analysis
1. Create a common class to implement servletcontextlistener 2. Rewrite abstract methods Listen to ServletContext creation Listen to ServletContext destroy 3. Configuration web.xml annotation
① xml version
/* * 1. Define a class to implement the ServletContextListener interface and rewrite the method * (Listen for the creation and destruction of ServletContext) * * 2. to configure web.xml (or note) * * */ public class MyServletContextListener implements ServletContextListener { /* * ServletContext Once when created * */ @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("ServletContext Created"); } /* * ServletContext Once for destruction * */ @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("ServletContext Destroyed"); } }
<listener> <listener-class>com.itheima07.listener.MyServletContextListener</listener-class> </listener>
② Annotation version
@WebListener public class MyListener implements ServletContextListener { // Listen to ServletContext creation @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("ServletContext Already created..."); } // Listen to ServletContext destroy @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("ServletContext It's destroyed...."); } }
4.3 introduction of 8 listeners in servlet specification
Created by listening object
1)ServletContextListener
/** * Listener for listening to ServletContext object creation and destruction * @since v 2.3 */ public interface ServletContextListener extends EventListener { /** * This method is executed when the object is created. The parameter of this method is the ServletContextEvent event object, and the event is the action of create object * Event object encapsulates the source of triggering event, that is, event source, namely ServletContext */ public default void contextInitialized(ServletContextEvent sce) { } /** * Object destroy execute this method */ public default void contextDestroyed(ServletContextEvent sce) { } }
2)HttpSessionListener
/** * Listener for listening to HttpSession object creation and destruction * @since v 2.3 */ public interface HttpSessionListener extends EventListener { /** * This method is executed when the object is created. */ public default void sessionCreated(HttpSessionEvent se) { } /** * Object destroy execute this method */ public default void sessionDestroyed(HttpSessionEvent se) { } }
3)ServletRequestListener
/** * Listener for listening to ServletRequest object creation and destruction * @since Servlet 2.4 */ public interface ServletRequestListener extends EventListener { /** * This method is executed when the object is created. */ public default void requestInitialized (ServletRequestEvent sre) { } /** * Object destroy execute this method */ public default void requestDestroyed (ServletRequestEvent sre) { } }
When the properties of the listening domain change
1)ServletContextAttributeListener
/** * Listener used to listen for property changes in the ServletContext domain (application domain) * @since v 2.3 */ public interface ServletContextAttributeListener extends EventListener { /** * Property is added to the domain to trigger this method. The parameter is the ServletContextAttributeEvent event object, and the event is add attribute. * Event object encapsulates event source, namely ServletContext. * When the ServletContext executes the setAttribute method, this method knows and executes. */ public default void attributeAdded(ServletContextAttributeEvent scae) { } /** * Property removed from domain triggers this method */ public default void attributeRemoved(ServletContextAttributeEvent scae) { } /** * Property change in domain triggers this method */ public default void attributeReplaced(ServletContextAttributeEvent scae) { } }
2)HttpSessionAttributeListener
/** * Listener for listening for property changes in HttpSession domain (session domain) * @since v 2.3 */ public interface HttpSessionAttributeListener extends EventListener { /** * Property is added to the domain to trigger this method. */ public default void attributeAdded(HttpSessionBindingEvent se) { } /** * Property removed from domain triggers this method */ public default void attributeRemoved(HttpSessionBindingEvent se) { } /** * Property change in domain triggers this method */ public default void attributeReplaced(HttpSessionBindingEvent se) { } }
3)ServletRequestAttributeListener
/** * Listener used to listen for property changes in the ServletRequest domain (request domain) * @since Servlet 2.4 */ public interface ServletRequestAttributeListener extends EventListener { /** * Property is added to the domain to trigger this method. */ public default void attributeAdded(ServletRequestAttributeEvent srae) { } /** * Property removed from domain triggers this method */ public default void attributeRemoved(ServletRequestAttributeEvent srae) { } /** * Property change in domain triggers this method */ public default void attributeReplaced(ServletRequestAttributeEvent srae) { } }
Two perceptual listeners related to conversation
Here I want to make it clear to the students that the two perceptual listeners related to the conversation domain do not need to be configured, just write the code directly.
1)HttpSessionBinderListener
/** * Listener for sensing objects and session domain binding * When data is added to or removed from the session domain, two methods of this listener are executed. * Joining the session domain is bound to the session domain * Remove from session domain and unbind from session domain */ public interface HttpSessionBindingListener extends EventListener { /** * When data is added to the session domain, that is, binding, this method executes */ public default void valueBound(HttpSessionBindingEvent event) { } /** * When removed from the session domain, that is, unbound, this method performs */ public default void valueUnbound(HttpSessionBindingEvent event) { } }
2)HttpSessionActivationListener
/** * Listener for passive and active objects in session domain */ public interface HttpSessionActivationListener extends EventListener { /** * This method executes when data in the session domain is passivated */ public default void sessionWillPassivate(HttpSessionEvent se) { } /** * This method executes when data in the session domain is activated */ public default void sessionDidActivate(HttpSessionEvent se) { } }
4.4 case: Simulation of spring framework
- Configuration files can be read at project startup
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--Global configuration parameters--> <context-param> <param-name>configLocation</param-name> <param-value>words.properties</param-value> </context-param> </web-app>
@WebListener public class MyListener implements ServletContextListener { // Listen to ServletContext creation /* ServletContextEvent Context event object, get ServletContext */ @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("ServletContext Already created..."); // Get the context object through servletContextEvent ServletContext servletContext = servletContextEvent.getServletContext(); // I can load the name of the company definition Profile String configLocation = servletContext.getInitParameter("configLocation"); System.out.println("Get profile name dynamically:" + configLocation); } // Listen to ServletContext destroy @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("ServletContext It's destroyed...."); } }
4.5 case: Statistics of online population
demand
If users use the website, the number of online users will be + 1; if users exit the website, the number of online users will be - 1
technical analysis
Total number of people online using ServletContext domain objects
Using the ServletContextListener listener, when the project is started, the total number of initializers is 0
Use HttpSessionListener listener, user access, number + 1, user exit, number - 1
Use the LogoutServlet controller to destroy the session of the current session
requirement analysis
code implementation
① InitNumberListener
@WebListener public class InitNumberListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { // Get context domain object ServletContext servletContext = servletContextEvent.getServletContext(); // Initialize online population servletContext.setAttribute("number", 0); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
② NumberChangeListener
@WebListener public class NumberChangeListener implements HttpSessionListener { // Session establishment, number of people online + 1 @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { // Get session domain object HttpSession session = httpSessionEvent.getSession(); // Get context domain object ServletContext servletContext = session.getServletContext(); // Take out the number of people online Integer number = (Integer) servletContext.getAttribute("number"); // +1 servletContext.setAttribute("number", number + 1); } // Session destruction, number of people online-1 @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { // Get session domain object HttpSession session = httpSessionEvent.getSession(); // Get context domain object ServletContext servletContext = session.getServletContext(); // Take out the number of people online Integer number = (Integer) servletContext.getAttribute("number"); // -1 servletContext.setAttribute("number", number - 1); } }
③ index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>${NAME}</title> </head> <body> <h3>listener Knowledge learning</h3> <h5>Number of people online: ${applicationScope.number}</h5> <a href="${pageContext.request.contextPath}/LogoutServlet">User exit</a> </body> </html>
④ LogoutServlet
@WebServlet("/LogoutServlet") public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Destroy session request.getSession().invalidate(); response.getWriter().write("logout"); } }