1. Introduction to JSP
JSP (Java Server Pages) is a server-side scripting language. It is a technology that adds Java language to HTML pages to generate dynamic pages: new tags (<%, %>,...) are added.
JSP is a dynamic web page generation technology developed based on Java and Servlet. Its underlying implementation is Java Servlet.
JSP pages are composed of HTML code and Java code embedded in it. The server processes these Java codes after the page is requested by the client, and then returns the generated HTML page to the client's browser.
2. JSP execution process The client requests the JSP page -> JSP Parser parses *.jsp and compiles it into *.java -> javac command compiles it into *.class -> executes the class file -> responds and returns the result to the client
JSP code contains two categories: JSP elements and Template data. Template data refers to the part that the JSP engine does not process, that is, the JSP engine will directly pass out the parts other than the tags <%...%> without any processing.
When JSP is executed for the first time or after modifying the JSP file, it will call JSP Parser to compile the *.jsp file into a servlet program, so it will be slower.
3. JSP basic syntax
1. Two annotation types
(1) HTML comment You can add a comment in HTML format to the JSP code. This comment is sent to the client but is not displayed on the page. The syntax is as follows:
<!-- Comments in HTML format, visible when viewing source code on the client -->
<!-- This comment was added by <%=programmer%>-->
If the programmer is a hackiller, the comment returned on the client is <!-- This comment is added by the hackiller -->
(2) JSP comments are written in the JSP code but are not sent to the client.
<%-- JSP comment, this comment will be ignored when JSP is compiled --%>
<%-- /*Multi-line comments in Scriptlet*/ --%>
<%-- /**Multi-line comments in Scriptlet, which can be extracted from java files using javadoc*/ --%>
<%-- JSP single line comment--%>
2. 3 script elements
(1) Declaration of global variables
<%! int i=0; String str="Hello World!"; %>
(2)Expression
In JSP code, expressions are often used to output the value of a variable, which can be anywhere
<%! int a=1; int b=2; String str="Hello World!"; %>
<%=a+b%> <%=str>
PS: You cannot use the ";" symbol as the terminator of an expression. But the same expression must end with a semicolon in the Scriptlet.
(3)Scriptlet
A script segment is used to contain a valid Java program segment
<% int b=3; %>local variable
3. 3 command elements
(1)page command
<%@ page contentType="text/html;charset=utf-8"%>
Define the global attributes of the JSP file, including: language, extends, import, session, buffer, autoflush, isThreadSafe, info, errorPage, isErrorPage, contentType (output format from server to client)
Its location can be anywhere on the page, but it is recommended to place it at the top of the page.
language: declares the type of scripting language. Currently, only "java" can be used.
extends: Indicates the full name of the Java Class that needs to be added when compiling JSP. It will limit the compilation ability of JSP, so use with caution!
import: List of java packages that need to be imported.
session: Set whether the client requires HTTP Session. Default is true.
buffer: The size of the buffer is used by the out object to process the output of the executed JSP to the client browser. The default value is 8Kb.
autoFlush: Sets whether to force output if the buffer overflows. If it is defined as true (default value), the output will be normal; if it is defined as false, an unexpected error will occur.
isThreadSafe: Sets whether the JSP file can be used in multiple threads. Default is true.
info: text information. It can be retrieved using the Servlet.getServletInfo() method.
errorPage: Set the JSP file that handles exception events
sErrorPage: Set whether this page is a page that handles exception events. If set to true, the exception object can be used.
contentType: Set the MIME type and character encoding set. The default MIME type is text/html, and the default character set is charset=ISO-8859-1.
Multiple < %@page %> directives can be used in a page, but except for the import attribute, other attributes can only be used once.
Packages imported by JSP by default. The following packages have been imported during JSP compilation, so there is no need to use the page directive to introduce them in the JSP file:
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
(2)include directive
Html code
<%@ include file = "relative path" %>
Use the include directive to include a static file in JSP and parse the JSP statements in this file.
If the path starts with "/", then this path mainly refers to the context path of the jsp application.
If the path is opened as a file name or file directory, then this path is the current path of the JSP file being used.
(3)taglib command
Html code
<%@ taglib uri = "TagLibrary" prefix = "mypfx" %>
Use the taglib directive to define a tag library and its custom prefix.
uri: Uniform Resource Identifier uniquely names the custom label based on the prefix of the label, which can be a relative or absolute path.
prefix: the prefix of the custom label. Do not use jsp, jspx, java, javax, servlet, sun, sunw as prefixes, these have been declared reserved by Sun.
4. 8 action commands
(1) Page jump: <jsp:forward>
The <jsp:forward> tag passes a request object containing a user request from one jsp file to another.
Contains 2 attributes in total
The page attribute is an expression or a string describing the file or URL to be directed.
<jsp:param>Send one or more parameters to a dynamic file. If the <jsp:param> tag is used, the target file must be a dynamic file (such as Servlet or JSP, etc.)
Html code
<jsp:forward page=test.jsp>
<jsp:param name="username" value="<%=user%>"/>
<jsp:param name="password" value="12345678"/>
</jsp:forward>
Get the username through request.getParameter("username")
(2)Include page: <jsp:include>
<jsp:include> allows the inclusion of static and dynamic web resources, and the results of these two inclusions are different.
If only static files are included, then this inclusion only adds the contents of the included file to the JSP file, similar to < %@include% >;
If a dynamic web resource is included, the included file will also be executed by the JSP compiler.
If this include file is dynamic, you can also use <jsp:param> to pass parameters and parameter values.
(3) Create Bean: <jsp:useBean>
Create a Bean instance and specify its name and scope.
<jsp:useBean id="beanInstanceName" scope="page|request|session|application" class="package.className"/>
Contains 5 attributes.
id: Confirm the Bean variable in the defined scope, and use the id to use this Bean instance in the program. The value of id is case sensitive.
Scope: The scope in which the Bean exists and the valid scope of the id variable name. The default value is page.
class: Use the new keyword and class constructor to instantiate a bean from a class. The class cannot be abstract and must have a public, no-argument constructor.
type: If this Bean already exists in the specified scope, using type will assign a data type to this Bean. If type is used without class or beanName, the bean will not be instantiated.
beanName: beanName can be a string package.class, or a jsp expression, and its value will be passed to the Beans.instantiate method. The value of type can be the same as beanName, its base class, or the interface it implements.
(4) Set Bean properties: <jsp:setProperty>
<jsp:setProperty name="beanInstanceName" property="*"|property="propertyName" value="string|<%=expression%>"|param="parameterName"/>
name: Indicates the name of the Bean instance that has been created in <jsp:useBean>, that is, id.
property: Match the properties in the Bean
param: refers to the parameter name in the request object, and sets the corresponding value to the Bean attribute.
value: Use the specified value to set the Bean property. This value can be a string or an expression. If it is a string, it will be converted to the type of the Bean attribute (for example, "0.98" will be converted to the double type 0.98). If it is an expression, its type is required to be consistent with the type of the Bean attribute.
PS: Param attributes and value attributes cannot be used at the same time in the same <jsp:setProperty>
(5) Get Bean properties: <jsp:getProperty>
Get the attribute value in the existing Bean object and display it on the page.
<jsp:getProperty name="beanInstanceName property="propertyName"/>
name: The same name as the existing object instance.
property: the name of the property in the object
(6) Use Applet plug-in: <jsp:plugin>
Html code
<jsp:plugin type="applet" code="MeidaPlay.class" codebase="../classes">
<jsp:parmas>
<jsp:param name="way" value="Hall"/>
</jsp:params>
<jsp:fallback>
<p>Unable to load applet!</p>
</fallback>
</jsp:plugin>
Use <jsp:plugin> to insert an applet or Bean, and if necessary, download a Java plug-in to execute it.
(7) Define parameters: <jsp:param>
Can be used in <jsp:include>, <jsp:forward>, <jsp:plugin>.
(8) Plug-in error message: <jsp:fallback>
When the <jsp:plugin> plug-in cannot be displayed normally, a prompt message is displayed.
3. JSP built-in objects
1. Request: Request object. This object encapsulates the information submitted by the user. The encapsulated information can be obtained by calling the corresponding method of the object.
When the request object obtains the Chinese characters submitted by the customer, garbled characters will appear and special processing must be performed.
Commonly used methods:
getParameter(String parameterName): Get the form submission information.
getProtocol(): Get the protocol used by the customer.
getServletPath(): Get the page where the customer submitted information.
getMethod(): The method to obtain the information submitted by the customer.
getHeader(String str): Get the values of accept, accept-encoding and Host in the HTTP header file.
getRermoteHost(): Get the customer's IP address.
getServerName: Get the server name.
getServerPort: Get the port number of the server.
getParameterNames(): Get the names of all parameters submitted by the client.
2. Response: The response object responds dynamically to the client's request and sends data to the client.
(1) Dynamically respond to the contentType attribute. Use the page command to statically set the contentType attribute of the page. When setting this attribute dynamically, use response.setContextType("text/html;charset=utf-8");
(2)Response redirection
response.sendRedirect("index.jsp");
3. Session: session object
(1)What is a Session object?
The Session object is automatically created when the first JSP page is loaded to complete session management.
It begins when a client opens a browser and connects to the server, and ends when the client closes the browser and leaves the server. This is called a session.
(2) ID of Session object
When a customer visits a JSP page on the server for the first time, the JSP engine generates a Session object and assigns an ID number of String type. The JSP engine also sends this ID number to the client and stores it in a cookie. In this way, the Session object, It is not until the client closes the browser that the client's Session object is modified by the server, and the session correspondence with the client disappears.
(3)Common methods
public String getId(): Get the number of the Session object.
public void setAttribute(String str,Object obj): Add the parameter object to the Session object.
public Object getAttribute(): Get the attributes in the Session object based on the attribute name.
public boolean isNew(): Determine whether it is a new customer.
4. Application: application object
(1)What is an Application object?
This Application object is generated after the server is started. When a customer browses between various pages of the website visited, the Application object is the same, and all customers share this built-in Application object.
(2)Common methods
setAttribute(String key,Object obj): Add the parameter object to the Application object.
getAttibute(String key): Get the attributes in the Application object based on the attribute name
5. Out: output object
The out object is an output stream used to output data to clients.
out.print(): Output various types of data.
out.newLine(): Outputs a newline character.
out.close(): Close the stream.
6. Config: Configuration object Generally, we use the Config object to obtain some initialization configuration information. Commonly used methods are getInitParameter and getInitParameterNames to obtain the parameters during Servlet initialization.
7.Page: page object
The page object represents the running class object generated by the JSP file and is not recommended for general readers.
8.PageContext: page context object
The PageContext class introduced by JSP allows you to access many properties of the page. The pageContext variable stores the value of the PageContext object associated with the current page. The PageContext class has methods such as getRequest, getResponse, getOut, and getSession.
9.Exception: exception object
The exception object represents the exception object generated when the JSP file is running. This object cannot be used directly in ordinary JSP files, but can only be used in
< %@page isErrorPage="true"%> is used in JSP files. This is because the error object generated when the JSP file is running is thrown out and can only be intercepted by a JSP that uses the < %@pageisErrorPage="true"% > tag to intercept the error object. The most commonly used method is getMessage, used to obtain error information.
4. Instance login page: index.jsp
Html code
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>System login</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/vbulletin.css" rel="stylesheet" type="text/css">
<style type="text/css">
.btn {
font-family: "Tahoma", "宋体";
font-size: 9pt;
color: #001E3C;
BORDER-BOTTOM: #6794BC 1px solid;
BORDER-LEFT: #8BB8E0 1px solid;
BORDER-RIGHT: #6794BC 1px solid;
BORDER-TOP: #8BB8E0 1px solid;
background-image: url(image/buttonbg.gif);
CURSOR: hand;
font-style: normal;
padding-left: 3px;
padding-right: 3px;
}
</style>
<script type="text/javascript">
function doLogin(){
var vform = document.loginform;
if(!loginform.username.value){
alert("Please enter username!")
return;
}
if(!loginform.password.value){
alert("Please enter password!")
return;
}
vform.submit();
}
</script>
</head>
<body topmargin="0" leftmargin="0" >
<form action="receive.jsp" name="longinForm" method="post">
<table width="100%" height="100%">
<tr>
<td align="center" valign="middle">
<TABLE id="form1"
cellspacing="0" cellpadding="0" border="0" style="width: 500;">
<CAPTION style="display: none">
</CAPTION>
<TR>
<TD>
<TABLE width="100%" height="100%" cellspacing="0"
cellpadding="0" border="0" style="table-layout: fixed">
<TR>
<TD valign="top">
<FIELDSET id="form1_group0" style="width: 100%;">
<LEGEND>System login</LEGEND>
<DIV>
<DIV style="width: 100%; height: 100%">
<TABLE width="100%" cellspacing="0"
cellpadding="4" border="0" style="table-layout: fixed;">
<COLGROUP>
<COL width="100"></COL>
<COL width="50%"></COL>
<COL width="100"></COL>
<COL width="50%"></COL>
</COLGROUP>
<TR>
<TD align="right">
username
</TD>
<TD class="InnerTableContentCell">
<input type="text" name="username"
style="width: 100%;">
</TD>
<TD align="right">
password
</TD>
<TD>
<input type="password" name="password"
style="width: 100%;" />
<input type="hidden" name="action2" value="0">
</TD>
</TR>
<TR>
<TD colSpan="4"
align="right">
<input type="button" name="login" value="Login" onclick="this.form.submit();" class="btn"/>
</TD>
</TR>
</TABLE>
</DIV>
</DIV>
</FIELDSET>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</td>
</tr>
</table>
</form>
</body>
</html>
Receive data page: receive.jsp
Html code
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" info="action tag"%>
<jsp:useBean id="userVo" class="exercise.vo.UserVo" scope="request">
<jsp:setProperty name="userVo" property="name" param="username"/>
<jsp:setProperty name="userVo" property="password" param="password"/>
</jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" >
<link href="css/vbulletin.css" rel="stylesheet" type="text/css">
</head>
<body>
This is my JSP page. <br>
<hr>Use <jsp:getProperty> to get the value submitted in the form<br>
name:<jsp:getProperty property="name" name="userVo"/><br>
password:<jsp:getProperty property="password" name="userVo"/>
<br><br><hr>
<%
out.println("Get directly from the vo object:<br> name:"+userVo.getName()+
"<br>password:"+userVo.getPassword()+"<br>");
String serviceName = request.getServerName();//request object inside 1.jsp
out.println("<br><hr>Server name: "+serviceName);
out.println("<br>MIME type: "+response.getContentType());//2.jsp internal response object
session.setAttribute("sessionName","session object inside jsp");//3.jsp internal session object
out.println("<br>session object: "+session.getAttribute("sessionName"));//4.jsp internal out object
pageContext.setAttribute("pageContext","Context environment reference");//pageContext object inside 5.jsp
//6.application
//7. config ServletConfig instance
//8. Instance of page java.lang.Object
//9. exception must use an instance of java.lang.Throwable on the page with isErrorPage=true in the page directive.
String info = pageContext.getServletContext().getServerInfo();
out.println("Get the info attribute in the page command: "+info);
%>
</body>