✍
1,JSP
-
What is JSP?
- Java Server Pages: Java server-side pages, like servlets, are used for dynamic Web technology! The essence of JSP is actually a Servlet.
- It can be understood as: a special page, in which both html tags and java code can be specified and defined
-
The difference between JSP and HTML
- HTML only provides users with static data
- JAVA code can be embedded in JSP pages to provide users with dynamic data
-
The difference between JSP and Servlet
- Servlets are difficult to format data
- JSP is easy to typeset data
category | Applicable scenario |
---|---|
HTML | Only static resources can be developed, java code cannot be included, and dynamic data cannot be added. |
Servlet | Writing java code can output page content, but it is very inconvenient and the development efficiency is very low. |
JSP | It includes HTML presentation technology and the ability of Servlet to output dynamic resources. However, it is not suitable for use as a controller. |
1.1 JSP principle
-
JSP is essentially a Servlet
-
When we visit Jsp for the first time, the Jsp engine will translate the Jsp into a Servlet, and the file is stored in the work directory in tomcat (source directory).
-
In JSP pages, as long as it is JAVA code, it will be output intact. If it is HTML code, it will be converted to
out.write("<html>\r\n");
In this format, output to the front end!
1.1. 1. JSP execution process analysis diagram
Principle of JSP:
Client submit request
-- Tomcat server resolves the request address
-- find the JSP page
-- Tomcat translates JSP pages into java files of servlets
-- translate it well java file compiled into class file
-- return to the client browser.
1.2 script of JSP
- The script of JSP is the way that JSP defines Java code
- As an application of Java technology, JSP has some expanded syntax, but all Java syntax supports it!
1.2. 1. java script segment
- The first is the java script segment, which can define local variables and write statements
- Format: <%% >
<%-- jsp Script fragment --%> <% int sum = 0; for (int i = 1; i <=100 ; i++) { sum+=i; } out.println("<h1>Sum="+sum+"</h1>"); %>
1.2. 2. jsp declaration
- The second is jsp declaration, which can define global variables, methods and classes
- Format: <%!% >
<%! static { System.out.println("Loading Servlet!"); } private int Var = 0; public void kuang(){ System.out.println("Entered the method Kuang!"); } %>
1.2. 3. jsp expression
- The third kind: jsp expression, which is used to output the output of the program to the client (browser)
- Format: <% = variable or expression% >
<%= new java.util.Date()%>
1.3. JSP instruction
Using the include operation, you can include some duplicate code and continue to use it. From the perspective of normal page composition, it may sometimes be divided into several areas. Some of these areas may not need to be changed all the time. What needs to be changed is one of the specific content areas. There are now two ways to achieve the above functions.
-
Method 1: each JSP page (HTML) contains toolbar, header information, tail information and specific content
-
Method 2: divide the toolbar, header information and tail information into independent files and import them directly when using
-
Obviously, the second method is better than the first one. The first one will have a lot of duplicate code and is inconvenient to modify
-
In JSP, if you want to implement the included operation, there are two methods: static inclusion and dynamic inclusion. The static inclusion can use the include instruction, and the dynamic inclusion needs to use the include action tag.
1.3. 1. Include static include
Format:
<%@ include file="File path to include"%>
- Static inclusion is the direct replacement of the content, just like the variables defined in the program. The contents of this file are included when the servlet engine translates, so only one servlet is generated, so two pages cannot have variables with the same name.
<%--@include The two pages will be combined into one--%> <%@include file="common/header.jsp"%> <h1>Web page subject</h1> <%@include file="common/footer.jsp"%>
When using include dynamic inclusion, we can pass parameters, such as:
jsptag.jsp
We put parameters in this JSP so that we can access: http://localhost:8080/jsptag.jsp It's equivalent to http://localhost:8080/jsptag.jsp?name=kuangshen&age=12
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>1</h1> <%-- http://localhost:8080/jsptag.jsp?name=kuangshen&age=12 --%> <jsp:forward page="/jsptag2.jsp"> <jsp:param name="name" value="kuangshen"/> <jsp:param name="age" value="12"/> </jsp:forward>> </body> </html>
jsptag2.jsp
We get the parameters on another page
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>2</h1> <%--Take out parameters--%> name:<%=request.getParameter("name")%> Age:<%=request.getParameter("age")%> </body> </html>
- Access test
1.3. 2. Include dynamic include
Format:
<jsp:include page="File path to include" />
Dynamic inclusion is in the compilation stage of the code. The included part and the included part are two independent parts. They will be included dynamically only when running, such as method calls.
<%--jsp:include: Splicing pages, the essence is still three--%> <jsp:include page="/common/header.jsp" /> <h1>Web page subject</h1> <jsp:include page="/common/footer.jsp" />
1.4. JSP comments
Two kinds of syntax operations of annotation are supported in JSP
- One is to display comments, which are allowed to be seen by the client (browser);
- Display comment syntax: inherited from HTML style
- The other is implicit annotation, which is invisible to the client
- Implicit annotation syntax: inherited from JAVA style, JSP has its own annotations
1. html notes: <!-- -->:Only comments html code snippet 2. jsp Note: Recommended <%-- --%>:All can be annotated
1.5. Customize the error page
We can customize the error page ourselves and display it on the web XML, for example
jsp2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% <%-- Manual manufacturing error --%> int x = 1/0; %> </body> </html>
- Test start
- At this time, the error page of 500 pops up. We can write the error page ourselves to jump to a more beautiful error page when an error occurs
- Let's create a new error package, 500 jsp
500.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Customize 500 error interface</title> </head> <body> <h1>Customize 500 error interface</h1> <img src="../img/500.png" alt="500"> </body> </html>
- We are on the web Configuring error pages in XML
<error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page>
- Access test
- When an error occurs, we will jump to 500 written by ourselves JSP page
1.6 customize 404 page
- Similarly, we can customize 404 pages ourselves, just on the web Configure 404 page path in XML again
404.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>404</title> </head> <body> <img src="../img/404.png" alt="404" > </body> </html>
- web. Configuration in XML
<error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page>
- Test access
1.7. Nine built-in objects
Built in objects: objects that do not need to be created in jsp pages and can be used directly (objects automatically created by jsp can be used directly)
Variable name | Real type | effect |
---|---|---|
pageContext | Pagecontext (store things) | The current page shares data, and eight other built-in objects can be obtained |
request | HttpServletRequest (storage) | Multiple resources requested at one time (forwarding) |
session | Httpsession (store things) | Between multiple requests in a session |
application | ServletContext (storage) | Share data among all users |
response | HttpServletResponse | Response object |
page | Object | this object of the current page (Servlet) |
out | JspWriter | Output object, data output to page |
config | ServletConfig | Configuration object of Servlet |
exception | Throwable | Exception object |
1.8. PageContext object
- brief introduction
It is a unique object of JSP, and there is no such object in the Servlet. It is also a domain (SCOPE) object, but it can manipulate the properties in the other three domain objects. It can also get the other eight implicit objects.
PageContext is used to represent the entire JSP page. It is the scope object of the current page. Once it jumps, it will become invalid
- life cycle
It is a local variable, so its life cycle is born with the creation of JSP and disappears with the end of JSP. Each JSP page has a separate PageContext.
- The PageContext object operates on other scope storage and retrieval
Through pagecontext SetAttribute ("name", value) stores the value
Through pagecontext Getattribute ("name") gets the value
- PageContext get other built-in objects
pageContext.getRequest(); //Return request built-in object pageContext.getResponse(); //Return the response built-in object pageContext.getServletConfig(); //Return config built-in object pageContext.getException(); //Return exception built-in object pageContext.getPage(); //Return page built-in object pageContext.getOut(); //Return out built-in object pageContext.getServletContext(); //Return application built-in object pageContext.getSession(); //Return session built-in object
Requirements: we are in pagecontextdemo01 jsp stores four data, and we go to other jsp pages to get it
pageContextDemo01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--Built in object--%> <% pageContext.setAttribute("name1","1 number"); request.setAttribute("name2","2 number"); session.setAttribute("name3","3 number"); application.setAttribute("name4","4 number"); %>
pageDemo02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% // Take it from pageContext and search it // From bottom to top (SCOPE): Page - > request - > session - > Application String name1 = (String) pageContext.findAttribute("name1"); String name2 = (String) pageContext.findAttribute("name2"); String name3 = (String) pageContext.findAttribute("name3"); String name4 = (String) pageContext.findAttribute("name4"); String name5 = (String) pageContext.findAttribute("name5"); %> <%--use EL Expression output ${} --%> <h1>The retrieved value is:</h1> <h3>${name1}</h3> <h3>${name2}</h3> <h3>${name3}</h3> <h3>${name4}</h3> <%--use jsp Expression output--%> <h3><%=name5%></h3> <%--use EL Expression output--%> <h3>${name5}</h3> </body> </html>
- Note that the name5 data does not exist at this time, but what will happen if we use jsp expression and EL expression to get it respectively?
- Let's first visit / pagecontextdemo01 JSP to store data, and then visit / pagedemo02 JSP to fetch data
- Only No. 3 and No. 4 data are obtained, so this is the problem of domain objects
object | Scope |
---|---|
pageContext.setAttribute | The saved data is only valid in one page |
request.setAttribute | The saved data is only valid in one request, and the request forwarding will carry this data |
session.setAttribute | The saved data is valid only in one session, from opening the browser to closing the browser |
application.setAttribute | The saved data is only valid in the server, from opening the server to closing the server |
pageContext.setAttribute("name1","1 number"); //The saved data is only valid in one page request.setAttribute("name2","2 number"); //The saved data is only valid in one request, and the request forwarding will carry this data session.setAttribute("name3","3 number"); //The saved data is valid only in one session, from opening the browser to closing the browser application.setAttribute("name4","4 number"); // The saved data is only valid in the server, from opening the server to closing the server
- Therefore, these objects generally have the following usage scenarios
- Request: the client sends a request to the server. The generated data is useless after the user reads it. For example, news is useless after the user reads it!
- session: the client sends a request to the server, and the generated data is still useful when the user runs out, such as a shopping cart;
- application: when the client sends a request to the server, the generated data is used up by one user and may be used by other users, such as chat data;
1.9. Four domain objects
Domain object name | Range | level | remarks |
---|---|---|---|
PageContext | page range | Minimum, can only be used on the current page | Because the scope is too small, it is rarely used in development |
ServletRequest | Request scope | For one-time request or current request forwarding | After the request is forwarded, the request domain is lost when it is forwarded again |
HttpSession | Session scope | Used when data sharing is requested multiple times | Multiple requests to share data, but different clients cannot share |
ServletContext | Scope of application | Maximum, the whole application can be used | Use as little as possible. If the data is modified, it needs to be synchronized |
2,JavaBean
JavaBeans are entity classes. Is a special Java class, written in the Java language, and complies with the JavaBean API specification.
JavaBean s have specific ways to write:
- Must have a parameterless construct
- Property must be privatized
- There must be a corresponding get/set method
JavaBean s are generally used to map fields in a database
- Tables in the database correspond to classes in java
- The fields in the table correspond to the properties in the java class
- The row records in the table correspond to the objects created in java
For example, this is a people table in the database
id | name | age | address |
---|---|---|---|
1 | Qinjiang 1 | 3 | Xi'an |
2 | Qinjiang 2 | 18 | Xi'an |
3 | Qinjiang 3 | 100 | Xi'an |
class People{ private int id; private String name; private int id; private String address; } class A{ new People(1,"Qinjiang 1",3,"Xi'an"); new People(2,"Qinjiang 2",3,"Xi'an"); new People(3,"Qinjiang 3",3,"Xi'an"); }
2.1 package name of entity class
For the package name of JavaBean entity class, we have the following methods:
- com.XXX.pojo
- com.XXX.entity
- com.XXX.dto
- com.XXX.vo
2.2 entity class
JavaBean entity classes are generally used to map with database fields. For example, we create a People class
public class People { private int id; private int age; private String address; // Nonparametric structure public People() { } // Parametric structure public People(int id, int age, String address) { this.id = id; this.age = age; this.address = address; } // get/set method public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } // Override toString method @Override public String toString() { return "People{" + "id=" + id + ", age=" + age + ", address='" + address + '\'' + '}'; } }
-
If we simply create a class, it can only be called a People class, not an entity class. How can we call it an entity class?
-
We need to establish the corresponding People table in the database
-
Entity classes generally correspond to the table structure in the database one by one
javabean.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% // People people = new People(); // people.setId(); // people.setName(); // people.setAge(); // people.setAddress(); // people.getId(); // people.getName(); // people.getAge(); // people.getAddress(); %> <jsp:useBean id="people" class="com.kuang.pojo.People" scope="page" /> <jsp:setProperty name="people" property="id" value="1" /> <jsp:setProperty name="people" property="name" value="Li Qin" /> <jsp:setProperty name="people" property="age" value="3" /> <jsp:setProperty name="people" property="address" value="Xi'an" /> id<jsp:getProperty name="people" property="id"/> full name<jsp:getProperty name="people" property="name"/> Age<jsp:getProperty name="people" property="age"/> address<jsp:getProperty name="people" property="address"/> </body> </html>
The meaning of this code is the meaning of the annotated code
- jsp:userBean is equivalent to new People
- jsp:setProperty is equivalent to people setXXX
- jsp:getProperty is equivalent to people getXXX
3. MVC three-tier architecture
-
What is MVC?
Model,View,Controller
Model, view, controller
Model: JavaBean entity class and corresponding fields in database table
Views: jsp pages
Controller: servlet, which is responsible for jumping to the page
Model:
- Business processing: complete specific business operations (services)
- Data persistence layer: addition, deletion, modification and query of database (Dao)
View:
- Display page. jsp page for dynamic display and html for static data display.
- Provide a link to initiate a Servlet request
Controller: (Servlet)
- Accept the user's request and get the user's request parameters
- Give it to the business layer to process the corresponding code
- Control view jump
The process is as follows:
Login - > receive the user's login request - > process the user's request (obtain the user's login parameters, username, password) - -- > give it to the business layer to process the login business (judge whether the user name and password are correct) - > Dao layer query whether the user name and password are correct – > database
4. EL expression
-
Concept: Expression Language
-
Function: replace and simplify the writing of java code in jsp pages
-
Syntax: ${expression}
-
Configure dependency before use
<!-- JSTL Dependency of expression --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!-- standard Tag library --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
4.1 basic grammar
The syntax format of EL expression is very simple. It is written as ${expression content}
EL expression is to output the content to the page
For example, output the content named message in the request field in the browser.
Suppose we store a data named message (request.setAttribute("message","EL");) in the request field, At this time, the method of obtaining in jsp is shown in the following table:
Java code block | JSP expression | EL expression |
---|---|---|
<% String message = (String)request.getAttribute("message"); out.write(message);%> | <%=request.getAttribute("message")%> | ${message} |
We can see from the above that data can be obtained from the request domain, but EL expression is the simplest way to write. This is also the way that most of us will adopt when using JSP as a view in our actual development in the future.
Writing code in JSP pages
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>EL Introduction to expressions</title> </head> <body> <%--use java The code is stored in the request field with a name of message Data--%> <% request.setAttribute("message","Expression Language");%> Java Code block acquisition:<% out.print(request.getAttribute("message"));%> <br/> JSP Expression get:<%=request.getAttribute("message")%> <br/> EL Expression get: ${message} </body> </html>
4.2. Obtain data in four domains
The function of EL expression is to obtain data. It can only obtain data from the four fields, and the call is findAttribute(name,value); Method, search the fields one by one according to the name from small to large, return if found, and display nothing if not found.
4.3 precautions for EL expression
When using EL expression, it helps us do some processing, so that we can avoid some errors when using it. It has no null pointer exceptions, no array subscripts out of bounds, and no string splicing.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>EL Considerations for expressions</title> </head> <body> <%--EL Three of the expressions have no--%> First: no null pointer exception<br/> <% String str = null; request.setAttribute("testNull",str); %> ${testNull} <hr/> Second: no array subscript is out of bounds<br/> <% String[] strs = new String[]{"a","b","c"}; request.setAttribute("strs",strs); %> Take the first element: ${strs[0]} Take the sixth element: ${strs[5]} <hr/> Third: no string splicing<br/> <%--${strs[0]+strs[1]}--%> ${strs[0]}+${strs[1]} </body> </html>
4.4 operator of EL expression
The operators in EL expression are shown in the following figure, which are clear at a glance:
However, there are two special operators. The code of how to use them is as follows
4.4.1,empty
Empty operator: judge whether the object is null, whether the string is empty, and whether there are 0 elements in the collection. If it is empty or null, it returns an empty string and an empty array; otherwise, it returns false.
4.4. 2. Ternary operator
Conditions? True: false
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="com.itheima.domain.User" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>EL Two special operators</title> </head> <body> <%--empty Operator: It determines whether the object is null,Whether the string is an empty string and whether there are 0 elements in the collection --%> <% String str = null; String str1 = ""; List<String> slist = new ArrayList<String>(); pageContext.setAttribute("str", str); pageContext.setAttribute("str1", str1); pageContext.setAttribute("slist", slist); %> ${empty str}============When the object is null return true<br/> ${empty str1 }==========When the string is empty, the string is returned true(Note: it does not call trim()method)<br> ${empty slist}==========Yes when there are 0 elements in the collection true <hr/> <%--Ternary operator condition?really:false --%> <% request.setAttribute("gender", "female"); %> <input type="radio" name="gender" value="male" ${gender eq "male"?"checked":""} >male <input type="radio" name="gender" value="female" ${gender eq "female"?"checked":""}>female </body> </html>
5. JSTL expression
The use of JSTL tag library is to make up for the shortcomings of HTML tags. It customizes many tags for us to use. The function of tags is the same as that of java code. We only need to look at several common tags in the core tag library!
5.1 application requirements
To use the JSTL tag library, you need to import coordinates in a Java Web project.
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
5.2 core label Library
Tags that we may often use are listed here
Label name | Functional classification | classification | effect |
---|---|---|---|
<c:if> | Process control | Core tag library | Used to judge |
<c:choose> ,<c:when>,<c:otherwise> | Process control | Core tag library | For multiple condition judgment |
<c:foreache> | Iterative operation | Core tag library | For loop traversal |
5.3 use of JSTL
5.3.1,if
- If: equivalent to if statement of java code
Properties:
- test is a required attribute and accepts a boolean expression
- If the expression is true, the if label body content is displayed; if false, the label body content is not displayed
- In general, the test attribute value is used in conjunction with el expressions
be careful:
- c: The if tag does not have else. If you want else, you can define a c:if tag
5.3.2,c:out
Used to display data in JSP, like <% = >
coreis.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--introduce JSTL Core tag library so that we can use it JSTL label--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h4>if test</h4> <hr> <form action="coreif.jsp" method="get"> <%-- EL Expression to get the data in the form ${param.Parameter name} --%> <input type="text" name="username" value="${param.username}"> <input type="submit" value="Sign in"> </form> <%--Submit to this page,If the submitted user name is administrator, the login is successful--%> <c:if test="${param.username=='admin'}" var="isAdmin"> <c:out value="Welcome to the administrator!" /> </c:if> <c:out value="${isAdmin}" /> </body> </html>
- Submit form to this page
- If the value entered in the form is admin, return true and assign true to isAdmin. If the value entered in the form is not admin, return false and assign false to isAdmin
- If the value entered in the form is admin, it will be printed in the web page: welcome to the administrator!
- Otherwise, print the value of isAdmin in the web page, that is, false
5.3.3,c:choose
- choose: equivalent to the switch statement of java code
- Using the choose tag declaration is equivalent to the switch declaration
- Using the when tag for judgment is equivalent to case
- Using the otherwise tag to declare other cases is equivalent to default
5.3.4,c:set
Used to save data
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <%--Define a variable score,The value is 85--%> <c:set var="score" value="85" /> <c:choose> <c:when test="${score>=90}"> Your grades are excellent </c:when> <c:when test="${score>=80}"> Your grades are average </c:when> <c:when test="${score>=70}"> Your grades are good </c:when> <c:when test="${score>=60}"> Your grades are not good </c:when> </c:choose> </body> </html>
5.3.5,foreach
- foreach: equivalent to a for statement in java code
coreforeach.jsp
<html> <head> <title>Title</title> </head> <body> <% ArrayList<String> people = new ArrayList<>(); people.add(0,"Zhang San"); people.add(1,"Li Si"); people.add(2,"Wang Wu"); people.add(3,"Zhao Liu"); people.add(4,"Tian Liu"); request.setAttribute("list",people); %> <%-- var ,Variables traversed each time items,Object to traverse begin Where to start end Where does it end step step --%> <c:forEach var="people" items="${list}"> <c:out value="${people}" /> <br> </c:forEach> <hr> <c:forEach var="people" items="${list}" begin="1" end="3" step="1"> <c:out value="${people}" /> </c:forEach> </body> </html>
6. Modify jsp template in IDEA
You can modify the jsp template in the IDEA