First, JSP introduction and use
1, what is JSP
JSP full name for Java Server Pages, Chinese named Java Server Pages, its fundamental is a simplified Servlet design, it is initiated by Sun Microsystems, many companies together to establish a dynamic web page technology standard
JSP technology is a bit similar to ASP technology, it is in the traditional webpage HTML file (*.htm,*.html) insert Java program section (Scriptlet) and JSP tag (tag), so as to form JSP files, suffix named (*.jsp).
Web applications developed with JSP are cross-platform and can run on Linux as well as other operating systems.
JSP separates the Web logic from the display of Web design, supports reusable component-based design, and makes the development of Web-based applications fast and easy.
- *.html static pages (containing fixed page content)
- *.jsp dynamic pages (page data can be dynamically updated, support nested Java code and HTML code, equal to HTML+ Java)
2. Why does JSP appear
What is JSP technology, JSP and Servlet difference and connection?
- Using servlets to generate dynamic pages, you need to print out many HTML tags in the code with out.print() and return them to the client browser interface for display.
- In servlets, you have to mix statically displayed content with code that generates content dynamically.
- Using servlets to develop dynamic web pages, programmers and web editors cannot work together. In order to separate the front and back ends and reduce the complexity and redundancy of the code, JSP technology came into being.
Servlet presents the information inconvenient, introduced JSP.
JSP is also essentially a servlet!!!!!! (The original servlet is a Java file, whereas the JSP is a different file.)
A JSP is an HTML page with Java code embedded in it.
3, JSP how to nest Java code (understand, basic will not use small script to write Java code)
Small script (<% Java code %>)
Declaration tag: <%! Variable or method declaration %>
Expression tag: <%= expression %> how it appears on the page
Program code tag: <% Java code %> Dynamically displays content on the page
annotation
<%– JSP comments, you can’t see –%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <! - HTML comments (this annotation will be displayed in the JSP page) - > < % - the JSP comment - % > < % - code label - % > < % int a = 10; int b=20; % % > < % - expression tags - > a variables + b = < % = a + b % > < % - statement label - % > < %! Public void ABC (){system.out.println (" ABC method "); } %> <% abc(); %> </body> </html>Copy the code
Two, JSP working principle
1. Brief introduction
When the browser to http://localhost:8080/day9\_1/index.jsp.
The server finds the suffix.jsp, it finds the index_jsp file based on the path, translates the index_jsp. Java file, compiles the Java file, generates an index_jsp.class file, and loads the class file to run.
Translate THE JSP into a Java file, which is the output of all THE HTML code in the JSP through a stream, that is, the final translation into class, loaded by the virtual machine, it is essentially a servlet, it will respond, response is the JSP IN the HTML code to stream back to the browser.
So the HTML code is displayed in the JSP
2. Practical application demonstration
1, place the JSP file in the project folder of a Webapps you created earlier
2. Check the folder corresponding to the project in the Work directory and find that it is empty
3. Start the Tomcat server and access the JSP page
4. New content appears in the project folder corresponding to the Work directory
5, check out the index_jsp.java file
6, check HttpJspBase
Third, JSP built-in objects
A total of 9 such objects are predefined in JSP, respectively: Request, Response, Session, Application, Out, Pagecontext, config, Page, exception
Jar package to import
1. Detailed explanation of built-in objects
1.1 the request object
The request object is javax.mail. Servlet. It kind of object.
This object represents the request information of the client and is used to receive data sent to the server over HTTP. (including header information, system information, request mode and request parameters, etc.)
The scope of the Request object is a single request.
1.2 the response object
Response represents a response to the client, which is mainly to send the object processed by the JSP container back to the client.
The Response object also has scope and is only valid within the JSP page. Owning type :HttpServletResponse
1.3 the session object
Session objects are automatically created by the server to be associated with user requests.
The server generates a session object for each user to store the user information and track the operation status of the user.
The Session object internally uses the Map class to store data. Therefore, data is saved in the format of Key/value.
The value of the session object can be used for complex object types, not just strings.
1.4 the application object
The application object stores information in the server until the server is shut down, otherwise the information stored in the application object is valid throughout the application.
The Application object has a longer lifetime than the Session object and is similar to the system’s “global variable” ServletContext
The difference between:
- Request: indicates a single request
- Session: during the browser access (during the session)
- Application: Data can be stored across browsers during server startup
1.5 the out object
The OUT object is used to output information within the Web browser and to manage the output buffer on the application server.
When using the OUT object to output data, you can operate on the data buffer to clear the residual data in the buffer in time and make room for other output.
After the data output is completed, the output stream should be closed in time.
Out. print("<script type='text/javascript'>alert(' username does not exist '); location.href='index.jsp'</script>");Copy the code
1.6 the pageContext object
The function of the pageContext object is to get any range of parameters, through which you can get JSP page out, Request, Reponse, Session, application, and other objects.
The pageContext object is created and initialized by the container and can be used directly in JSP pages
1.7 the config object
The main purpose of the config object is to get configuration information for the server.
A Config object is obtained through the getServletConfig() method of the pageConext object.
When a Servlet is initialized, the container passes some information to the Servlet through a Config object.
The developer can provide initialization parameters for Servlet programs and JSP pages in the application environment in the web.xml file.
String url= config.getServletContext().getrealPath ("/image"); <h1>url=<%=url %></h1>Copy the code
1.8 page object
The Page object represents the JSP itself and is legal only within the JSP page.
The Page implied object essentially contains variables referenced by the current Servlet interface, similar to the This pointer in Java programming.
1.9 the exception object
The Exception object displays exception information and can only be used in pages containing isErrorPage=”true”. Using this object in a normal JSP page will not compile a JSP file.
Excepation objects, like all Java objects, have a system-provided inheritance structure.
The Exception object defines almost all exceptions.
In Java programs, you can use the try/catch keyword to handle exceptions; If an exception occurs in a JSP page that is not caught, an exception object is generated and passed to the error page set in the Page directive, where the corresponding Exception object is processed.
(1) Add the errorPage attribute to the page where errors may occur:
<%@ page pageEncoding="utf-8" errorPage="error.jsp" contentType="text/html; charset=UTF-8" language="java" %>Copy the code
(2) Set isErrorPage=”true” in error. JSP.
<%@ page language="java" isErrorPage="true" import="java.util.*" pageEncoding="UTF-8"%>
Copy the code
The code for
1, test.jsp (server internal error)
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%=6/0%> </body> </html>Copy the code
2. In order to prevent users from seeing such a messy interface, you can set the errorPage attribute to indicate that the user will jump to a new page if an error occurs
<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="test2.jsp" %> <html> <head> <title>Title</title> </head> <body> <%=6/0%> </body> </html>Copy the code
Test2. JSP output error message
<%@ page contentType="text/html; charset=UTF-8" language="java" isErrorPage="true" %> <html> <head> <title>Title</title> </head> <body> exception=<%=exception.getMessage() %> </body> </html>Copy the code
2. JSP scope
test.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% request.setAttribute("a1","aaa"); %> request=<%=request.getAttribute("a1")%><br> <% session.setAttribute("b1","bbb"); %> session=<%= session.getAttribute("b1")%><br> <% application.setAttribute("c1","ccc"); %> application=<%= application.getAttribute("c1")%><br> <% pageContext.setAttribute("d1","ddd"); %> pageContext=<%=pageContext.getAttribute("d1")%><br> <a href="test2.jsp">test2.jsp</a><br> </body> </html>Copy the code
test2.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" isErrorPage="true" %> <html> <head> <title>Title</title> </head> <body> <h1>test2.jsp</h1> request=<%=request.getAttribute("a1")%><br> session=<%= session.getAttribute("b1")%><br> application=<%= application.getAttribute("c1")%><br> pageContext=<%=pageContext.getAttribute("d1")%><br> </body> </html>Copy the code
Four, JSP instructions
JSP directives are used to set the attributes related to the entire JSP page, such as how the page is encoded and the scripting language.
The syntax is as follows:
<%@ directive attribute="value" %> Directive: directive name Attribute name value: attribute valueCopy the code
1, page instruction
Page directives provide the container with instructions for the current Page. A JSP Page can contain multiple Page directives
Syntax for the Page directive:
<%@ page attribute="value" %>
Copy the code
2. Include directives
JSPS can include other files through include directives.
The included files can be JSP files, HTML files, or text files. The included file is compiled and executed as if it were part of the JSP file.
The syntax format of the Include directive is as follows:
<%@ include file=" file relative url "%>Copy the code
The file name in the include directive is actually a relative URL address.
If you do not associate a path with the file, the JSP compiler defaults to looking under the current path.
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%@include file="top.jsp"%> <%@include file="middle.jsp"%> <%@include file="bottom.jsp"%> </body> </html>Copy the code
3. The Taglib directive
The JSP API allows users to customize tags, and a custom tag library is a collection of custom tags.
The Taglib directive introduces the definition of a collection of custom tags, including library paths and custom tags.
<%@ taglib uri="uri" prefix="" %>
Copy the code
The URI attribute determines the location of the tag library, and the prefix attribute specifies the (customizable) prefix of the tag library.
Common status codes
Sixth, EL expression
In practice, small scripts are not used to implement page nesting
1, What Expression Language
Originally defined in JSTL1.0
In JSP2.0, EL was separated from JSTL and placed in the JSP specification as part of the JSP2.0 specification
Using EL expressions in JSPS simplifies access to objects and variables by being EL expressions
2. EL expression syntax
${name of information to display}Copy the code
EL expression if you want to read the variable, the variable must be in scope, pageContext, request, session, and application
When the expression does not specify the scope of the variable or object, then the container will look up the variable or object from pageContext – > Request – > Session – > Application. We can get the value of the specified scope by implicit object:
- The pageScope object, used to get property values for the current page
- RequestScope object, used to get the value of the property of the requestScope
- SessionScope object, used to get sessionScope property values
- ApplicationScope object that gets the value of an application-scope property
Specify scope fetch syntax:
${requestScope.key}
Copy the code
<%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page import="java.util.HashMap" %> <%@ page import="java.util.Map" %> <%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> title </title> </head> <body> <h1>top.jsp</h1> <% / if the same key is used, Which value does the EL expression choose to display in different scopes? The pageContext. SetAttribute (" a4 ", "the pageContext content"); Request. SetAttribute (" a4 ", "the request content"); The session. The setAttribute (" a4 ", "the session content"); Application. The setAttribute (" a4 ", "application content"); %> k1=${a3.k1} session-a4=${sessionScope.a4}<br> pageContext-a4=${pageScope.a4}<br> request-a4=${requestScope.a4}<br> application-a4=${applicationScope.a4} </body> </html>Copy the code
3. Basic operators in EL
<%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page import="java.util.HashMap" %> <%@ page import="java.util.Map" %> <%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> title </title> </head> <body> <h1>top.jsp</h1> <% / The variables must be in scope: pageContext, request, session, application int a = 10; pageContext.setAttribute("a1",a); List list=new ArrayList(); list.add("abc"); pageContext.setAttribute("a2",list); Map map=new HashMap(); map.put("k1","key"); pageContext.setAttribute("a3",map); // Which value will the el expression display if the key is the same and the scope is different? The pageContext. SetAttribute (" a4 ", "the pageContext content"); Request. SetAttribute (" a4 ", "the request content"); The session. The setAttribute (" a4 ", "the session content"); Application. The setAttribute (" a4 ", "application content"); %> ${20+30}<br> ${20>30}<br> ${20<30}<br> ${20>30?" aaa":"bbb"}<br> a=${a1}<br> abc=${a2[0]}<br> k1=${a3.k1} session-a4=${sessionScope.a4}<br> pageContext-a4=${pageScope.a4}<br> request-a4=${requestScope.a4}<br> application-a4=${applicationScope.a4} </body> </html>Copy the code
Seven, JSTL
1. What is JSTL
JSP standard Tag Library (JSTL) is a SET of JSP tags, which encapsulates the common core functions of JSP applications.
JSTL supports generic, structured tasks such as iteration, conditional judgment, XML document manipulation, internationalization tags, and SQL tags. In addition, it provides a framework for using custom tags that integrate with JSTL.
According to the functionality provided by JSTL tags, they can be divided into five categories: core tags, formatted tags, SQL tags, XML tags, and JSTL functions
2. JSTL functions and syntax format
What it does: Simplifies JSP page coding
Usage:
- Jakarta-taglibs-standard-1.1.2. Zip: jakarta-taglibs-standard-1.1.2; zip: jakarta-taglibs-standard-1.1.2; Copy the standard. Jar and jstl.jar files to/web-INF /lib/.
- <% @taglib prefix= “page name” URI = “functional scope path” %>
3. Core tags
The core tag is the most commonly used JSTL tag.
3.1 grammar
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Copy the code
3.2 classification
- Expressions operate on out, set, remove, and catch
- Flow control if, choose, WHEN, and otherwise
- Iterate forEach and forTokens
- URL operations import, PARam, URL, and Redirect
- The Set tag
3.3 < c: set >
It is used primarily to store variables in a JSP scope or a JavaBean property or Map object
3.4 < c: out >
Mainly used to display the content of data
3.5 < c: remove >
Mainly responsible for removing variables
3.6 < c: if > *
If true, output the contents of the label body
3.7 < c: forEach > *
Loop control, which allows you to browse through the members of an array or Collection
4. Format labels
4.1 FMT: formatDate *
Function: Formats a date type into a string in the specified schema
attribute
- Value: data to be formatted
- Pattern: Format pattern, same as parameter Settings of SimpleDateFormat
- Var: variable to store in the formatted string. If var is not specified, the formatted result is displayed on the page
- Scope: domain property space for storing variables. Default page
- Type: the value can be date, time, or both, indicating whether the given value contains the date, time, or both. The default value is date
4.2 FMT: parseDate
Function: Converts a specified string to a date type
<fmt:parseDate value="${now }" pattern="yyyy-MM-dd" var="today"/>
Copy the code
- Value Indicates the time obtained by the server
- Pattern: Conversion format
- Var: variable displayed on the page
4.3 FMT: formatNumber
Formats a number in the specified format
attribute
- MaxIntegerDigits: The largest number of digits in the integer part
- MinIntegerDigits: The smallest number of digits in the integer part
- MaxFrctionDigits: The largest number of digits in the decimal part
- MinFrctionDigits: The smallest number of digits in the decimal part
- Var: a variable that stores formatted results
- Scope: Scope of the var attribute
- IntegerOnly: Whether to parse only integer true or floating point false
5. Code examples
<%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page import="java.util.Date" %> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>Title</title> </head> <body> <h1>jstl</h1> <c:set Var ="uname" scope="session" ></c:set> <c:out value="${sessionscope. uname}"></c:out> <c:if Test = "${uname = = '* *'}" > this is zhang < / c: if > < c: choose > < c: when test = "${uname = = '* *'}" > * * < / c: when > < c: otherwise > not zhang SAN </c:otherwise> </c:choose> <% List list=new ArrayList(); list.add("abc"); list.add("bcd"); List. The add (" l li si "); pageContext.setAttribute("ulist",list); % > < h4 > cycle data < / h4 > < c: forEach items = "${ulist}" var = "user" varStatus = "sta" > <! -- count starts at 1, The index starts at 0 - > ${sta. Count} - ${sta. Index} - > ${user} < br > < / c: forEach > < % pageContext. The setAttribute (" mytime ", new Date ()); %> date=<fmt:formatDate value="${mytime}" pattern="yyyy-MM-dd"></fmt:formatDate> </body> </html>Copy the code
The chapter summary is here (the better we understand you guys, the better we understand you guys).
Students who are interested in learning Java are welcome to join QQ Learning exchange group: 1126298731
Have a question welcome to ask, everyone together in learning Java on the road to play strange upgrade! (O ゜ – ゜▽゜)