๐ป๐‘ ๐‘–๐‘›๐‘ฆ๐‘Ž๐‘ข

๐ป๐‘ ๐‘–๐‘›๐‘ฆ๐‘Ž๐‘ข

ๆœ‰่ถฃๆœ‰็›ผ๏ผŒๆ— ็พๆ— ้šพ.
github
telegram
instagram

JSP Basics

Introduction to JSP#

JSP (Java Server Pages) is fundamentally a simplified Servlet design that allows the use of HTML tags in Java. JSP is a dynamic web technology standard and also a standard of JavaEE. Like Servlets, JSP is executed on the server side. JSP was developed after the Servlet technology to make it easier for developers to write HTML tags; in fact, JSP is essentially a Servlet.

However, people usually use Servlets as control components in web applications, responsible only for responding to requests and generating data, which is then forwarded to JSP using forwarding techniques, while JSP technology is used as a data display template. This makes the program structure clearer and enhances readability and maintainability.

Common Dynamic Website Development Technologies#

JSP: Java platform, high security, suitable for developing large, enterprise-level, distributed web applications, such as Hadoop, online banking, 12306, etc.

ASP.NET: .Net platform, simple and easy to learn. However, it has poor security and cross-platform capabilities.

PHP: Simple, efficient, low-cost development cycle, especially suitable for web application development for small and medium-sized enterprises. (LAMP: Linux + Apache + MySQL + PHP)

Composition of JSP Page Elements#

JSP Directives#

JSP directives are designed for the JSP engine; they do not directly produce any visible output but simply tell the engine how to process the rest of the JSP page. In the JSP 2.0 specification, three directives are defined, with the basic syntax format being <%@ directive attributeName="value" %>. If a directive has multiple attributes, these attributes can be written in one directive or separated.

  1. page directive: The page directive is used to define various attributes of the JSP page. Regardless of where the directive appears in the page, it applies to the entire JSP page. To maintain program readability and adhere to good programming practices, the page directive is usually placed at the beginning of the entire JSP page, and a page can have multiple page directives.

    <%@ page language="java" contentType="text/html,ISO-8859-1" 
    import="java.util.*,java.sql.*,java.io.*" session="true|false" 
    buffer="none|8kb|sizekb" autoFlush="true|false" info="a string content" 
    errorPage="relative_url" isErrorpage="true|false"%>
    
  • language specifies the scripting language used in the JSP page, with the default value being java.
  • contentType is used to specify the file type and encoding method of the JSP page, with the default value being "text/html,ISO-8859-1".
  • import allows referencing class files used in the scripting language, with multiple classes or packages separated by commas. The JSP engine automatically imports java.lang.; java.servlet.; javax.servlet.jsp.; javax.servlet.http..
  • pageEncoding specifies the encoding method of the JSP page, with the default value being "ISO-8859-1".
  • session indicates whether to create a session object, with the default being true.
  • buffer specifies whether the out object creates a buffer and specifies the buffer size. The default is 8kb; none means no buffer is created.
  • autoFlush indicates whether the buffer automatically flushes, with the default being true. If false, not manually flushing when the buffer is full will cause an exception.
  • info defines a string constant that can be printed using the getServletInfo method.
  • errorPage specifies the error handling page. It can also be set in web.xml for the entire web application, where the sub-elements specify the fully qualified name of the exception class, and the element specifies the path of the error handling page starting with "/". If the errorPage attribute is set for a certain JSP page, then the error handling specified in the web.xml file will not apply to that page.
  1. include directive: Used to include other JSP pages. If the include directive includes other JSP pages, the JSP engine will translate these two JSPs into one Servlet, so the include directive is often referred to as static inclusion.

    <%@ include file="absolute URL or relative URL of the included component" %>
    

The included file must follow JSP syntax. The included file can have any extension; even if its extension is html, the JSP engine will process its content as it does with JSP pages. For clarity, the JSP specification recommends using .jspf (JSP fragments) as the extension for static inclusion files. Since using include indicates that two JSP pages will be involved and will be translated into one Servlet, the directives of these two JSP pages must not conflict (except for pageEncoding and import).

  • taglib directive: Used to define custom tags using tag libraries and enable customized behavior in the JSP page.

Expressions#

Expressions executed in the JSP page are written as <%= expression %>, and note that expressions do not end with a semicolon. For example, the current time: <%= new java.util.Date() %>

Scriptlets#

To insert multiple lines of Java code in the JSP page, use <% Java code %>. The JSP engine will place the Java code in the JSP scriptlet directly into the _jspService method of the Servlet, so the Java code within <% %> must strictly adhere to Java syntax.

Declarations#

To define variables or methods in the JSP page, use <%! Java code %>. The Java code in the declaration is translated outside the _jspService method, belonging to the class, so member variables can be declared and initialized, and methods can be declared or defined. Static code blocks can also be declared. The scope of JSP implicit objects is limited to the _jspService method of the Servlet, so implicit objects cannot be used in JSP declarations.

<%!
static {
  System.out.println("loading Servlet!");
}
private int globalVar = 0;
public void jspInit() {
  System.out.println("initializing jsp!");
}
%>
<%!
public void jspDestroy() {
  System.out.println("destroying jsp!");
}
%>

Comments (3 types)#

  1. HTML comments
  2. JSP comments: <%-- JSP comment, not visible to the client --%>
  3. JSP script comments: Java comments // single line, /* multi-line */

Static Content#

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<html>
<head>
  <title>index.jsp page</title>
</head>
<body>
  <h1>Hello everyone</h1><hr>
  <!-- I am an HTML comment, visible to the client -->
  <%-- I am a JSP comment, not visible to the client --%>
    <%!
  String s = "Zhang San";
// Declared a string variable
int add(int x, int y) {
  // Declared a function that returns an integer, implementing the sum of two integers.
  return x + y;
}
%>
  <%
    // single line comment
/* multi-line comment */
out.println("Hello everyone");
%>
  <br>
  Hello, <%= s %><br>
  x + y = <%= add(10, 5) %><br>
</body>
</html>

JSP Runtime Principles and Lifecycle#

When a user first requests Tomcat, it compiles the JSP file into a Servlet Java file, compiles the Java file into a class file, loads it into memory, and generates the file in the corresponding project folder in Tomcat's work directory. If the JSP page is modified, the JSP engine will recompile it and load it into memory for user requests. Note that when a user first requests a JSP page, the method executed first is the constructor.

The _jspService() method is called to handle client requests. For each request, the JSP engine creates a thread to handle that request. If multiple clients request the same JSP file simultaneously, the JSP engine will create multiple threads. Each client request corresponds to one thread. Executing in a multithreaded manner can greatly reduce the demand on system resources, improving system concurrency and response time. However, attention must also be paid to the synchronization issues brought about by multithreading. Since the Servlet always resides in memory, the response is very fast.

When the JSP engine calls the corresponding jspServlet, it passes or creates 9 objects related to web development for use by the jspServlet. The designers of JSP technology defined 9 corresponding variables to facilitate developers in obtaining references to these web objects while writing JSP pages.

9 Built-in Objects of JSP#

Introduction to Built-in Objects#

JSP built-in objects are a set of objects created by the web container that can be used without the new keyword.

Four Scope Ranges#

  1. application_SCOPE: Applies to the entire web application, shared among multiple users.
  2. session_SCOPE: Applies to the entire web application, shared among a single user.
  3. request_SCOPE: Applies to requests, shared among forwarded requests.
  4. page_SCOPE: Applies to the current page, visible only on the current page.

out Object#

Buffer: A buffer is a region in memory used to hold temporary data.

out Object: It is an instance of the JspWriter class, commonly used to send text to the client. It is returned by calling the getOut method of the pageContext object, and its function and usage are very similar to the PrintWriter object returned by ServletResponse.getWriter. The type of the out implicit object in the JSP page is JspWriter, which is equivalent to a PrintWriter with caching functionality. The buffer size can be adjusted by setting the buffer attribute of the page directive, or even turning off caching. The buffer will only be written to the buffer provided by the Servlet engine when the following conditions are met: the buffer attribute of the page directive has disabled the caching function of the out object; the buffer of the out object is full; the entire JSP page has ended.

<%
  out.println("aaa");
  response.getWriter().write("bbb");
%>
"bbb will be output before aaa"

Common methods:

  • void println(); prints a string to the client.
  • void clear(); clears the contents of the buffer; will throw an exception if called after flush.
  • void clearBuffer(); clears the contents of the buffer; will not throw an exception if called after flush.
  • void flush(); outputs the contents of the buffer to the client.
  • int getBufferSize(); returns the size of the buffer in bytes; if no buffer is set, it is 0.
  • int getRemaining(); returns how much usable space is left in the buffer.
  • boolean isAutoFlush(); returns whether the buffer automatically clears or throws an exception when full.
  • void close(); closes the output stream.

request/response Objects#

Two Submission Methods for Forms

  1. Get: Submits data in plain text through the URL, which can be seen in the URL. The submitted data cannot exceed 2KB. It has low security but higher efficiency than the post method. It is suitable for submitting small amounts of data with high security, such as search and query functions.

  2. Post: Encapsulates the user-submitted information within the HTML header. It is suitable for submitting large amounts of data and high-security user information, such as registration, modification, uploading, etc.

request Object#

The client's request information is encapsulated in the request object, which allows understanding the client's needs and responding accordingly. It is an instance of the HttpServletRequest class. The request object has a request scope, meaning it remains valid until the client's request is completed.

Common Methods of the request Object

  1. String getParameter(); returns the parameter value for the specified parameter.
  2. String[] getParameterValues(); returns all values for the specified parameter.
  3. void setAttribute(); stores attributes in this request.
  4. Object getAttribute(); returns the value of the specified attribute.
  5. String getContentType(); gets the MIME type of the request body.
  6. String getProtocol(); returns the protocol and version used for the request.
  7. String getServerName(); returns the hostname of the server that received the request.
  8. int getServerPort(); returns the port number on which the server received this request.
  9. String getCharacterEncoding(); returns the character encoding method.
  10. void setContentEncoding(); sets the character encoding method for the request.
  11. int getContentLength(); returns the length of the request body (in bytes).
  12. String getRemoteAddr(); returns the IP address of the client that sent this request.
  13. String getRealPath(String path); returns the real path of a virtual path or the absolute path of a relative path.
  14. String getContextPath(); returns the context path, which is the root directory of the project.
    For Chinese garbled issues: request.setCharacterEncoding("UTF-8");
    For URL Chinese garbled issues: Add attributes in Tomcat's /conf/server.xml.

response Object#

The response object contains information related to responding to client requests, but it is rarely used directly in JSP. It is an instance of the HttpServletResponse class. The response object has a page scope, meaning that the response object for a page is only valid for that access; other response objects are invalid for the current page.

Common Methods of the response Object

  1. String getCharacterEncoding(); returns the character encoding used for the response.
  2. void setContentType(); sets the MIME type of the response, usually "text/html, charset=UTF-8".
  3. PrintWriter getWriter(); returns an object that can output characters to the client ("Note the difference: PrintWriter outputs always precede the built-in out object, or manually flush in out").
  4. sendRedirect(location); redirects the client's request.

Request Redirection: It is a client behavior, response.sendRedirect(), which essentially equates to two requests; the previous request object will not be saved, and the URL in the address bar will change.

Request Forwarding: It is a server behavior, request.getRequestDispatcher().forward(); it is a single request, and the request object will be preserved after forwarding, while the URL in the address bar will not change.

session Object#

A session represents a single session between the client and the server. In the web context, a session refers to the time from when a user enters a website until the browser is closed, which is the time the user spends browsing the website.

The server's memory stores different sessions for different users.

The session object is a built-in object in JSP.

The session object is automatically created when the first JSP page is loaded, managing the session duration.

From the moment a client opens a browser and connects to the server until the client closes the browser and leaves the server is referred to as a session.

When a client accesses a server, they may switch between several pages on the server, and the server needs a way to recognize this as a single client, which requires the session object.

The session object is an instance of the HttpSession class.

Common Methods of the session Object

  1. long getCreationTime(); returns the session creation time.
  2. String getId(); returns the unique ID assigned to the session by the JSP engine upon creation.
  3. Object setAttribute(); binds an object to this session using a specified name.
  4. Object getAttribute(); returns the object bound to this session with the specified name; returns null if not found.
  5. String[] getValueNames(); returns an array containing all available attributes in this session.
  6. int getMaxInactiveInterval(); returns the time interval (in seconds) after which this session will be canceled between two requests.
  7. void setMaxInactiveInterval(); sets the session's lifetime.

Session Lifecycle

  1. Creation: When a client first accesses a JSP or Servlet, the server creates a SessionId for the current session. Each time the client sends a request to the server, this SessionId is included, and the server validates it.
  2. Activity: Pages opened through hyperlinks during a session belong to the same session. As long as the current session page is not completely closed, reopening a new browser window to access the same project resources will still belong to the same session. Unless all pages of the current session are closed, accessing a JSP or Servlet again will create a new session (but the original session still exists, and the SessionId remains on the server, though it will no longer be carried by the client to validate with the server until the session times out).
  3. Destruction: There are three ways to destroy a session:
  • Calling the session.invalidate() method.
  • Session expiration (timeout), which can be configured in web.xml for session timeout, with the unit being minutes.
  • Server restart.

application Object#

The application object implements data sharing among users and can store global variables.
The application starts when the server starts and terminates when the server shuts down.
Operations on the same attribute of the application object can be performed between different users or connections.
Any operation on the application object's attributes will affect other users' access to it.
The lifecycle of the application object is determined by the server's startup and shutdown.
The application object is an instance of the ServletContext class.

Common Methods of the application Object

  1. void setAttribute(); binds an object to this session using a specified name.
  2. Object getAttribute(); returns the object bound to this session with the specified name; returns null if not found.
  3. Enumeration getAttributeNames(); returns an enumeration of all available attribute names.
  4. String getServerInfo(); returns the name and version number of the JSP (Servlet) engine.

page Object#

The page object refers to the current JSP page itself, similar to the this pointer in a class; it is an instance of the java.lang.Object class. The common method is the member method of the Object class.

pageContext Object#

The pageContext object is the most important object in JSP technology; it represents the runtime environment of the JSP page. This object not only encapsulates references to the other 8 implicit objects but is also a scope object that can be used to store data. Additionally, this object encapsulates some common operations frequently involved in web development, such as including and forwarding other resources, retrieving attributes from other scope objects, etc.

The pageContext object provides access to all objects and namespaces within the JSP page. This object can access the session of the current page and retrieve attribute values from the application of the current page. This object serves as a comprehensive collection of all functionalities within the page. The class name of this object is also called pageContext.

Common Methods of the pageContext Object

  1. JspWriter getOut(); returns the out object used for the current client response.
  2. HttpSession getSession(); returns the session object for the current page.
  3. Object getPage(); returns the page object for the current page.
  4. ServletRequest getRequest(); returns the request object for the current page.
  5. ServletResponse getResponse(); returns the response object for the current page.
  6. void setAttribute(); sets attributes and their values.
  7. Object getAttribute(); retrieves the value of an attribute within a specified scope.
  8. int getAttributeScope(); returns the scope of a specified attribute.
  9. void forward(); jumps to another page without changing the address bar.
  10. void include(); includes another page.
  11. PageContext.APPLICATION_SCOPE represents constants for various scopes.
  12. PageContext.SESSION_SCOPE
  13. PageContext.REQUEST_SCOPE
  14. PageContext.PAGE_SCOPE
  15. findAttribute(); searches for attributes within various scopes.

Config Object#

The Config object is used by the JSP engine to pass information to a Servlet during initialization. This information includes parameters needed during Servlet initialization (composed of property names and values) and server-related information (by passing a ServletContext object).

Common Methods of the Config Object

  1. ServletContext getServletContext(); returns the ServletContext object containing server information.
  2. String getInitParameter(); returns the value of the initialization parameter.
  3. Enumeration getInitParameterNames(); returns an enumeration of all parameters required for Servlet initialization.

Exception Object#

The Exception object is an exception object that is generated when an error occurs during the execution of a page. If a JSP page wants to use this object, it must set isErrorPage to true; otherwise, it cannot be compiled. It is essentially an object of java.lang.Throwable. To handle exceptions in a page, specify the error handling page with <% page errorPage="exception.jsp" %>.

Common Methods of the Exception Object

  1. String getMessage(); returns a message describing the exception.
  2. String toString(); returns a brief description message about the exception.
  3. void printStackTrace(); displays the exception and its stack trace.
  4. Throwable fillInStackTrace(); rewrites the execution stack trace of the exception.

JSP Action Tags#

  1. JSP action elements: Action elements provide information during the request processing phase. Action elements follow the syntax of XML elements, with a start tag containing the element name, optional attributes, optional content, and an end tag that matches the start tag.
    JSP tags are also referred to as JSP Action elements, which are used to provide business logic functionality in JSP pages, avoiding direct Java code in JSP pages that makes them difficult to maintain.

  2. JSP action elements include five major categories:

    • Related to storing JavaBeans: jsp, jsp, jsp.
    • Six basic action elements present since JSP 1.2: jsp, jsp, jsp, jsp, jsp, jsp.
    • Six action elements newly added in JSP 2.0, mainly related to JSP Document: jsp, jsp, jsp, jsp, jsp, jsp.
    • Three actions newly added in JSP 2.0, mainly for dynamically generating XML element tag values: jsp, jsp, jsp.
    • Two actions newly added in JSP 2.0, only used in Tag Files: jsp, jsp.
  3. Common JSP Tags:

    • include: This tag is used to insert the output content of another resource into the output content of the current JSP page. This method of inclusion during JSP page execution is called dynamic inclusion. <jsp:include page="relativeURL | <%=expression%>" flush="true|false" />. The flush attribute specifies whether to flush the already output content of the current JSP page to the client before inserting the output content of other resources.

    • jsp compared to include directive: The jsp tag is dynamic inclusion, where the two JSP pages involved will be translated into two servlets, and their content will be merged during execution. The include directive is static inclusion, where the two JSP pages involved will be translated into one servlet, and their content will be merged at the source file level. Regardless of whether it is the jsp tag or the include directive, both will merge the content of the two JSP pages for output, so these two pages should not contain duplicate global HTML structure tags; otherwise, the content output to the client will be a disordered HTML document. However, the include directive is generally more efficient than the jsp tag. The following table provides a more intuitive comparison of the two.

      includejsp
      Syntax Format<%@ include file="..." %><jsp page="..." />
      Time of EffectDuring page translationDuring request
      Included ContentActual content of the fileOutput of the page
      Translated to ServletMain page and included page translated to one ServletMain page and included page translated to independent Servlets
      Compilation TimeSlower - resource must be resolvedFaster
      Execution TimeSlightly fasterSlower - resource must be resolved each time
    • jsp: This tag is used to forward the request to another resource. <jsp:forward page="relativeURL | <%=expression%>" />. It is equivalent to request.getRequestDispatcher("/url").forward(request, response), which performs an internal server jump operation.

    • jsp: When using jsp and jsp tags to include or forward requests to other resources, the jsp tag can be used to pass parameters to that resource.

<jsp:include page="relativeURL | <%=expression%>">
<jsp:param name="parameterName" value="parameterValue | <%= expression %>"/>
</jsp:include>
Multiple <jsp:param> tags can be used to pass multiple parameters.
  1. Mapping JSP

Mapping JSP refers to mapping a JSP to any other form of URL, configured in the web.xml file.

<servlet>
  <servlet-name>SimpleJspServlet</servlet-name>
  <jsp-file>/jsp/simple.jsp</jsp-file>
  <load-on-startup>1</load-on-startup>
</servlet>
โ€ฆโ€ฆ
<servlet-mapping>
  <servlet-name>SimpleJspServlet</servlet-name>
  <url-pattern>/xxx/yyy.html</url-pattern>
</servlet-mapping>

JavaBeans#

  1. Introduction to JavaBeans

    JavaBeans are Java classes that comply with certain specific standards. The benefits of using JavaBeans include reducing code duplication, minimizing code redundancy, clearly distinguishing functionalities, and improving code maintainability.

  2. Design Principles of JavaBeans

    Must be a public class;
    Must contain a public no-argument constructor;
    All properties must be private;
    Use getter and setter accessors to encapsulate property access.

    public class Book {
     // A compliant JavaBean class
     private String bookName;
     private String author;
     private double price;
     public Book() {
     }
     public String getBookName() {
       return bookName;
     }
     public void setBookName(String bookName) {
       this.bookName = bookName;
     }
     public String getAuthor() {
       return author;
     }
     public void setAuthor(String author) {
       this.author = author;
     }
     public double getPrice() {
       return price;
     }
     public void setPrice(double price) {
       this.price = price;
     }
    }
    
  3. How to Use JavaBeans in JSP

    The first method: create an instance of the JavaBean like a regular Java class.
    The second method: typically use JSP action tags to use JavaBeans in the JSP page.

  4. Scope

    Purpose: Instantiate or use JavaBeans within a specified scope in the JSP page.

    <jsp:useBean id="identifier" class="java.class.name" scope="scope"/> 
    <!-- The default scope is page. -->
    
  5. Property

Purpose: Assign values to the properties of an already instantiated JavaBean object, with four forms:

<jsp:setProperty name="JavaBeanInstanceName" property="*"/> (associated with the form)
<jsp:setProperty name="JavaBeanInstanceName" property="JavaBeanPropertyName"/> (associated with the form)
<jsp:setProperty name="JavaBeanInstanceName" property="JavaBeanPropertyName" value="BeanValue"/> (manually set)
<jsp:setProperty name="JavaBeanInstanceName" property="propertyName" param="parameter name in request object"/> (associated with request parameters) passed through URL.
  1. Name

Purpose: Retrieve the value of a specified property of the JavaBean object.

<jsp:getProperty name="JavaBeanInstanceName" property="propertyName"/>
  1. Four Scope Ranges of JavaBeans

    The scope attribute of useBeans can be used to specify the scope of the JavaBean.
    page: valid only on the current page
    request: can be obtained through request.getAttribute method
    session: can be obtained through session.getAttribute method
    application: can be obtained through application.getAttribute method.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.