Java Web (day10) -- EL expression, JSTL and Servlet advanced

Posted by guarriman on Thu, 06 Jan 2022 11:41:21 +0100

EL expression and JSTL (2) -- JSTL

1, JSTL introduction:

The full name of JSTL is JavaServer Pages Standard Tag Library, and the Chinese name is JSP standard tag function library. At present, the latest version is 1.2. JSTL is a standard specification specified by JCP (Java Community Process). It mainly provides Java Web developers with a standard general label function library.

The tag function library provided by JSTL is mainly divided into five categories:
(1) Core tag library
(2) I18N capable formatting tag library
(3) SQL tag library
(4) XML tag library
(5) Functions tag library

The core tag library mainly includes the following types:

1. Expression label:
(1) < C: out >: mainly used to display the content of data, like <% = scripting language% >
(2) < C: set >: mainly used to store variables in JSP scope or JavaBean attributes
(3) < C: remove >: mainly used to remove variables
(4) < C: catch >: it is mainly used to handle abnormal conditions that generate errors and store error information (less used)

2. Process control:
(1) < C: if >: the purpose is the same as the if we usually use in the program
(2) : itself is only used as the parent tag of < C: when > and < C: otherwise >
(3) /: when using < C: when > and < C: otherwise > for process control, both must be sub tags of < C: choose > (similar to switch ···········)

3. Iteration operation:
: loop traversal, which can browse the members in the collection in order. The operation mode is that when the conditions are met, the ontology content of < C: foreach > will be executed repeatedly.
: used to browse all members in a string, whose members are separated by delimiters.

2, Core tag library:

It includes common work of Web applications, such as loop, expression assignment, basic input and output, etc.

1. Expression label:
(1) < C: out >: mainly used to display the content of data, like <% = scripting language% >
(2) < C: set >: mainly used to store variables in JSP scope or JavaBean attributes
(3) < C: remove >: mainly used to remove variables
(4) < C: catch >: it is mainly used to handle abnormal conditions that generate errors and store error information (less used)
(5) < C: out > label
Create a new Java Web project chapter07, index The JSP code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
    request.setAttribute("name", "smyhvae");
%>
</head>
<body>
    <c:out value="${requestScope.name} "></c:out>

</body>
</html>

(6) < C: set > label

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
    request.setAttribute("name", "smyhvae");
%>
</head>
<body>
    <%--Output label --%>
    <c:out value="${requestScope.name} "></c:out>

    <%--Define variable labels --%>
    <c:set var="age" value="22"></c:set>
    ${age }

</body>
</html>

2. Process control:

(1) < C: if >: the purpose is the same as the if we usually use in the program
(2) : itself is only used as the parent tag of < C: when > and < C: otherwise >
(3) /: when using < C: when > and < C: otherwise > for process control, both must be sub tags of < C: choose > (similar to switch ···········)

3. Iteration operation:

(1) : loop traversal, which can browse the members in the collection in order. The operation mode is that when the conditions are met, the ontology content of < C: foreach > will be executed repeatedly.
(2) : used to browse all members in a string, whose members are separated by delimiters.
Code example:
(3)
Create a new user class as the traversal object. User. The Java code is as follows:

package com.vae.bean;

public class User {
    private String name;
    private String sex;
    private int age;
    public User() {
        super();
    }
    public User(String name, String sex, int age) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", sex=" + sex + ", age=" + age + "]";
    }


}

Create a new file index3 JSP, the code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.vae.bean.User,java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<%
    List<User> users = new ArrayList<User>();
    User u1 = new User("Life one", "male", 22);
    User u2 = new User("Life two", "male", 23);
    User u3 = new User("vae", "female", 24);
    users.add(u1);
    users.add(u2);
    users.add(u3);
    request.setAttribute("users", users);
%>
</head>

<body>
    <table border="1">
        <tr>
            <th>name</th>
            <th>sex</th>
            <th>age</th>
        </tr>

        <c:forEach items="${requestScope.users }" var="user">
            <tr>
                <td>${user.name}</td>
                <td>${user.sex}</td>
                <td>${user.age}</td>
            </tr>
        </c:forEach>
</body>
</html>

Operation results:

(4) Properties in:
·begin: indicates the beginning of the index. Generally, it is not written;
·End: indicates the end position. If you need to traverse ten lines, write 10 here.
·step: increment.

The above three attributes are used less.
·varStatus: current status. Its status is as follows:

        index  Index starts at 0

        count  Current traversal times from 1
        
        current Object currently being iterated

        first  Is it the first

        last   Is it the last one        

Servlet advanced (1) -- Filter

1, What is a Filter

1.Filter concept

Filter is not a servlet. It cannot generate a response, but it can preprocess a request before it reaches the servlet, or it can process the response when it leaves the servlet. In other words, the filter is actually a transmitter between the client and the servlet, and it can modify what is to be transmitted. The filtering function is to filter the requests sent from the client to the server, and also process the responses returned by the server. It allows users to change a request and modify a response.
 

Note: the filter is used to intercept requests and responses and cannot generate responses, while the servlet is used to process requests and generate responses.

2. Simple Filter example

package cn.itacst.chapter08.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class MyFilter
 */
@WebFilter("/MyFilter")
public class MyFilter implements Filter {

    /**
     * Default constructor. 
     */
    public MyFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
         response.setContentType("test/html;charset=utf-8");
         response.getWriter().print("get into filter");
		// pass the request along the filter chain
		String name=request.getParameter("name");
		System.out.println(name);
		if("dashuju".equals(name)) {
			chain.doFilter(request, response);
		}
		response.getWriter().print("sign out filter");
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

2, A Two mapping methods of Filter

1. Use wildcard * to intercept all user requests
The element of Filter is used to configure the resource information intercepted by the Filter. If you want the Filter to intercept all requests, you can use the wildcard * to implement it. The specific implementation method is as follows:

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.mengma.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2. Intercept access requests in different ways
On the web In the XML file, each element can be configured with a resource intercepted by a Filter. There is a special child element in the element, which is used to specify how the resources intercepted by the Filter are called by the Servlet container. There are four values of element, as shown in the table.

(1) Create ForwardServlet

package com.mengma.filter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForwardServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/first.jsp").forward(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

(2) Create first jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    first.jsp
</body>
</html>

(3) Create and edit a filter ForwardFilter

package com.mengma.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class ForwardFilter implements Filter {
    public void init(FilterConfig fConfig) throws ServletException {
        // The filter object is called during initialization, and some initialization parameters can be configured
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // It is used to intercept the user's request. If it matches the interception path of the current filter, this method will be called
        PrintWriter out = response.getWriter();
        out.write("Hello FilterTest");
    }
    public void destroy() {
        // The filter object is automatically called when it is destroyed to release resources
    }
}

At this point, you need to use the web Add the mapping information of ForwardFilter to the XML file. A child element is added to the code, and the value of this element is FORWARD, as shown below:

<filter>
    <filter-name>ForwardFilter</filter-name>
    <filter-class>com.mengma.filter.ForwardFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>ForwardFilter</filter-name>
    <url-pattern>/first.jsp</url-pattern>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

3, Filter chain

web.xml is configured with a filter filter. When the container is started, the init() method is executed for initialization, and then the destroy () method is executed when the container is closed to destroy the filter. Each time the server receives a request, the filter will be passed first. If there is an appropriate filter, the doFilter method of the corresponding filter will be executed.

Similar filters with the same matching pattern will exist in the same filter chain, and then they will be arranged in sequence according to the initialization order to realize layer by layer filtering. There is a doFilter method in filterChain. Its function is to forward the current request to the next filter in the filter chain for filtering, and then filter the results. It can only continue to be executed after waiting for the next filter to complete filtering. The execution process is similar to the following figure:

As shown in the figure above, filtering is performed layer by layer through the filter chain, just like nesting layer by layer. If there is only one filter (or the last one) in the filter chain, the chain is executed Dofilter () will directly forward the request and obtain the request resource resource. Since the same request and response are transmitted from beginning to end, each filter can modify the request or return the result, realizing the purpose of filtering and modification.

Code example:

ResponseFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        CustomResponseWrapper customResponseWrapper = new CustomResponseWrapper((HttpServletResponse) servletResponse);
        System.out.println("ResponseFilter Before execution");
        filterChain.doFilter(servletRequest,customResponseWrapper);//Perform the next level of filtering
        System.out.println("ResponseFilter After execution");
        }
    }

SecondFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
2         System.out.println("Second doFilter Before execution");
3         filterChain.doFilter(servletRequest,servletResponse);//This is the last layer of filter, which will directly request resource
4         System.out.println("Second doFilter After execution");
5     }

web.xml (the two filters use the same matching pattern '/ *', so they will be in the same filter chain)

<filter>
        <filter-name>ResponseFilter</filter-name>
        <filter-class>filter.ResponseFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ResponseFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>SecondFilter</filter-name>
        <filter-class>filter.SecondFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SecondFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Topics: Java Front-end