CGLIB proxy, jsp, EL expression, JSTL standard tag library

1. CGLIB agent

There is a class that does not implement the interface. If you want to enhance this class, you need to use the CGLIB proxy
  • Import CGLIB package
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.3.0</version>
</dependency>
  • Write the proxied class
package com.wz.practice.proxy.cglib;

public class UserService {
    public void add(){
        System.out.println("--------add execution--------");
    }

    public void update(){
        System.out.println("--------update execution--------");
    }
}
  • implement proxy
package com.wz.practice.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Implemented the MethodInterceptor interface: This interface is the mechanism provided by CGLIB for connecting method calls
 * By implementing the intercept method, additional operations can be performed before and after method calls.
 */

public class UserServiceFactory implements MethodInterceptor {

    private UserService userService;
    public UserServiceFactory(UserService userService){
        this.userService=userService;
    }
    public UserService getUserServiceProxy(){
        //Create Enhancer object,
        Enhancer enhancer = new Enhancer();
        //Specify a parent for the generated class
        enhancer.setSuperclass(UserService.class);
        //Set UserServiceFactory as method interceptor callback
        enhancer.setCallback(this);
        //Create a proxy object, convert it to UserService and return
        return (UserService) enhancer.create();
    }

    /**
     *Intercept here
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("Open transaction");
        //method.invoke() method is a method provided by Java reflection API.
        // Used to call the specified method on the specified object.
        // It accepts two parameters: the first parameter is the object instance on which the method is to be called, and the second parameter is the parameter to be passed to the method.
        Object invoke = method.invoke(this.userService, objects);
        System.out.println("Commit transaction");
        return invoke;
    }
}
  • test
package com.wz.practice.proxy.cglib;

public class Test001 {
    public static void main(String[] args) {
        UserService userServiceFactory = new UserServiceFactory(new UserService()).getUserServiceProxy();
        userServiceFactory.add();
    }
}

result:

CGLIB proxy, jsp, EL expression, JSTL standard tag library_EL expression

2. What is jsp

The father of jsp is HttpJspbase HttpJspBase inherits HttpServlet

In other words, jsp is essentially a Servlet

The external appearance of jsp is a page, but all functions of Servlet can be completed on this page.

jsp cannot be run directly. It needs to go through a process of translation before running. After being translated into Java code, it is compiled into a .class file and finally the class file will be run

3. Domain object

Objects with scope are called domain objects. Simply put, they are Java objects with scope.
There are four domain objects in jsp

request: The scope is the current request. When the current request ends, this domain object will no longer exist. Each request will create a domain object like yours.

session: The life cycle is the current session (a simple understanding is the opening and closing of a browser). In fact, the life cycle of a session is 30 minutes. Even if the page is closed, this object will survive in the jvm for a certain period of time before dying.

application(ServletContext): This object exists as long as Tomcat opens it. This object does not exist when Tomcat closes it. It has the longest life cycle.

pageContext: The life cycle is the current page. When the page is closed, this object will no longer exist.

Sort by life cycle order:

pageContext < request < session < application(ServletContext)

The most commonly used one in development is request session, which is also used. Application and pageContext are basically not used.

What exactly does it do with domain objects?

The execution results of the Servlet can be directly brought to the jsp page and displayed

4. EL expression

EL expressions can directly retrieve data from four domain objects
4.1. Basic use of El expression
4.1.1. Put data into domain objects in Servlet
package com.wz.practice.servlet;

import com.wz.practice.pojo.User;

import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet(urlPatterns = "/users")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Here you can put data into the domain object
        req.setAttribute("username","ZhangSan");
        req.setAttribute("user",new User(01,"ZhangSan","123456"));
        ArrayList<User> userList = new ArrayList<User>();
        for (int i = 0; i < 3; i + + ) {
            userList.add(new User(i + 1,"Username" + i,"123456"));
        }
        req.setAttribute("list",userList);

        //Put data in the session object
        HttpSession session = req.getSession();
        session.setAttribute("sessionKey","sessionVal");
        //Put the object in the application
        ServletContext application = req.getServletContext();
        application.setAttribute("applicationKey","applicationVal");

        req.getRequestDispatcher("/index.jsp").forward(req,resp);

    }
}
4.1.2. Use EL expressions to get data on the page
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <%
        pageContext.setAttribute("pageKey","pageVal");
        %>

        <%--Get data from req--%>
        The username is: ${username}<br>
        Object name: ${user.username}<br>
        The name of the first object in the collection: ${list[0].username}<br>

        <%--Get data from session--%>
        Get data from session: ${sessionKey}<br>
        Get data from application: ${applicationKey}<br>
        Get data from pageContext: ${pageKey}
    </body>
</html>

result:

4.2. The order in which EL retrieves data
pageContext < req < session < application

The above order is the order in which our EL expression takes out data.

If the pageContext is not fetched, then the data will be fetched from req. If the data is not fetched from req, then the data will be fetched from the session. The data will not be fetched from the session.

Then we have to go to the application to retrieve the data.

EL expressions can only retrieve data but cannot express logical relationships and traverse collections

5. Basic use of JSTL standard tag library

JavaServer Pages Standard Tag Library

Problems with EL:

  • EL is mainly used to obtain data in the scope. Although it can make judgments, all it gets is a result for display.
  • EL does not have flow control statements, such as judgments
  • EL can only perform single-point access to collections and cannot implement traversal operations, such as loops.

JSTL is a collection of jsp tags

The role of JSTL:

You can perform logical operations on the data obtained by EL

Can cooperate with EL to complete data display

  • Guide package
<!--jstl tag library-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
  • data preparation
package com.wz.practice.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
    private Integer id;
    private String username;
    private Double salary;
}


package com.wz.practice.servlet;

import com.wz.practice.pojo.Dept;

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;
import java.util.ArrayList;

@WebServlet(urlPatterns = "/depts")
public class DeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("age",18);

        req.setAttribute("score",10);

        ArrayList<Dept> depts = new ArrayList<Dept>();
        for (int i = 0; i < 10; i + + ) {
            depts.add(new Dept(i + 1,"clerk" + i + 1,8000.));
        }
        req.setAttribute("deptList",depts);

        req.getRequestDispatcher("/dept_list.jsp").forward(req,resp);
    }
}
  • fetch data
<%--
    Created by IntelliJ IDEA.
    User: WangZhi
        Date: 2023/8/19
            Time: 11:37
                To change this template use File | Settings | File Templates.
                --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--prefix tag library prefix--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <%--Logical operation operator in jstl--%>
        <c:if test="${age>=18}">
            Movies available
        </c:if>
        <%--if-----else if---else--%>
        <c:choose>
            <c:when test="${score<=60}">Failed</c:when>
            <c:when test="${score<75}">Good</c:when>
            <c:otherwise>Excellent</c:otherwise>
        </c:choose>


        <table cellpadding="0" cellspacing="0" border="1" style="width: 600px;text-align: center">

            <tr>
                <th>id</th>
                <th>name</th>
                <th>Salary</th>
                <th>Traverse subscripts</th>
            </tr>
    <%--
    items: What is the collection traversed?
    var: What is the object that is traversed each time?
    varStatus: the status of each traversal
    begin="start subscript" is not written
    end="End subscript" Do not write
    step="interval length" is not written
    --%>
            <c:forEach items="${deptList}" var="dept" varStatus="status">
                <tr>
                    <td>${dept.id}</td>
                    <td>${dept.username}</td>
                    <td>${dept.salary}</td>
                    <td>${status.index}</td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>

result:

CGLIB proxy, jsp, EL expression, JSTL standard tag library_Basic use of JSTL standard library _02