“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Overview of Servlets

1.1 What is a Servlet

  1. Servlets are one of the JavaEE specifications. A specification is an interface.
  2. Servlets are one of the three components of JavaWeb. The three components are Servlet, Filter, and Listener.
  3. A Servlet is a Small Java program running on a server that receives requests from clients and responds to data sent to them.

To put it simply: Servlets are small applications written in Java that run on a Web server, such as the Tomcat server.

1.2. Servlet demonstration

public class HelloServlet implements Servlet {
    /** * The service method is dedicated to handling requests and responses *@param servletRequest
    * @param servletResponse
    * @throws ServletException
    * @throws IOException
    */
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
	System.out.println("Hello Servlet has been accessed"); }}Copy the code

      
<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_4_0.xsd"
    version="4.0">
<! Configure servlet application for Tomcat with servlet tag -->
    <servlet>
        <! --servlet-name tag Servlet program alias (usually class name) -->
        <servlet-name>HelloServlet</servlet-name>
        <! --servlet-class is the name of the servlet class -->
        <servlet-class>com.servlet.HelloServlet</servlet-class>
    </servlet>
    <! -- Servlet-mapping tag to configure access address for servlet applications -->
    <servlet-mapping>
        <! The servlet-name tag is used to tell the server which servlet I am currently configuring to use -->
        <servlet-name>HelloServlet</servlet-name>
        <! The --url-pattern tag configures the access address <br/> / slash when parsed by the server, indicates the address: http://ip:port/ Project path <br/> /hello indicates the address: http://ip:port/ project path /hello <br/> -->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
Copy the code

1.3 common Errors

1.3.1 paths configured in URl-pattern do not start with a slash

1.3.2 The configured servlet-name value does not exist

Ii. Servlet life cycle

2.1 Servlet Life Cycle

Life cycle of Servlet object: Servlet creates object -> initialize operation -> run operation -> destroy operation

The Web server manages the lifecycle of servlets, and the entire process of Servlet objects is managed by the Web server.

2.2. Lifecycle methods in Servlet interfaces

Life cycle approach role Run number
A constructor Executed when the object is instantiated

There must be a public parameterless constructor
1 time
void init(ServletConfig config) Executed at initialization time 1 time
void service(ServletRequest req, ServletResponse res) Each request is executed N time
void destroy() When the server is normally down 1 time

2.3 Request flow of servlets

localhost:8080/one/hello
# 1. The browser sends the request, Tomcat receives the request and obtains the project path and resource path to access through the settlement request address.Project path: /one Resource path: /helloTomcat will scan all servlets under the one project inside the server, obtain the access address of each Servlet, and store it in a collection. The resource path is ket, and the fully qualified name of the class is Value.
   Map<String,String> map = new HashMap<>();
   map.put("/one","com.servlet.HelloServlet");
# 3. Use the resource path /one as the key to get the value from the map and get the fully qualified name of the class.
# 4. He will create a Servlet instance cache pool (key is the fully qualified name of the Servlet, value is the instance object of the Servlet), take the found key, and go to the ServletMap, if found, it is not the first time to access, if not found, it is the first time to access.
   Map<String,Servlet>servletmap = new HashMap<>(); If (servletMap.get (" fully qualified name ") == null){} else{// execute step 7 for the NTH time} # 5. The Servlet object is instantiated by reflection and placed in the instance cache pool. Tomcat creates the ServletConfig object, then calls init, passing in the created Servlet object # 7. Create the HttpRequest and HttpResponse objects and call the service method, passing in the HttpRequest and HttpResponse objects. # 8. Wait for the next visit.Copy the code

2.4 inheritance system of Servlets

Against 2.4.1, GenericServlet class

The Servlet and ServletConfig interfaces are implemented by default, and its subclass is HttpServlet if we write a Servlet that uses the Http protocol.

package cn.servlet;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet(urlPatterns = "/demo")
public class DemoServlet extends GenericServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("I'm a GenericServlet subclass"); }}Copy the code

2.4.2, the HttpServlet class

package cn.httpservlet;

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(urlPatterns = "/demo02")
public class DemoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("I'm a subclass of HttpServlet"); }}Copy the code

2.4.3, subtotal

  1. GenericServlet is a GenericServlet that can be used to handle requests and responses from various protocols.

  2. HttpServlet is specially used to process HTTP protocol sent requests, now all browsers send requests are using HTTP protocol, so we only need to inherit HttpServlet development in the future, you can follow the following steps to develop:

Create a class that inherits HttpServlet. 2. Override the service method whose parameters start with Http: This method processes the request and responds to the data. Note: Do not call the superclass service method in this method (405)Copy the code

2.5, ServletConfig class

The ServletConfig class is the configuration information class for servlets.

Both the Servlet program and the ServletConfig object are created by Tomcat and used by us. A Servlet application is created by default the first time it is accessed. A ServletConfig object is created when each Servlet application is created.

2.5.1 Three functions of ServletConfig

  1. Gets the value of servlet-name, the alias of the Servlet program.
  2. Gets the initialization parameter init-param.
  3. Get the ServletContext object.

2.5.2 Common methods

ServletConfig Indicates the common methods of the interface instructions
String getInitParameter(” parameter name “) Gets the parameter by the specified parameter name

2.5.3 Demonstration

The encoding format is used as the initial configuration parameter of the Servlet, which is read and output in the service method of the Servlet.

public class ServletConfigServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the configuration object
        ServletConfig config = this.getServletConfig();
        // Get the initialization parameter values
        String encoding = config.getInitParameter("encoding");
        if ("utf-8".equalsIgnoreCase(encoding)){
            // Simulate the response data to the browser
            System.out.println("Perform UTF-8 encoding operation");
        } else {
            // Simulate the response data to the browser
            System.out.println("Perform GBK coding operation"); }}}Copy the code
<servlet>
	<! - the servlet name -- -- >
    <servlet-name>ServletConfigServlet</servlet-name>
    <! -- Servlet fully qualified name -->
    <servlet-class>com.servlet</servlet-class>
	<init-param>
    	<! -- Parameter name -->
        <param-name>encoding</param-name>
        <! -- Parameter value -->
        <param-value>utf-8</param-value>
    </init-param>
</servlet>

<! --servlet access address -->
<servlet-mapping>
	<! -- Servlet name: must be the same as the servlet name above -->
    <servlet-name>ServletConfigServlet</servlet-name>
    <! -- Browser access address, must start with / -->
    <url-patten>ServletConfigServlet</url-patten>
</servlet-mapping>
Copy the code

2.6, the ServletContext class

2.6.1 Overview of ServletContext

ServletContext is an interface that represents a Servlet context object, ** a Web project has only one instance of a ServletContext object. **ServletContext object is a domain object. The ServletContext is created when the Web project deployment starts. Destroy it when the Web project stops.

2.6.2 Four functions of the ServletContext class

  1. Gets the context parameter context-param configured in web. XML.
  2. Gets the current project path in the format of/project path.
  3. Obtain the absolute path on the server hard disk after project deployment.
  4. Access data like Map

2.7 domain objects

Domain objects are objects that can access data like maps, called domain objects. The domain here refers to the scope of data access operations, the entire Web project.

His role is to share data.

Save the data Take the data Delete the data
map put() get() remove()
The domain object setAttribute() getAttribute() removeAttribute()

2.8、 loadOnStartup

Let the Web container create and initialize the Servlet when it starts. The value ranges from 1 to 10. The smaller the value, the higher the load. The default value is -1: creates and initializes on the first access

It can be configured in XML:

<load-on-startup>1</load-on-startup>
Copy the code

He can also use the annotation configuration method:

@WebServlet(urlPatterns = "/response", loadOnStartup =1)
Copy the code

Request object

Overview of the HttpServletRequest object

HttpServletRequest is an interface whose implementation class object is called the request object, which encapsulates all the request information (request line, request header, request body (request parameters)).

The HttpServletRequest interface contains a number of methods. Tomcat implements this object and calls service() to pass in the request object when the servlet starts. We can use it directly in the service method.

HttpServletRequest object

Request is related to the request line Functional description
String getMethod() GET request mode GET or POST
String getRequestURI() Uniform Resource Identifier Uniform Resource Identifier, which represents a Resource name
StringBuffer getRequestURL() Uniform Resource Locator, which represents an accessible address
String getProtocol() Get the protocol and version
String getContextPath() Get the context path (project name path)
Request is related to the request header Functional description
String getHeader(String headName) Gets the value of the specified request header

Parameter: The name of the key

Return: the value of the corresponding request header
Request is related to the request parameter Functional description
String getParameter(String name) Get a parameter value from the parameter name
String[] getParameterValues(String name) Gets a set of values with the same name as the parameter name

Check box, and select multiple from the drop-down list
Enumeration getParameterNames() Get all parameter names
Map getParameterMap() Get all of the form’s parameter keys and values and wrap them into a Map object
Enumeration method of the interface instructions
boolean hasMoreElements() Return true if there are other elements
E nextElement() Returns the next element
package com.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("/line")
public class RequestLineServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the request line information
        System.out.println("Get method:" + request.getMethod());
        System.out.println(Uniform Resource Identifier: + request.getRequestURI());
        System.out.println(Uniform Resource Locator: + request.getRequestURL());
        System.out.println("Agreement and Version:" + request.getProtocol());
        System.out.println("Current project address:" + request.getContextPath());

        // Get a request header
        System.out.println("Get the request header value for host:" + request.getHeader("host")); }}Copy the code

3.3. Garbled Request Parameters (POST)

3.3.1 Cause of Garbled characters in request Parameters

When the browser sends data to the server, utF-8 encoding is used, but the server decoding by default uses ISO-8859-1 decoding: European code, does not support Chinese characters.

If it is a GET request and the Tomcat version is later than 8.0.5, garbled characters do not need to be considered. Otherwise, garbled characters need to be considered in GET requests.

3.3.2 Solution to Garbled Characters in POST Mode

  1. Solution: request. SetCharacterEncoding (” utf-8 “) set the request parameter encoding to utf-8.
  2. Code position: Always set the code for the request before getting the request parameters.
  3. Page code: This code must be the same as the page code. If the page uses GBK, then use GBK here as well.

Iv. Response object

4.1 overview of HttpServletResponse Objects

HttpServletResponse is an interface whose implementation class objects are called response objects, which are used to give response data (response line, response header, response body) to the browser. The HttpServletResponse interface contains a number of methods. Tomcat implements this object and calls service() to pass in the request and response objects when the servlet is started. We can use it directly in the service method.

4.2 Methods related to response data

Response body related methods Functional description
OutputStream getOutputStream() If the server returns binary data

Use this method, such as pictures
PrintWriter getWriter() Use this method if the server is returning text data for characters
@WebServlet(urlPatterns = "/response")
public class ResponseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the character print stream object
        PrintWriter out = response.getWriter();
        // Display the response data to the browser
        out.print("<h1 style='color:red'>hello browser<h1>"); }}Copy the code

4.3 The response content is garbled in Chinese

4.3.1 Garbled Characters

Because the default response body in Tomcat is the European code table, ISO-8859-1 does not support Chinese.

4.3.2 solutions

4.3.2 Method 1

Before getting the print stream object, set the encoding of the print stream to UTF-8 by doing the following

The response method instructions
The response. SetCharacterEncoding (” character set “) Used to set the character set of the response body

Sets the stopwatch used by the print stream
@WebServlet(urlPatterns = "/response")
public class ResponseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set the print stream encoding
        response.setCharacterEncoding("utf-8");
        // Get the character print stream object
        PrintWriter out = response.getWriter();
        // Display the response data to the browser
        out.print(

); }}Copy the code

4.3.3 Method 2

Tell the browser to return the data type and encoding with the following method

Methods that respond to objects Functional description
void setContentType(String type) 1. Tell the browser to return the content type

2. Set the print stream encoding

Note: Must be set before getting the stream, otherwise invalid
@WebServlet(urlPatterns = "/response")
public class ResponseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set the print stream encoding
        // response.setCharacterEncoding("utf-8");

        // Tells the browser to return the content type and set the print stream encoding
        response.setContentType("text/html; charset=utf-8");
        // Get the character print stream object
        PrintWriter out = response.getWriter();
        // Display the response data to the browser
        out.print(

); }}Copy the code

Five, the JSP

5.1 The role of JSP

JSP — Java Server Page runs on the Server side of the Java Page, previously learned HTML runs on the browser side. JSP is run on the server and is eventually parsed into static HTML and run in the browser. The HTML page we see on the browser is actually the result of the JSP running on the server.

The main function of JSP is to replace the Servlet program back HTML page data. This is because it is very complicated for Servlet programs to send back HTML page data. Development and maintenance costs are extremely high.

5.2 advantages of JSP

technology The characteristics of
HTML Static page advantages: convenient page beautification operation, write JS script and CSS code are more convenient.

Disadvantages: Cannot write dynamic content.
Servlet Small Java program that runs on the server

Pros: Make dynamic content

Disadvantages: Inconvenient to write HTML as well as CSS and JS code
JSP JSP = HTML + Servlet

Features: both the advantages of HTML: easy to beautify and write JS code.

There are also Servlet benefits: You can write Java code on the page, and you can create dynamic content (not recommended).

5.3 principle of JSP

A JSP page is essentially a Servlet program. ** When we first visit the JSP page. The Tomcat server translates the JSP page into a Java source file for us. And compile it into a.class bytecode program. If we open the Java source file, it is not difficult to find the following contents:

We traced the source code to the HttpJspBase class. It directly inherits from the HttpServlet class. That is to say. A Java class translated by JSP, which indirectly inherits from the HttpServlet class. In other words, the translation is a Servlet program.

Translated Servlet program source code, not difficult to find. Its underlying implementation is also through an output stream. Send back HTML page data

To the client.

    out.write("\r\n");
    out.write("\r\n");
    out.write("<html>\r\n");
    out.write("<head>\r\n");
    out.write(" Title\r\n");
    out.write("</head>\r\n");
    out.write("<body>\r\n");
    out.write("A. sp page \r\n");
    out.write("</body>\r\n");
    out.write("</html>\r\n");
Copy the code

5.4. JSP running process

The JspServlet first translates the JSP file code into the Java code of the Servlet, which is then compiled into a bytecode file for execution, with a Servlet at the bottom.

  1. The browser requests a JSP page, and Tomcat’s JspServlet first translates the JSP file into a Servlet file: xxx_jsp.java.
  2. Compile the xxx_jsp. Java file to produce a bytecode file: xxx_jsp.class.
  3. Load the bytecode file xxX_jsp. Class and create the XXX_JSP object.
  4. The service method of xxX_JSP is called to process the request and respond to the data.

The first time a browser accesses a JSP, Tomcat translates the JSP into a Servlet and compiles it into a bytecode file, which is generated only once. If the JSP content is modified during this time, it will be re-translated.

Forwarding and redirection

6.1 Functions of forwarding and redirection

Used for jumping web components, from component A to another component B.

6.2, forwarding,

6.2.1 Jump position

Request forwarding refers to the operation that the server hops from one resource to another resource after receiving a request. A jump to a component (resource) on the server side.

6.2.2 Forwarding methods

request.getRequestDispatcher("/ Address to jump to").forward(request, response);
Copy the code

6.3 redirection

6.3.1 Jump location

A jump to a page (component/resource) in a browser.

6.3.2 Redirection methods

response.sendRedirect("Address to jump to")
Copy the code

6.4 Differences between Forwarding and Redirection

The difference between Forward forward Redirect redirect
directory You can access resources in the WEB-INF directory The resources in the WEB-INF directory cannot be accessed
The address bar The address bar will not change, the last address Changes and displays the new address
Jump position The jump is performed on the server Jump in the browser
Request object (domain) Request domain data is not lost because it is the same request Request domain data is lost because it is not the same request

6.5, pay attention to

  1. Whether it is a redirection or a forward, the subsequent code will be executed, but generally there is no code behind a forward or a redirection, and there is no point in execution, because either the forward or redirection browser will ultimately display the data of the page after the jump.
  2. If you want to preserve data in the request domain, you must use forwarding.
  3. If you want to jump to a resource in the WEB-INF directory, you must use a forward.
  4. If you want to cross domains, you must use redirection.

Vii. Three major scopes

7.1 what is scope

An area of server memory for data sharing between servlets. The scope structure is a Map<String, Object>.

7.2. Scope type

scope type scope
Request the domain HttpServletRequest It only works on the same request
Session domain HttpSession In the same conversation

The browser accesses the server for the first time until the browser is closed

The entire process is called a session
Contextual domain ServletContext In the same application

The entire process from server startup to server shutdown is in effect

7.3. Scope methods

Scope-dependent methods role
The Object getAttribute (” key “) You get a value out of that
Void setAttribute(” key “,Object data) Stores key-value pairs of data into the scope
Void removeAttribute (” key “) Deletes the key-value pair data in scope

7.4. How to select a scope

Consider a small scope first, and use a small scope if a small scope satisfies your requirements.

8. EL expression

8.1 what is an EL expression

The full name of an EL Expression is: Expression Language. Is an expression language.

EL expressions are mainly used to output data in JSP pages instead of expression scripts in JSP pages. Because EL expressions are much cleaner than JSP expression scripts when it comes to output data.

8.2 EL expression operation

8.2.1 Arithmetic operation

Arithmetic operator instructions For example, The results of
+ add The ${12 + 18} 30
subtraction 18 – ${8} 10
* The multiplication 12 * 12 ${} 144
/(div) division
6 / 3 or Orange-red or attach
{6 div 3}
2
%(mod) modulus {3} 10% or{10 mod 3} 1

8.2.2 Logical operations

Logical operator instructions For example, The results of
&& or the and With the operation {12 == 12 && 12 < 11} or{ 12 == 12 and 12 < 11 } false
| or or Or operation
12 = = 12 12 < 11 or {12 = = 12 \ | the \ | 12 < 11} or
{12= =12 or 12<11}
true
! Or not Take the operation
! t r u e after {! After the true}
{not true}
false

8.2.3 Relational operation

Relationship between operation instructions For example, The results of
= = or eq Is equal to the
5 = = 5 or 5 = = {5} or
{5 eq 5}
true
! = or ne Is not equal to
5 ! = 5 or {5! = 5} or
{5 ne 5}
false
< or lt Less than
3 < 5 or {< 3 or 5}
{3 lt 5}
true
> or gt Is greater than
2 > 10 or {2} > 10 or
{2 gt 10}
false
< = or le Less than or equal to
5 < = 12 or {5 <= 12} or
{ 5 le 12 }
true
> = or ge Greater than or equal to
3 > = 5 or {3 >= 5} or
{ 3 ge 5 }
false

8.2.4 Ternary operation

Expression 1? Expression 2: Expression 3

Returns the value of expression 2 if the value of expression 1 is true, and 3 if the value of expression 1 is false.

8.2.5 Air freight

Null: Determines whether the content is empty, not whether the object is empty.

8.3, EL values from four scopes

The method by which the EL obtains data is from one of the four scope objects, from the smallest to the largest. If you need to specify the scope, you can specify it using the following built-in objects of the EL.

8.3.1 the PageContext object

JSP is essentially a Servlet, but it has one more scope than a Servlet: the page domain. There are four scopes in JSP. The page domain only works in a SINGLE JSP page, and data cannot be shared between different JSPS, which is smaller than the request domain scope.

PageContext Operation related method instructions
void setAttribute(String key, Object value) Add keys and values to the page fields
Object getAttribute(String key) Get the value from the page field
void removeAttribute(String key) Delete keys with the same name in all four fields
Object findAttribute(String key) Automatically lookup a key from four scopes,

Look from small to large, and stop if found.

If not found, return null
The < %// Add a string to the page field
	pageContext.setAttribute("name"."I am the page field."); % >Copy the code

8.3.2. EL Specifies the domain to obtain data

scope EL spelled
Page domain The ${pageScope. Key name}
Request the domain The ${requestScope. Key name}
Session domain The ${sessionScope. Key name}
Contextual domain The ${applicationScope. Key name}
<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > EL specified domain to get the data < / title > < / head > < body > < %// Add a string to the page field
        pageContext.setAttribute("name"."Page field");
        / / request domain
        request.setAttribute("name"."Request domain");
        / / session domain
        session.setAttribute("name"."Session domain");
        // Context domain
        application.setAttribute("name"."Context domain"); ${requestscope. name} <hr> ${requestscope. name} <hr> ${sessionScope. Name} <hr> ${sessionScope. Name} <hr> ${sessionScope. Name} <hr> ${sessionScope. ${applicationScope. Name} <hr> </body> </ HTML >Copy the code

JSTL tag library

The JSTL Standard Tag Library is the JSP Standard Tag Library. Is a continuous improvement of the open source JSP tag library. EL expressions are primarily used to replace expression scripts in JSPS, while tag libraries are used to replace code scripts. This makes the entire JSP page much more concise. The JSTL consists of five different functional tag libraries.

scope URL The prefix
Core label library Java.sun.com/jsp/jstl/co… c
formatting Java.sun.com/jsp/jstl/fm… fmt
function Java.sun.com/jsp/jstl/fu… fn

9.1 Usage Steps

9.1.1 importing the JAR package

taglibs-standard-impl-1.21..jar
taglibs-standard-spec-1.21..jar
Copy the code

9.1.2. Import the tag library

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"% >Copy the code

9.1.3 Use labels

Common tags in the core Tag library

9.2.1, < c: if / >

Used for single-condition judgments on a page.

The property name Whether EL is supported Attribute types Property description
test Support, must be EL Boolean value If the condition is true in EL, the tag body content is executed

Note: There is no corresponding else tag
<%--
ii.<c:if />
ifTags are used to makeifJudgment. The test attribute indicates the condition (output using the EL expression) --%> <c:if test="${ a == b }"> <h1> If a = b</h1> </c:if>
<c:if test="${ a ! = b }"> <h1> If a is not equal to b</h1> </c:if>
Copy the code

9.2.2, < c: choose >

For multi-branch (multi-condition) decisions, similar to switch… case …. Default.

Tag name role
choose Like Swtich in Java, Choose is simply a container containing the following two elements
when More than one can appear for each judgment, similar to case in switch. There is a test attribute, which has the same function as if
otherwise If all of the above conditions are not met, execute the Otherwise content. Similar to default in switch

9.2.3, < c: forEach >

Used to iterate over collections or arrays (most commonly).

The property name Whether EL is supported Attribute types Property description
items true An array or collection. Use an EL expression to represent a collection or array
var false String The variable name of var represents each element in the collection
varStatus false String The state object representing each element,

There are four attributes, the meanings of which are shown in the table below

VarStatus property sheet:

attribute The data type meaning
index int Index number of the element currently traversed, starting from 0
count int How many elements have we traversed so far, starting at 1
first boolean Return true if the first element is currently traversed
last boolean Return true if the last element is currently traversed
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> < HTML > <head> <title> < span style> tr {text-align: center; } </style> </head> <body> <table align="center" border="1" cellspacing="0" cellpadding="0" width="80%"> < caption > student information list < caption > < tr > < th > serial number < / th > < th > student id < / th > < th > name < / th > < th > gender < / th > < th > achievement < / th > < / tr > < % - forEach tag: The items property for JSP pages to iterate over collections and arrays: Sets the collection or array to iterate over: typically gets from scopevarProperty: Sets a variable name to receive each element traversed. VarStatus property: sets a variable name to record the state of the currently traversed element (state object). Index property: The index value of the currently traversed element in the collection0Start count attribute: how many elements have been traversed up to the current element, starting from1--%> <c:forEach items="${stus}" var="stu" varStatus="status"> <! --> <tr style="background-color:${status.count % 2 == 0 ? 'gray; ':'}">
            <td>${status.count}</td>
            <td>${stu.id}</td>
            <td>${stu.name}</td>
            <td>${stu.gender? "Male":"Female"}</td>
            <td>${stu.score}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>
Copy the code

9.3. Format common tags in the Tag Library

9.3.1, < FMT: formatDate >

Use to format the date.

The property name Attribute types Property description
test Date The date object to format
pattern String Specify date format