Article directory
Introduction to JSP
JSP stands for Java Server Pages (Java Server Pages), which is a dynamic web development technology
-
Simplified design of Java servlets, mainly used to implement the user interface part of Java web applications
-
Use JSP tags to insert Java code into HTML web pages (dynamic parts are written in Java). Tags usually start with <% and end with %>
-
JSP embeds Java code in HTML pages, obtains user input data through web forms , accesses databases and other data sources, and then dynamically creates web pages.
-
Web applications developed with JSP are cross-platform and can run under Linux as well as other operating systems.
-
JSP separates web page logic from display of web design
The main differences between html and jsp:
.html is a static page containing fixed page content
.jsp is a dynamic page. The page data can be dynamically updated and supports nested java code and html code.
How JSP works
When the browser accesses the page and the server finds the file with the suffix .jsp , it will find the index.jsp file according to the path , translate the index.jsp into the index_jsp.java file and compile it to generate the index_jsp.class file , and load the class file and run it.
Translating JSP into a java file is to output all the HTML code in the JSP through the stream, and finally translate it into a class and then load it into the virtual machine. It is essentially a servlet and responds back (the response back is to stream the HTML code in the JSP way to write back to the browser)
JSP life cycle
JSP life cycle, that is, the entire process from creation to destruction,
Similar to the servlet life cycle ( Servlet Working Principle and Life Cycle ), the JSP life cycle also includes compiling JSP files into servlets
-
Compilation phase:
The servlet container parses the JSP file, converts the JSP file into a servlet, then compiles the servlet source file and generates the servlet class -
Initialization phase: jspInit()
loads the servlet class corresponding to JSP, creates an instance and calls its initialization method
(generally only executed once) -
Execution phase: _jspService()
calls the service method of the servlet instance corresponding to JSP (all interactive behaviors related to the request until destroyed) -
Destruction phase: jspDestroy()
calls the destruction method of the servlet instance corresponding to the JSP, and then destroys the servlet instance
Code example:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>life.jsp</title>
</head>
<body>
<%!
private int initVar=0;
private int serviceVar=0;
private int destroyVar=0;
%>
<%!
public void jspInit(){
initVar++;
System.out.println("jspInit(): JSP被初始化了"+initVar+"次");
}
public void jspDestroy(){
destroyVar++;
System.out.println("jspDestroy(): JSP被销毁了"+destroyVar+"次");
}
%>
<%
serviceVar++;
System.out.println("_jspService(): JSP共响应了"+serviceVar+"次请求");
String content1="初始化次数 : "+initVar;
String content2="响应客户请求次数 : "+serviceVar;
String content3="销毁次数 : "+destroyVar;
%>
<h1>JSP demo</h1>
<p><%=content1 %></p>
<p><%=content2 %></p>
<p><%=content3 %></p>
</body>
</html>
JSP comments
<!-- html注释内容,查看源码时能看到 -->
<%-- jsp注释,查看⻚⾯源码时看不到 --%>
Main notes:
grammar | describe |
---|---|
<%--Comment--%> | JSP comments, the comment content will not be sent to the browser or even compiled |
<!-- Comments --> | HTML comments, you can see the comment content when viewing the source code of the web page through the browser |
<% | Represents static <% constant |
%> | Represents static %> constant |
\’ | Single quotes used in attributes |
\" | Double quotes used in attributes |
Nested Java code in JSP
Use small script: <% java code%>
Basic format:
声明标签:
<%!变量或者⽅法声明%>
表达式标签:
<%= 表达式%> 在⻚⾯上显示的效果
程序代码标签:
<%java代码%> ⻚⾯上动态展示内容
page指令:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
代码示例:
<body>
<%! int i=10;%><!--成员变量-->
<%! public void show(){
}%> <!--成员⽅法-->
<%=i%> <!--输出变量值-->
</body>
JSP syntax
Chinese encoding problem
If we want to display Chinese normally on the page, we need to add the following code to the head of the JSP file
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
script
Script programs can contain any Java statements, variables, methods, or expressions as long as they are valid in the scripting language
Any text, HTML tags, and JSP elements must be written outside the script program
Syntax format:
一、
<% 代码片段 %>
二、等价的xml格式:
<jsp:scriptlet>
代码片段
</jsp:scriptlet>
declare variables
A declaration statement can declare one or more variables and methods
一、
<%! declaration; [ declaration; ]+ ... %>
二、等价的xml语句
<jsp:declaration>
代码片段
</jsp:declaration>
Code example:
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
expression
The scripting language expression contained in a JSP expression is first converted into String and then inserted into the place where the expression appears.
The expression element can contain any expression that conforms to the Java language specification , but a semicolon cannot be used to terminate the expression.
一、
<%= 表达式 %>
二、 等价的xml语句
<jsp:expression>
表达式
</jsp:expression>
Code example:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
</head>
<body>
<p>
今天的日期是: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
Output:
今天的日期是: 2021-9-21 13:40:07
instruction
JSP instructions are used to set properties related to JSP pages
Syntax format:
<%@ directive attribute="value" %>
directive:指令名称 attribute 属性名 value:属性值
Three command tags:
Command name | describe |
---|---|
<%@ page … %> | Define page dependency attributes, such as script language, error page, cache requirements, etc. |
<%@ include … %> | include other files |
<%@ taglib … %> | Introduce the definition of the tag library (can be a custom tag) |
Page command
The Page directive provides the container with usage instructions for the current page. A JSP page can contain multiple page directives.
The syntax format of the Page command:
<%@ page attribute="value" %>
attribute name | attribute value | describe |
---|---|---|
language | java | The language used when interpreting the JSP file, generally java language, the default is java |
extends | The full name of any class | Which class should be inherited when compiling the JSP file? JSP is a Servlet, so when specifying inheritance of a common class, you need to implement the init, destroy and other methods of the Servlet. |
import | Any package name or class name | Import the classes, packages, etc. used in the JSP. Import is the only page directive attribute that can be declared multiple times. One import can reference uogelei, separated by English commas <%@ page import=package name. Class name, package name. Class name %> |
session | true、false | Whether the Session object is built-in in the JSP. If it is true, the Session object is built-in and can be used directly. Otherwise, it defaults to true. |
autoFlush | true,false | Whether to run the cache. If it is true, the string output by using out.println() and other methods does not arrive at the client server immediately, but is temporarily stored in the cache. The cache is full or the program is completed or It does not reach the client until the out.flush() operation is executed. The default is true. |
buffer | none or number KB | Specify the cache size, valid when autoFlush is set to true, for example <%@ pagebuffer=10kb%> |
isThreadSafe | true,false | Is it thread safe? If true, multiple threads will be run to run the jsp program at the same time. Otherwise, only one thread will be run and the other threads will wait. The default is false. |
isErrorPage | true,false | Specify whether the page is an error display page. If it is true, the JSP has a built-in Exception object exception, which can be used directly. Otherwise, there is none. The default is false. |
errorPage | Relative path to a JSP page | Indicates an error page. If the JSP program throws an uncaught exception, it will go to the page specified by errorPage. The isErrorPage attribute of the page specified by errorPage is usually true, and the built-in exception object is an uncaught exception. |
contentType | Valid document types | The client browser determines the document type based on this attribute. For example, the HTML format is text/html, the plain text format is text/plain, the JPG image is image/jpeg, the GIF image image/gif WORD document is application/msword. This attribute Often followed by charset to set the encoding, its function is to notify the server and browser to use the same code table. |
pageEncoding | UTF8, ISO8859-1, etc. |
Include directive
JSP can include other files through the include directive
The included files can be JSP files, HTML files or text files. The included files can be regarded as part of the JSP file and will be compiled and executed at the same time.
The file name in the include directive is actually a relative URL address. If there is no path associated with the file, the JSP compiler will search in the current path by default.
Syntax format:
<%@ include file="⽂件相对 url 地址" %>
Taglib directive
JSP API allows users to customize tags. A custom tag library is a collection of custom tags.
The Taglib directive introduces the definition of a custom tag collection, including library paths and custom tags.
The uri attribute determines the location of the tag library, and the prefix attribute specifies the prefix of the tag library (can be customized)
Syntax format:
<%@ taglib uri="uri" prefix="" %>
JSP built-in objects
A total of 9 objects are predefined in JSP: request, response, session, application, out, pagecontext, config, page, exception
request object
Function:
Represents the client's request information and accepts data transmitted to the server through the HTTP protocol (including header information, system information, request methods, request parameters, etc.)
Type: javax.servlet.httpServletRequest
The scope of the request object is one request
response object
Function:
Represents the response to the client and passes the object processed by the JSP container back to the client.
Type:HttpServletResponse
Scope: only valid within JSP pages
session object
Objects automatically created by the server related to user requests
The server generates a session object for each user to save the user's information and track the user's operation status.
The Map class is used inside the session object to save data , and the format of the saved data is "Key/value"
The value of the session object is not limited to string type
application object
Function:
Save information in the server until the server is shut down (the information saved in the application object will be valid throughout the entire application)
Compared with the session object, the application object has a longer life cycle and is similar to the "global variables" of the system.
- Difference:
request-single request
session-during browser access (during session)
application-during server startup, the stored data can be cross-browser
out object
Function:
Output information in the web browser and manage the output buffer on the application server
When using the out object to output data, you can operate the data buffer to clear the remaining data in the buffer in time to make room for other outputs.
After the data output is completed, the output stream must be closed in time
Code example:
out.print("<script type='text/javascript'>alert('⽤户名不存在');location.href='index.jsp'</script>");
pageContext object
Function:
Get any range of parameters
Through it, you can obtain the out, request, response, session, application and other objects of the JSP page.
The creation and initialization of the pageContext object are completed by the container. The pageContext object can be used directly in the JSP page.
config object
Function:
Obtain server configuration information
A config object can be obtained through the getServletConfig() method of the pageConext object.
When a Servlet is initialized, the container passes certain information to the Servlet through the config object. Developers can provide initialization parameters for Servlet programs and JSP pages in the application environment in the web.xml file.
Code example:
//将image路径转换成服务器端的路径
String url= config.getServletContext().getRealPath("/image");
<h1>url=<%=url %></h1>
page object
The page object represents the JSP itself and is only legal within the JSP page.
The page implicit object essentially contains the variables referenced by the current Servlet interface, similar to the this pointer in Java programming.
exception object
Function:
Display exception information, only used in pages containing isErrorPage="true"
If you use this object in a general JSP page, the JSP file will not be compiled.
If an uncaught exception occurs in the JSP page, an exception object will be generated, and the exception object will be transferred to the error page set in the page directive, and then the corresponding exception object will be processed in the error page.
status code
status code | information | describe |
---|---|---|
100 | Continue | Only part of the request is received by the server, but as long as it is not rejected by the server, the client will continue the request. |
101 | Switching Protocols | server switch protocol |
200 | OK | Request confirmed |
201 | Created | Complete when requested, a new resource is created |
202 | Accepted | The request was accepted but not processed |
300 | Multiple Choices | A hyperlink table. Users can select a hyperlink and access it. A maximum of 5 hyperlinks are supported. |
301 | Moved Permanently | The requested page has been moved to a new URL |
302 | Found | The requested page has been temporarily moved to a new URL |
303 | See Other | The requested page can be found under a different URL |
306 | Unused | This status code is no longer used, but the status code is retained |
307 | Temporary Redirect | The requested page has been temporarily moved to a new URL |
400 | Bad Request | The server does not recognize the request |
401 | Unauthorized | The requested page requires a username and password |
402 | Payment Required | This status code cannot be used yet |
403 | Forbidden | Access to the requested page is prohibited |
404 | Not Found | The server cannot find the requested page |
405 | Method Not Allowed | The method specified in the request is not allowed |
406 | Not Acceptable | The server can only create a response that is unacceptable to the client |
407 | Proxy Authentication Required | A proxy server must be authenticated before requests can be served |
408 | Request Timeout | The request time exceeded the time that the server could wait, and the connection was disconnected. |
409 | Conflict | There is a conflict in the request |
410 | Gone | The requested page is no longer available |
411 | Length Required "Content-Length" is not defined and the server refuses to accept the request. | |
412 | Precondition Failed | The requested precondition was evaluated by the server as false |
413 | Request Entity Too Large | 因为请求的实体太大,服务器拒绝接受请求 |
414 | Request-url Too Long | 服务器拒绝接受请求,因为URL太长。多出现在把"POST"请求转换为"GET"请求时所附带的大量查询信息 |
415 | Unsupported Media Type | 服务器拒绝接受请求,因为媒体类型不被支持 |
500 | Internal Server Error | 请求不完整,服务器遇见了出乎意料的状况 |
501 | Not Implemented | 请求不完整,服务器不提供所需要的功能 |
502 | Bad Gateway | 请求不完整,服务器从上游服务器接受了一个无效的响应 |
503 | Service Unavailable | 请求不完整,服务器暂时重启或关闭 |
504 | Gateway Timeout | 网关超时 |
505 | HTTP Version Not Supported | 服务器不支持所指定的HTTP版本 |
EL表达式
在JSP2.0中,EL从JSTL中剥离出来,放置在JSP规范中,称为JSP2.0规范的一部分
在JSP中使用EL表达式,可以简化对象和变量的访问是EL表达式
语法:
${
需要展示信息的名字}
当表达式没有指定变量或者对象的范围时:
容器会依次从pageContext—>request—>session—>application中查找该变量或对象,
通过隐含对象获得指定作⽤域的值:
pageScope对象,⽤于获取当前⻚⾯的属性值
requestScope对象,⽤于获取请求范围的属性值
sessionScope对象,⽤于获取会话范围的属性值
applicationScope对象,⽤于获取程序范围的属性值
语法:
${
requestScope.key}
基础操作符:
术语 | 定义 |
---|---|
算术型 | + 、-、 * /(div) 除 、 %(mod) 余数 |
逻辑型 | and、&&、or、||、!、not |
关系型 | ==、eq、!=、ne、、gt、<=、le、>=、ge。可以与其他值进⾏⽐较,或与布尔型、字符串型、整型或浮点型⽂字进⾏⽐较 |
Empty | Empty操作符是⼀个前缀操作符⽤于判断⼀个值是否为null或者为empty如String str =“”; ${empty str} 返回值为true |
条件型 | A ?B :C。根据 A 赋值的结果来赋值 B 或 C |
代码示例:
单个变量:${
a+10}<br>
单个变量:${
s}<br>
单个对象:${
key.属性名}
//对象类型
Users u=new Users();
u.setName("王⽼五");
u.setPass("abc");
pageContext.setAttribute("u1",u);
user.name=${
u1.name}
user.pass=${
u1.pass}
// list集合对象:
List list=new ArrayList();
list.add("刘能");
list.add(30);
list.add(u);
pageContext.setAttribute("list2",list);
list1=${
list2[0]}<br/>
list2=${
list2[1]}<br/>
list3=${
list2[2].pass}<br/>
// map集合:
k1=${
map1.k1}<br>
k2=${
map1.k2.username}--- ${
map1.k2.password}
判断变量是否有值或是否存在: ${
empty key值}
List list2=new ArrayList();
list2.add("aa");
request.setAttribute("list222",list2);
判断list中是否有数据: ${
empty list222}
JSTL
JSP标准标签库(JSTL)是JSP标签集合,封装了JSP应用的通用核心功能
JSTL支持通用的、结构化的任务(迭代、条件判断、XML文档操作、国际化标签、SQL标签),还提供了一个框架来使用集成JSTL的自定义标签,根据JSTL标签所提供的功能,可以将其分为5个类别:核心标签、格式化标签、sql标签、xml标签、jstl函数
-
作用:
简化jsp⻚⾯编写代码 -
语法格式:
①standard.jar 和 jstl.jar 文件拷贝到 /WEB-INF/lib/ 下
②在JSP页面中引入<%@ taglib prefix=”页面使用的名称” uri=”功能范围的路径”%>
功能范围 | 前缀 | uri |
---|---|---|
core | c | http://java/sun.com/jsp/jstl/core |
i18n | fmt | http://java/sun.com/jsp/jstl/fmt |
sql | sql | http://java/sun.com/jsp/jstl/sql |
xml | x | http://java/sun.com/jsp/jstl/xml |
functions | fn | http://java/sun.com/jsp/jstl/function |
核心标签
核心标签是最常用的 JSTL标签
引用核心标签库语法:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
核心标签分类:
- 表达式操作
out、set、remove、catch - 流程控制
if、choose、when、otherwise - 迭代操作
forEach、forTokens - URL操作
import、param、url、redirect
① <c:set>
主要⽤来将变量存储⾄JSP范围中 或是JavaBean的属性或Map对象中
名称 | 说明 | 是否必须写 | 默认值 |
---|---|---|---|
Value | 要被存储的值 | 否 | ⽆ |
var | 存⼊的变量名称 | 否 | ⽆ |
scope | var变量的JSP范围 | 否 | Page |
target | JavaBean或Map对象 | 否 | ⽆ |
property | 指定target对象的属性 | 否 | ⽆ |
② <c:out>
主要用来显示数据的内容
名称 | 说明 | 是否必须写 | 默认值 |
---|---|---|---|
value | 需要显示出来的值 | 是 | ⽆ |
default | 如果value的值为null,则显示default的值 | 否 | ⽆ |
escapeXml | 是否转换特殊字符,如:<转换成 & lt; | 否 | True |
③ <c:remove>
主要负责移除变量
名称 | 说明 | 是否必须写 | 默认值 |
---|---|---|---|
Var | 欲移除的变量名称 | 是 | ⽆ |
Scope | var变量的jsp范围 | 否 | Page |
④ <c:if>
主要用于进行if判断,如果为true,则输出标签体中的内容
名称 | 说明 | 是否必须写 | 默认值 |
---|---|---|---|
Test | 表达式的结果为true,则执⾏体内容,false则相反 | 是 | ⽆ |
var | 如果用来存储test运算的结果(true或false) | 否 | ⽆ |
scope | Var变量的JSP范围 | 否 | page |
⑤ <c:choose>,<c:when>,<c:otherwise>
作用相当于if-else
名称 | 说明 | 是否必须写 | 默认值 |
---|---|---|---|
test | 如果表达式的结果为true,则执⾏体内容,false则相反 | 是 | ⽆ |
⑥ <c:forEach>
循环控制,它可以将数组,集合(Collection)中的成员循序浏览一遍
名称 | 说明 | 是否必须写 | 默认值 |
---|---|---|---|
var | ⽤来存放现在指定的成员 | 是 | ⽆ |
items | 被迭代的集合对象 | 否 | ⽆ |
varStatus | ⽤来存放现在指的相关成员信息 | 否 | ⽆ |
begin | 开始的位置 | 否 | 0 |
end | 结束的位置 | 否 | 最后⼀个成员 |
step | 每次迭代的间隔数 | 否 | 1 |
格式化标签:
① fmt:formatDate
- 作用
将日期类型格式化为指定模式的字符串
属性 | 描述 |
---|---|
value | 将要被格式化的数据 |
pattern | 格式化的模式,与SimpleDateFormat的参数设置⼀样 |
var | 格式化后的字符串所要存放的变量,若不指定var,则会将格式化的结果直接显示在⻚⾯ |
scope | Domain attribute space where variables are stored, default page |
type | Its values are date, time, and both, indicating whether the given value contains date, time, or both. The default is date. |
②fmt:parseDate
- Function:
Used to convert the specified string into date type
<fmt:parseDate value="${now }" pattern=“yyyy-MM-dd” var=“today”/>
Attributes | describe |
---|---|
Value | The time the server gets |
Pattern | Converted format |
Was | Variables displayed on the page |
③ fmt:formatNumber
- Function:
Format numbers according to the specified format
Attributes | describe |
---|---|
maxIntegerDigits | The largest number of digits in the integer part |
minIntegerDigits | The smallest number of digits in the integer part |
maxFrctionDigits | Maximum number of digits in the decimal part |
minFrctionDigits | Minimum number of digits in decimal part |
was | Variable to store formatted results |
scope | Scope of var attribute |
integerOnly | Whether to parse only integers true or floating point numbers false |