EL&Filter&Listener- Teaching

1 EL Expression and JSTL

1.1 EL expression

1.1.1 EL Expression Introduction ***

  • EL(Expression Language): Expression language

  • stay JSP 2.0 What's added to the specification , It's also Servlet Part of the norm

  • effect : stay JSP Get data from the page . Let's have JSP Out of the java Block of code and JSP expression

  • grammar :${ Expression content }

  • for example :

1.1.2 EL A quick start to expressions

  1. Create a web project :el_demo, Virtual directory /el

  2. stay web Create under directory el01.jsp

  3. Add data to the domain object in the file

  4. There are three ways to get data from domain objects (java Code block 、JSP expression 、EL expression )

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>EL Getting started with expressions </title>
    </head>
    <body>
      <%--1. Add data to the domain object --%>
      <% request.setAttribute("username","zhangsan"); %>

      <%--2. get data --%>
      Java Code block :<% out.println(request.getAttribute("username")); %> <br>

      JSP expression :<%= request.getAttribute("username")%> <br>

      EL expression :${username}
    </body>
    </html>
  5. Deploy and launch the project

  6. Pass the browser test

1.1.3 EL Expressions get different types of data ***

  • The data type to get

    1. Get data of basic data type

    2. Get data of custom object type

    3. Get data of array type

    4. obtain List Set type data

    5. obtain Map Set type data

  • Case study : newly build el02.jsp

    <%@ page import="com.itheima.bean.Student" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page import="java.util.HashMap" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>EL Expressions get different types of data </title>
    </head>
    <body>
      <%--1. Get basic data types --%>
      <% pageContext.setAttribute("num",10); %>
      Basic data type :${num} <br>

      <%--2. Get custom object type --%>
      <%
           Student stu = new Student(" Zhang San ",23);
           pageContext.setAttribute("stu",stu);
      %>
      Custom object :${stu} <br>
      <%--stu.name Realization principle getName()--%>
      The student's name :${stu.name} <br>
      Student age :${stu.age} <br>

      <%--3. Get array type --%>
      <%
           String[] arr = {"hello","world"};
           pageContext.setAttribute("arr",arr);
      %>
      Array :${arr}  <br>
      0 Index element :${arr[0]} <br>
      1 Index element :${arr[1]} <br>
      <%--EL There is no string concatenation in the expression --%>
      0 Index stitching 1 Elements of index :${arr[0]} + ${arr[1]} <br>

      <%--4. obtain List aggregate --%>
      <%
           ArrayList<String> list = new ArrayList<>();
           list.add("aaa");
           list.add("bbb");
           pageContext.setAttribute("list",list);
      %>
      List aggregate :${list} <br>
      0 Index element :${list[0]} <br>

      <%--5. obtain Map aggregate --%>
      <%
           HashMap<String,Student> map = new HashMap<>();
           map.put("hm01",new Student(" Zhang San ",23));
           map.put("hm02",new Student(" Li Si ",24));
           pageContext.setAttribute("map",map);
      %>
      Map aggregate :${map}  <br>
      The first student object :${map.hm01}  <br>
      The name of the first student :${map.hm01.name}

    </body>
    </html>
  • visit

1.1.4 EL Note on expressions

  • EL Expression has no null pointer exception

  • EL Expression has no index out of bounds exception

  • EL There is no concatenation of strings in an expression (el Expression + You can only add numbers )

  • Code

    • Null pointer

    • Crossing boundaries and string splicing

  • visit

1.1.5 EL The operator of the expression

  • Relational operator

  • Logical operators

  • Other operators

    • Whether the container element is 0, Is whether the length of the container is 0( It's just checking to see if the container is empty )

  • Case study : newly build el03.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>EL Expression operators </title>
    </head>
    <body>
      <%--empty--%>
      <%
           String str1 = null;
           String str2 = "";
           int[] arr = {};
      %>
      ${empty str1} <br>
      ${empty str2} <br>
      ${empty arr} <br>

      <%-- Ternary operator . Get gender data , Check the corresponding button ***--%>
      <% pageContext.setAttribute("gender","men"); %>
       <input type="radio" name="gender" value="men" ${gender == "men" ? "checked" : ""}> male
       <input type="radio" name="gender" value="women" ${gender == "women" ? "checked" : ""}> Woman
    </body>
    </html>
  • visit

1.1.6 EL Expressions use details ***

  • EL Expressions can get the data of four field objects , Search in domain objects from small to large by name

  • You can also get JSP The other eight implicit objects , And call methods in the object

  • Case study :el04.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>EL Expressions use details </title>
    </head>
    <body>
      <%-- Get the data in the four domain objects --%>
      <%
           //pageContext.setAttribute("username","zhangsan");
           request.setAttribute("username","zhangsan");
           //session.setAttribute("username","zhangsan");
           //application.setAttribute("username","zhangsan");
      %>
      ${username} <br>

      <%--pageContext Page domain get JSP The other eight implicit objects in   Get the virtual directory name --%>
      <%= request.getContextPath()%>   <%--jsp Can be obtained directly from request Four domain objects , Because there are these implicit objects --%>
      ${pageContext.request.contextPath} <%--el expression , You can only get the other eight stealth objects through the page domain --%>
      <%--${request.contextPath} <%--el expression , You can't directly access eight implicit objects &ndash;%&gt;--%>
      ${contextPath} <%--el expression , You can directly access the shared data in the four domains , It's not a property --%>
    </body>
    </body>
    </html>
  • visit

1.1.7 EL Of expression 11 Implicit objects

EL Expressions also provide us with implicit objects , Let's use it without declaring it , Eleven objects are shown in the table below , It should be noted that , It and JSP It's not the same thing :

EL Implicit objects in type Corresponding JSP Implicit objects remarks
PageContext *** Javax.serlvet.jsp.PageContext PageContext Exactly the same as
ApplicationScope Java.util.Map No, Manipulate application domain object data
SessionScope Java.util.Map No, Operating session domain object data
RequestScope Java.util.Map No, Operation request domain object data
PageScope Java.util.Map No, Operate page domain object data
Header Java.util.Map No, according to key Get the request header , Value is a
HeaderValues Java.util.Map No, according to key Get the request header , Values are multiple ( Array )
Param Java.util.Map No, according to key Get request parameters , Value is a
ParamValues Java.util.Map No, according to key Get request parameters , Values are multiple ( Array )
InitParam Java.util.Map No, according to key Get global parameters ,value Is the parameter value
Cookie Java.util.Map No, according to key obtain cookie Value
  • Case study

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>EL expression 11 Implicit objects </title>
    </head>
    <body>
      <%--pageContext object You can get the other three domain objects and JSP Eight implicit objects in --%>
      ${pageContext.request.contextPath} <br>

      <%--applicationScope sessionScope requestScope pageScope Operate the data in the four domain objects --%>
      <% request.setAttribute("username","zhangsan"); %>
      ${username} <br>
      ${requestScope.username} <br>

      <%--header headerValues   Get request header data --%>
      ${header["connection"]} <br>
      ${headerValues["connection"][0]} <br>

      <%--param paramValues Get request parameter data --%>
      ${param.username} <br>
      ${paramValues.hobby[0]} <br>
      ${paramValues.hobby[1]} <br>

      <%--initParam Get global configuration parameters --%>
      ${initParam["pname"]}  <br>

      <%--cookie obtain cookie Information --%>
      ${cookie}  <br> <%-- obtain Map aggregate --%>
      ${cookie.JSESSIONID}  <br> <%-- obtain map The second element in the set --%>
      ${cookie.JSESSIONID.name}  <br> <%-- obtain cookie The name of the object --%>
      ${cookie.JSESSIONID.value} <%-- obtain cookie The value of the object --%>


    </body>
    </html>
  • visit

  • summary

    1. Get shared data in four domains : ${ Data name} ( It's all through xxx.setAttribute())
    2. according to pageContext Get other implicit objects :${pageContext.request.contextpath}
    Be careful : contextpath Not sharing data , He's a virtual path , Is an attribute , There is a corresponding one getter Method :getContextPath
    <% request.getContextPath() %>

1.2 JSTL

1.2.1 JSTL Introduction to

  • JSTL(Java Server Pages Standarded Tag Library):JSP Standard label library

  • It mainly provides developers with a standard general label library

  • Developers can use these tags instead of JSP On the page Java Code , So as to improve the readability of the program , Reduce the difficulty of program maintenance

  • It consists of the following 5 Component composition :

1.2.2 Core tag library

1) Core library Introduction

In our actual development , Use of jstl The tag library is mainly based on the core tag library , Occasionally we use tags from international tag libraries . The following table lists the tags we may use frequently here , Please refer to the rest of the tag library 【JSTL Tag library .doc】 file .

Tag name Functional categories classification effect
<c:if> Process control Core tag library Used to judge
<c:choose> ,<c:when>,<c:otherwise> Process control Core tag library Used to judge multiple conditions
<c:foreache> Iterative operations Core tag library For loop traversal

2) Case study ***

  1. Create a web project :jstl_demo

  2. stay web Create one in the directory WEB-INF Catalog

  3. stay WEB-INF Create one in the directory libs Catalog , take JSTL Of jar Package import

    • (jar Package directory :day05_el Expression filter listener \ Information \JSTL Of jar package )

    • Add Reference Library

  4. establish JSP file , adopt taglib Import JSTL Tag library

  5. Use tags for process control and iteration traversal

    • newly build jstl01.jsp: Process control

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <!--prefix to jstl core The core library has a prefix name , The label used is c start -->
      <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      <html>
      <head>
         <title> Process control </title>
      </head>
      <body>
        <%-- Add grade data to the domain object --%>
        ${pageContext.setAttribute("score","T")}

        <%-- Judge your grades --%>
         <c:if test="${score eq 'A'}">
            good
         </c:if>

        <%-- Make a multi condition judgment on the results --%>
         <c:choose>
             <c:when test="${score eq 'A'}"> good </c:when>
             <c:when test="${score eq 'B'}"> good </c:when>
             <c:when test="${score eq 'C'}"> pass </c:when>
             <c:when test="${score eq 'D'}"> Poor </c:when>
             <c:otherwise> Illegal grades </c:otherwise>
         </c:choose>
      </body>
      </html>
    • newly build jstl02.jsp: Iterate through

      <%@ page import="java.util.ArrayList" %>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      <html>
      <head>
         <title> loop </title>
      </head>
      <body>
        <%-- Add a collection to a domain object --%>
        <%
             ArrayList<String> list = new ArrayList<>();
             list.add("aa");
             list.add("bb");
             list.add("cc");
             list.add("dd");
             pageContext.setAttribute("list",list);
        %>

        <%-- Ergodic set --%>
         <c:forEach items="${list}" var="str">
            ${str} <br>
         </c:forEach>
      </body>
      </html>
  6. Deploy and launch the project

  7. View... Through a browser

    • visit jstl01

    • visit jstl02

  1. problem : Error report of project operation

  2. solve :

2 Servlet Filters in the specification -Filter

2.1 Filter entry

2.1.1 Introduction of filter ***

  • filter ——Filter, It is JavaWeb One of the three components . The other two are Servlet and Listener

  • It can be to web All resources in the application are intercepted , And do some special operations after interception

  • When accessing server resources in a program , When a request comes , The server first determines whether a filter is associated with the requested resource , If there is , Filters can intercept requests , Complete some specific functions , The filter then decides whether to give it to the request resource . If not, request resources directly as before . The response is similar !

  • Filters are generally used to perform general operations , for example : validate logon 、 Unified coding 、 Sensitive character filtering and so on ~~~

    • Handle Universal operation : Unified coding

    • Handle Intercept operation : Permission to check , If you have permission, let it go , If not, intercept

    • Filters do two things : Intercept , Screening / Filter

  • Picture of the filter

  • Examples in life

    • Like a couple getting married , Regulations : Only guests with red envelopes can have dinner , You can't eat without it

    • Then it's impossible for the newcomers to do the work themselves , They invited two people , One takes the money , One is in charge of bookkeeping ( These two are the filters )

2.1.2 Filter Introduce ***

  • Filter It's an interface , If you want to realize the function of filter , The interface must be implemented

  • The core approach

  • Configuration mode

    • Annotation mode

    • The configuration file

  • Filter website

2.1.3 FilterChain ***

  • FilterChain It's an interface , Represents the filter chain object . from Servlet Containers provide implementation class objects , It can be used directly .

    • chain: [tʃeɪn] chain

  • Filters can define multiple , It will form a chain of filters

  • The core approach

  • website

2.1.4 Use of filters ***

  • Requirement specification

    • adopt Filter The filter solves the problem of multiple resources writing Chinese garbled code

  • The ultimate goal

    • Through this demand , Finally master Filter Use of filters

  • Implementation steps

    1. Create a web project :filter_demo, Virtual path /filter

    2. Create two Servlet Functional class , Write Chinese data to the client

      • newly build ServletDemo01:

        package com.itheima.servlet;

        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;

        @WebServlet("/servletDemo01")
        public class ServletDemo01 extends HttpServlet {
           @Override
           protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
               System.out.println("servletDemo01 Yes ...");
               //resp.setContentType("text/html;charset=UTF-8");
               resp.getWriter().write("servletDemo01 Yes ...");
          }

           @Override
           protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
               doGet(req,resp);
          }
        }
      • newly build ServletDemo02:

        package com.itheima.servlet;

        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;

        @WebServlet("/servletDemo02")
        public class ServletDemo02 extends HttpServlet {
           @Override
           protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
               System.out.println("servletDemo02 Yes ...");
               //resp.setContentType("text/html;charset=UTF-8");
               resp.getWriter().write("servletDemo02 Yes ...");
          }

           @Override
           protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
               doGet(req,resp);
          }
        }
      • visit

      • Find out demo1 and demo2 Is the code

      • It's all in the code before :resp.setContentType("text/html;charset=UTF-8"); To solve the problem of garbled code

      • But if there is 100 individual Servlet We need to solve the problem of garbled code ? We're going to write a hundred times ?

      • no need , Just use a filter

    3. Create a Filter Filter implementation class , rewrite doFilter The core approach

    4. Solve Chinese garbled code in method , And release

      package com.itheima.filter;

      import javax.servlet.*;
      import java.io.IOException;

      /*
          The filter basically uses
         /*: Indicates access to any resource in the current application , This filter will work
      */
      @WebFilter("/*")
      public class FilterDemo01 implements Filter{

         @Override
         public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
             System.out.println("filterDemo01 Yes ...");

             // Deal with the mess
             servletResponse.setContentType("text/html;charset=UTF-8");

             // release
             filterChain.doFilter(servletRequest,servletResponse);
        }
      }
    5. Deploy and launch the project

    6. Pass the browser test

2.1.5 Filter Details of the use of filters

  • Configuration mode

    • Annotation mode @WebFilter( Intercept path )

    • Configuration file mode

  • The order in which multiple filters are used

    • If there are multiple filters , Depending on the order of filter mapping

    • That is to say filter-mapping Order of configuration

  • Case study

    • take demo1 Of WebFilter Note masking

    • newly build FilterDemo02:

      package com.itheima.filter;

      import javax.servlet.*;
      import java.io.IOException;

      /*
          The filter basically uses
      */
      //@WebFilter("/*")
      public class FilterDemo02 implements Filter{

         @Override
         public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
             System.out.println("filterDemo02 Yes ...");

             // Deal with the mess
             servletResponse.setContentType("text/html;charset=UTF-8");

             // release
             filterChain.doFilter(servletRequest,servletResponse);
        }
      }
    • To configure filter

       <filter>
             <filter-name>filterDemo01</filter-name>
             <filter-class>com.itheima.filter.FilterDemo01</filter-class>
         </filter>
         <filter-mapping>
             <filter-name>filterDemo01</filter-name>
             <url-pattern>/*</url-pattern>
         </filter-mapping>

         <filter>
             <filter-name>filterDemo02</filter-name>
             <filter-class>com.itheima.filter.FilterDemo02</filter-class>
         </filter>
         <filter-mapping>
             <filter-name>filterDemo02</filter-name>
             <url-pattern>/*</url-pattern>
         </filter-mapping>
  • visit

2.1.6 Life cycle

  • establish ( born )

    • When the application loads, the object is instantiated and executed init Initialization method

  • service ( Alive )

    • The process of providing services by objects , perform doFilter Method

    • As long as the app provides services , The object has always been

  • The destruction ( Death )

    • The object is destroyed when the application is unloaded or when the server stops . perform destroy Method

  • Filter There is only one instance object in memory . So it's also a single case .

  • Case study : newly build FilterDemo03

    package com.itheima.filter;

    import javax.servlet.*;
    import java.io.IOException;

    /*
        Filter life cycle
    */
    //@WebFilter("/*")
    public class FilterDemo03 implements Filter{

       /*
            Initialization method
        */
       @Override
       public void init(FilterConfig filterConfig) {
           System.out.println(" Object initialization succeeded ...");
      }

       /*
            Service delivery method
        */
       @Override
       public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
           System.out.println("filterDemo03 Yes ...");

           // Deal with the mess
           servletResponse.setContentType("text/html;charset=UTF-8");

           // release
           filterChain.doFilter(servletRequest,servletResponse);
      }

       /*
            Destruction of objects
        */
       @Override
       public void destroy() {
           System.out.println(" The object is destroyed ...");
      }
    }
  • To configure : In order not to affect the test , Mask the configuration code of the previous two filters

    <filter>
       <filter-name>filterDemo03</filter-name>
       <filter-class>com.itheima.filter.FilterDemo03</filter-class>
    </filter>
    <filter-mapping>
       <filter-name>filterDemo03</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>
  • visit

2.1.7 FilterConfig Filter configuration object

  • FilterConfig It's an interface . Represents the configuration object of the filter , You can load some initialization parameters .

    • And ServletConfig similar

  • The core approach

  • website

  • Case study : newly build FilterDemo04

    package com.itheima.filter;

    import javax.servlet.*;
    import java.io.IOException;

    /*
        The use of filter configuration objects
    */
    //@WebFilter("/*")
    public class FilterDemo04 implements Filter{

       /*
            Initialization method
        */
       @Override
       public void init(FilterConfig filterConfig) {
           System.out.println(" Object initialization succeeded ...");

           // Get filter name
           String filterName = filterConfig.getFilterName();
           System.out.println(filterName);

           // according to name obtain value
           String username = filterConfig.getInitParameter("username");
           System.out.println(username);
      }

       /*
            Service delivery method
        */
       @Override
       public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
           System.out.println("filterDemo04 Yes ...");

           // Deal with the mess
           servletResponse.setContentType("text/html;charset=UTF-8");

           // release
           filterChain.doFilter(servletRequest,servletResponse);
      }

       /*
            Destruction of objects
        */
       @Override
       public void destroy() {
           System.out.println(" The object is destroyed ...");
      }
    }
  • filter To configure

    <filter>
    <filter-name>filterDemo04</filter-name>
    <filter-class>com.itheima.filter.FilterDemo04</filter-class>
    <init-param>
    <param-name>username</param-name>
    <param-value>zhangsan</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>filterDemo04</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
  • start-up tomcat

3 Servlet The listener in the specification -Listener

3.1 Observer design pattern ***

  • Before I introduce the listener , Let's popularize a knowledge with the students first , Observer design pattern .

  • Because all the listeners are the embodiment of the observer design pattern .

  • So what is the observer design pattern ?

  • It's an embodiment of event driven . It's like being watched when you're doing something , When doing something , Triggering event .

  • The observer model usually consists of the following three parts :

    • Event source : Object that triggered the event .

    • event : Trigger action , It encapsulates the event source .

    • Monitor : When the event source triggers the event , What to do . It's usually an interface , It's up to the user .( The idea here also involves a design pattern , We are JDBC The next day of the course, I will explain to the students , The strategy pattern )

      • After the event source triggers an event , The listener is listening to the process , And then execute a logic

    • Example : The dog found a man passing by the door , They'll bark ( watchdog )

  • Examples in life

    • The teacher made a rule , Once the teacher finds out the students 9 If you click later, you will be late , Then punish ,9 No punishment will be given to the students who come before

    • In this case , The source of the incident is students

    • The incident is late

    • The monitor is the teacher

  • About the monitor

    • In the process , We can : Object creation and destruction 、 Changes in attributes in domain objects 、 Listen for session related content

    • Servlet Standardize the plan of the Communist Party 8 A monitor , Listeners are provided in the form of interfaces , Specific functions need to be completed by ourselves

3.2 The listener of the listening object

1) ServletContextListener ***

  • ServletContextListener: For monitoring ServletContext Object creation and destruction

  • The core approach

    • Parameters :ServletContextEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say ServletContext

    • The real event is to create or destroy ServletContext Operations on objects

2) HttpSessionListener

  • HttpSessionListener: For monitoring HttpSession Object creation and destruction

  • The core approach

    • Parameters :HttpSessionEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say HttpSession

    • The real event is to create or destroy HttpSession Operations on objects

3) ServletRequestListener

  • ServletRequestListener: For monitoring ServletRequest Object creation and destruction

  • The core approach

    • Parameters :ServletRequestEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say ServletRequest

    • The real event is to create or destroy ServletRequest Operations on objects

3.3 A listener that listens to changes in the properties of domain objects

1) ServletContextAttributeListener

  • ServletContextAttributeListener: For monitoring ServletContext Changes in attributes in the application domain

  • The core approach

    • Parameters :ServletContextAttributeEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say ServletContext

    • The real event is to add 、 remove 、 Replacement of properties in the application domain

2) HttpSessionAttributeListener

  • HttpSessionAttributeListener: For monitoring HttpSession Property changes in the session domain

  • The core approach

    • Parameters :HttpSessionBindingEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say HttpSession

    • The real event is to add 、 remove 、 Replace the operation of the property in the session domain

3) ServletRequestAttributeListener

  • ServletRequestAttributeListener: For monitoring ServletRequest Changes in properties in the request domain

  • The core approach

    • Parameters :ServletRequestAttributeEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say ServletRequest

    • The real event is to add 、 remove 、 Replace the property in the request domain

3.4 Listening to session related perceptual listeners

1) HttpSessionBindingListener

  • HttpSessionBindingListener: Listener for sensing object and session domain binding

  • The core approach

    • Parameters :HttpSessionBindingEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say HttpSession

    • The real event is to add 、 Remove data from session domain

  • HttpSessionBindingListener and HttpSessionAttributeListener difference :

    1. Only when HttpSessionBindingListener Class , Add remove to session Domain will trigger binding , Unbundling method .
    2. Any object ( Whether it's realized or not HttpSessionAttributeListener) Trigger the corresponding event when it changes .

2) HttpSessionActivationListener

  • HttpSessionActivationListener: Listener for sensing passivation and activation of objects in session domain

  • The core approach

    • Parameters :HttpSessionEvent Represents the event object

    • The event source is encapsulated in the event object , That is to say HttpSession

    • The real event is data passivation in the session domain 、 The operation of activation

3.4 The use of listeners

  • In actual development , We can start from here according to the specific situation 8 Choose from two listeners to use

  • Perceptual listeners don't need to be configured , Just write the code according to the actual needs , So we won't show it here

  • We are in the remaining 6 Among them, select a listener to create, destroy and change the properties in the object domain

  • Show me the next two

3.4.1 ServletContextListener Use ***

  1. Create project :listener_demo, Virtual path /listener

  2. establish com.itheima.listener.ServletContextListenerDemo

    package com.itheima.listener;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener; /*
    ServletContext Listener for creation and destruction of objects
    // Configure listeners :@WebListener
    */
    @WebListener
    public class ServletContextListenerDemo implements ServletContextListener{
    /*
    ServletContext This method is executed when the object is created
    */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
    System.out.println(" Listening to object creation ..."); // Get objects
    ServletContext servletContext = sce.getServletContext();
    System.out.println(servletContext); } /*
    ServletContext Execute this method when the object is destroyed
    */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    System.out.println(" Monitored the destruction of the object ...");
    }
    }
  3. Start project :ServletContext It's created when the project starts , So here we just need to start tomcat

3.4.2 ServletContextAttributeListener Use

  1. newly build ServletContextAttributeListenerDemo

    package com.itheima.listener;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextAttributeEvent;
    import javax.servlet.ServletContextAttributeListener; /*
    Listeners that apply property changes in domain objects
    */
    @WebListener
    public class ServletContextAttributeListenerDemo implements ServletContextAttributeListener{
    /*
    Execute this method when adding properties to an application domain object
    */
    @Override
    public void attributeAdded(ServletContextAttributeEvent scae) {
    System.out.println(" Listening to the addition of attributes ..."); // Get the application domain object
    ServletContext servletContext = scae.getServletContext();
    // get attribute
    Object value = servletContext.getAttribute("username");
    System.out.println(value);
    } /*
    Execute this method when replacing properties into application domain objects
    */
    @Override
    public void attributeReplaced(ServletContextAttributeEvent scae) {
    System.out.println(" The replacement of the property is detected ..."); // Get the application domain object
    ServletContext servletContext = scae.getServletContext();
    // get attribute
    Object value = servletContext.getAttribute("username");
    System.out.println(value);
    } /*
    Execute this method when removing a property from an application domain object
    */
    @Override
    public void attributeRemoved(ServletContextAttributeEvent scae) {
    System.out.println(" Listening to removal of attribute ..."); // Get the application domain object
    ServletContext servletContext = scae.getServletContext();
    // get attribute
    Object value = servletContext.getAttribute("username");
    System.out.println(value);
    }
    }
  2. modify ServletContextListenerDemo: stay contextInitialized Add the following code to :

    // Add attribute 
    servletContext.setAttribute("username","zhangsan"); // Replace attributes
    servletContext.setAttribute("username","lisi"); // Remove properties
    servletContext.removeAttribute("username");
  3. start-up tomcat

  4. Annotation configuration listener , Change it to xml Manual configuration

    1. Note two demo Medium //@WebListener

    2. web.xml Add the following configuration

    <!-- Configure listeners -->
    <listener>
    <listener-class>com.itheima.listener.ServletContextListenerDemo</listener-class>
    </listener> <listener>
    <listener-class>com.itheima.listener.ServletContextAttributeListenerDemo</listener-class>
    </listener>

4 Comprehensive case - Student management system transformation ***

4.1 Requirement specification

4.1.1 Solve the mess

In our student management system , There will certainly be the problem of request and response in Chinese . And the garbled problem is learning Servlet How to solve the problem has been explained in the course of . Just in the actual development , When there are a lot of Servlet when , Definitely not in every Servlet Write the code to solve the garbled code . therefore , We can use the filter we learned today to solve the problem of request and response garbled .

4.1.2 Check login

In the student management system , It includes the input of student information and the query of student list , user ( staff ) Information input and query . Of course , Our actual function may be much more than that . But in terms of existing functions , Not everyone can access it directly through the address bar , It should have the authority to control , It's just that our course can't be further explained here , But at least login , Identity authentication is still necessary .

thus , Just one question , It's on every visit Servlet when , stay Servlet Add the judgment of whether the identity has been authenticated into the code of ? obviously , It's not reasonable . that , Since it's not in every Servlet Written in , It should be unified management and maintenance . here , Our filters will be available again .

4.1.3 Page java Block of code and jsp Expression transformation

We learned about filters today , And learned EL Expression and JSTL Tag library , They're there to avoid us JSP There is too much in the page java Code or jsp expression . We're going to use what we've learned today to transform the page .

4.2 Case realization

4.2.1 The filter solves the problem of global garbled code

  1. Code

    package com.itheima.filter;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse; /*
    Solve the problem of global garbled code
    */
    @WebFilter("/*")// /* Represents filtering all of the url
    public class EncodingFilter implements Filter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
    try{
    //1. Convert request and response objects to and HTTP Agreement related
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse; //2. Set the encoding format
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8"); //3. release
    filterChain.doFilter(request,response);
    } catch (Exception e) {
    e.printStackTrace();
    } }
    }

4.2.2 Filter solution check login

  1. Code

    package com.itheima.filter;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse; /*
    Check login
    */
    @WebFilter(value = {"/addStudent.jsp","/listStudentServlet"})// Filter some url adopt value To specify the
    public class LoginFilter implements Filter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
    try{
    //1. Convert request and response objects to and HTTP Agreement related
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse; //2. Get the data in the session domain object
    Object username = request.getSession().getAttribute("username"); //3. Judge user name
    if(username == null || "".equals(username)) {
    // Redirect to login page
    response.sendRedirect(request.getContextPath() + "/login.jsp");
    return;
    } //4. release
    filterChain.doFilter(request,response);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

4.2.3 EL Expression and JSTL Optimize JSP Interface

  1. addStudent.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title> Add student </title>
    </head>
    <body>
    <%-- Be careful :el If you want to get request object , Only through pageContext Page domain get
    pageContext.request, amount to java In the code block pageContext.getRequest()
    --%>
    <form action="${pageContext.request.contextPath}/addStudentServlet" method="get" autocomplete="off">
    The student's name :<input type="text" name="username"> <br>
    Student age :<input type="number" name="age"> <br>
    Student achievement :<input type="number" name="score"> <br>
    <button type="submit"> preservation </button>
    </form>
    </body>
    </html>
    • a key : stay jsp Pass through EL Expression to get the virtual path of the project :${pageContext.request.contextPath}

  2. index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
    <title> Student management system home page </title>
    </head>
    <body>
    <%--
    Get the data in the session domain
    If it is obtained, the hyperlinks for adding and viewing functions will be displayed
    If not, the hyperlink of login function will be displayed
    --%>
    <c:if test="${sessionScope.username eq null}">
    <a href="${pageContext.request.contextPath}/login.jsp"> Please log in </a>
    </c:if> <c:if test="${sessionScope.username ne null}">
    <a href="${pageContext.request.contextPath}/addStudent.jsp"> Add student </a>
    <a href="${pageContext.request.contextPath}/listStudentServlet"> Look at the students </a>
    </c:if> </body>
    </html>
    • Be careful :EL The expression will automatically find the shared data in the four domain objects , therefore ${sessionScope.username eq null} Medium sessionScope It can be omitted , It's written in ${username eq null}

  3. listStudent.jsp

    <%@ page import="com.itheima.bean.Student" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
       <title> Look at the students </title>
    </head>
    <body>
       <table width="600px" border="1px">
           <tr>
               <th> The student's name </th>
               <th> Student age </th>
               <th> Student achievement </th>
           </tr>
    <%-- s yes students Every object traversed ,EL This traversal can be used in expressions --%>      
           <c:forEach items="${students}" var="s">
               <tr align="center">
                   <td>${s.username}</td>
                   <td>${s.age}</td>
                   <td>${s.score}</td>
               </tr>
           </c:forEach>
       </table>
    </body>
    </html>
  4. login.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title> Students log in </title>
    </head>
    <body>
       <form action="${pageContext.request.contextPath}/loginStudentServlet" method="get" autocomplete="off">
          full name :<input type="text" name="username"> <br>
          password :<input type="password" name="password"> <br>
           <button type="submit"> Sign in </button>
       </form>
    </body>
    </html>

EL&Filter&Listener:EL Expression and JSTL,Servlet Filters in the specification ,Servlet The listener in the specification , Looking at design patterns , The use of listeners , Comprehensive case student management system more related articles

  1. [ turn ]EL Expression and JSTL Expression instance

    /* **Title:EL Expression and JSTL Expression instance **Author:Insun **Blog:http://yxmhero1989.blog.163.com/ */ For the convenience of writing JSP, We introduced E ...

  2. Struts label 、Ognl expression 、el expression 、jstl The relationship and function of tag library

    I used to use , But I can't tell the difference between them , So look for information , Integrate and differentiate them , Better understanding , One Introduce 1.Struts2 The role of   Struts2 Tag libraries provide themes . Template support , Greatly simplifies the view page ...

  3. JSP and El Expression and JSTL Tag library uses

    Core tag library : <%@ page language="java" import="java.util.*" pageEncoding="utf-8 ...

  4. EL Expression and JSTL Core tag library

    1 EL expression 1.1 EL Overview EL, Full name Expression Language. The main role : ①EL Expressions are mainly used to replace jsp Script expressions in the page , So that we can learn from all kinds of web Search in domain java object ( some ...

  5. EL expression 、 jstl label

    https://www.cnblogs.com/zhaotiancheng/p/6391894.html https://blog.csdn.net/zdwzzu2006/article/detail ...

  6. It's personal jsp、EL expression 、JSTL Notes from the tag library , Less concepts, more practical , If you need to leave your mailbox , The manuscript will be shared at the first time PDF For everyone !

    jsp Chapter one jsp Introduction and comparison servlet effect : Dynamic web page technology , Get data from database dynamically jsp and servlet Advantages and disadvantages : jsp advantage : Page performance is convenient , Good for writing html Code jsp shortcoming : Business logic processing ...

  7. Javaweb Learning notes 6—EL The expression and JSTL And custom tags

    Today, let's talk about javaweb The sixth stage of learning . EL The expression and JSTL And custom tags are introduced in the last article JSP An extension of , It can't be said that it's very important , But also understand . Old rules , First of all, use a mind map to show today's blog content . ps: ...

  8. EL Expression and JSTL( 3、 ... and )——EL expression

    stay JSP The development of , In order to obtain Servlet Data stored in , It usually takes a lot of Java Code , This kind of practice makes JSP The page is very confusing , So ,JSP2.0 Provides a kind of EL standard , It's a simple data access language . 1. First time to know EL E ...

  9. jsp(3,6,9) EL Expressions and JSTL

    1. jsp 1.1jsp What is it? Full name : Java Server Pages,java Server page . and Servlet equally , yes sun A dynamic web development technology defined by the company .    characteristic : be based on html Template , Can be in h ...

  10. sketch jsp And EL Expression and jstl And its use

    Jsp The order of include Instructions include Instructions : Represents the inclusion of the page . effect : You can put some jsp The pages are included together , External display . Layout of the page , It's no longer needed , Now we use css+div Make a layout .include ...

Random recommendation

  1. [Asp.net] Talk about password box and read-only box

    author :Wolfy Source :http://www.cnblogs.com/wolf-sun/ introduction Recently, I was in charge of a small project of a company , From the front desk to the next generation , It's all made by ourselves , Get a small information management system for a customer , Although it's about the interface or something ...

  2. curl The breakpoint continues

    Excerpt from http://blog.csdn.net/zmy12007/article/details/37157297 Excerpt from http://www.linuxidc.com/Linux/2014-10/107 ...

  3. js Simple writing

    I am writing JavaScript Code has been around for a long time , I can't remember when it started . about JavaScript What the language has achieved in recent years , I feel very excited : I'm lucky to be a beneficiary of these achievements . I've written a lot of articles , chapter , There's another one ...

  4. Ubuntu_16.04_Lamp

    Ubuntu_16.04 install Lamp development environment Catalog install Apache2 install php5 install mysql-server install php5-mysql(php Use mysql service , Include mysql,mysqli,m ...

  5. display:inline-block Next , Elements cannot be on the same horizontal line and between elements margin How to solve the problem of space

    In front page editing , It is often used when block elements are arranged horizontally , We'll use floats or dispaly:inline-block: Floating is easy to use , Obvious effects , But there will be potential BUG,( For the time being ): that display:inline-b ...

  6. koa middleware

    koa yes Express The next generation is based on node Of web frame   There are 1.x and 2.0 Two versions 1. Express Express It's the most popular of the first generation web frame   It's right node.js Of http It was packaged Exp ...

  7. Django And get request url Parameters of

    When get The address is 127.0.0.1:8000/mysite10 This type of URL There are two ways : 1, stay urls The routing of urlpatterns It defines routing in this way re_path('^mysite(\d+)$' ...

  8. How to build your own threat perception brain SIEM?| Hard open class

    How to build your own threat perception brain SIEM?| Hard open class The author of this article : Xie unitary 2017-03-10 10:09 project : Hard open class Introduction : Baidu security expert with ten years of experience in security products , Hand in hand teach you to build with open source projects SIEM Ann ...

  9. ORA-00001: unique constraint (...) violated It's not necessarily a data conflict

    Link to the original text :http://blog.163.com/jet_it_life/blog/static/205097083201301410303931/ Got a tester RAISE Of JIRA, On some form ...

  10. Use python take excel Data import database

    Use python take excel Data import database Because you need to process the data , take excel Data import into database , Record the process . Library used :xlrd and pymysql ( If you need to write excel have access to xlwt) direct ...