Combing Servlet and JSP (2), servletjsp

Source: Internet
Author: User

Combing Servlet and JSP (2), servletjsp

A JSP page is essentially a Servlet,Run the JSP page in the JSP ContainerA Servlet container is also a JSP Container.

When a JSP page is requested for the first time, the Servlet/JSP Container mainly performs the following two tasks:

① Convert a JSP page to a JSP page implementation class. This implementation class is a Java class that implements the javax. servlet. jsp. JspPage interface or the sub-interface javax. servlet. jsp. HttpJspPage. The class name of this implementation class is generated by the Servlet/JSP Container. If a conversion error occurs, the error message is sent to the client.

② If the conversion is successful, the Servlet/JSP Container then compiles the Servlet class, loads and instantiates the class, and performs lifecycle operations like other normal servlets.

Use a picture to describe the above operations, as shown below:

 

 

For subsequent requests from the same JSP page, the Servlet/JSP Container first checks whether the JSP page has been modified. If yes, the JSP page will be re-translated, compiled, and executed. If not, execute the JSP Servlet that is already in the memory. In this way, the actual cost for the first call of a JSP page is much higher than that for later calls because it involves translation and compilation. To solve this problem, perform the following actions:

① Configure the application so that all JSP pages are called when the application starts, rather than called at the first request.

② Pre-compile the JSP page and deploy it as a Servlet.

  JSP APIs include four packages.:

Package

Description

Javax. servlet. jsp

Includes the core classes and interfaces used for Servlet/JSP containers to translate JSP pages into servlets.

Javax. servlet. jsp. tagext

This includes the types used to develop custom tags.

Javax. el

Provides APIs for the Unified Expression Language.

Javax. servlet. jsp. el

Provides a set of classes that must be supported by Servlet/JSP containers to use expression languages on JSP pages.

JSP supports two differentComment format:

Annotation type

Format

Features

JSP comments

<% --...... -- %>

JSP comments are neither sent to the browser nor nested.

HTML/XHTML comments

<! --...... -->

An HTML/XHTML comment is not processed by the container and is sent to the browser as it is. One of the purposes of HTML/XHTML staple food is to determine the JSP page itself.

  JSP nine implicit (built-in) Objects:

Object

Type

Description

Request

Javax. servlet. http. HttpServletRequest

Whenever a client requests a JSP page, the JSP Engine creates a new reuqest object to represent this request. The request object provides a series of methods to obtain HTTP header information, cookies, and HTTP methods.

Response

Javax. servlet. http. HtpServletResponse

When the server creates a request object, it will also create a response object to respond to this client. The response object also defines the interface for processing the HTTP header module. With this object, developers can add new cookies, timestamps, HTTP status codes, and so on.

Out

Javax. servlet. jsp. JspWriter

The out object is used to write content to the response object.

Session

Javax. servlet. http. HttpSession

The session object is used to track sessions between client requests.

Application

Javax. servlet. ServletContext

The application object represents the JSP page throughout the lifecycle of the JSP page. This object is created during JSP page initialization and removed as jspDestory () is called. By adding properties to the application, all JSP files that constitute the web application can access these properties.

Config

Javax. servelt. ServletConfig

The config object allows developers to access Servlet or JSP Engine initialization parameters, such as file paths.

PageContext

Javax. servlet. jsp. PageContext

The pageContext object is mainly used to access page information and filter most implementation details. This object cannot be exported except the attributes of pageContext, page, and exception objects. Other built-in attributes of the object can be exported. The object contains the instruction information sent to the JSP page and defines some fields.

Page

Javax. servlet. jsp. HttpJspPage

A page object is a reference of a page instance and can be seen as a representative of the entire JSP page (synonymous with this object)

Exception

Java. lang. Throwable

The exception object encapsulates the exception information thrown from the previous page and is usually used to generate an appropriate response to the error condition.

  Command

Commands are the first type of JSP syntax elements. They indicate how the JSP converter translates JSP pages into servlets.

  Page command

  You can use the page command to control how the JSP converter converts some aspects of the current JSP page.

The syntax of the page command is as follows:

<% @ Page attribute1 = "value1" attribute2 = "value2"... %>

The following is a list of page Directive attributes:

Attribute

Description

Import

Define one or more java types to be imported and used on this page.

Session

The default value is True, and session management is added to this page. If the value is false, the opposite is True.

Buffer

The buffer size of the implicit object out is defined in KB. It must end with a suffix of KB. The default value is 8 KB or greater. This value can be none, which means no buffer is available and all data is directly written to PrintWriter.

AutoFlush

The default value is True. If the value is True, the output stream is automatically written when the output buffer is full. If the value is False, the output stream is written only when the flush method of the implicit object is called. Therefore, if the buffer overflows, an exception is thrown.

IsThreadSafe

Defines the thread security level of the page.

Info

Returns the result of calling the getServletInfo method of the Servlet class generated by the container.

ErrorPage

Defines the page used to handle errors when an error occurs.

IsErrorPage

This page is an error handling page.

ContentType

Defines the content type of the implicit response object on this page. The default value is text/html.

PageEncoding

Define the character encoding of this page.

IsELIgnored

Configure whether to ignore EL expressions.

Language

Define the script language type on this page.

Extends

Defines the parent class to be inherited by the JSP implementation class.

DeferredSyntaxAllowedAsLiteral

Specifies whether to parse the "# {" symbol in the string. The default value is False ." {# "Is an inspiration symbol for an expression language.

TrimDirectiveWhitespaces

Defines whether to output unnecessary spaces or empty numbers. The default value is False.

Most page commands can appear anywhere on the page, but generally the page commands are placed at the first line of code. The page command can also appear multiple times, but the command attributes that appear multiple times must have the same value. However, except for the import attribute, the results of multiple page commands containing the import attribute are accumulated.

  Include command

You can use the include command to include the content of other files to the current JSP page. A page can contain multiple include commands. If there is a scenario where the content will be used in multiple different pages or in different pages, the modular include file is very useful.

The include command syntax is as follows:

<% @ Include file = "url" %>

There are many JSP commands, but the page and include commands are the most important. Other taglib, tag, attribute, and variable commands will appear later.

Script Element

A script is a Java code block, starting with the <% symbol and ending with the %> symbol.

  

Script element type

Description

Format

Expression

Each expression is executed by the JSP Container and Output Using the print method of the implicit object out.

The expression starts with "<% =" and ends with "%>. The expression does not end with a semicolon.

Statement

You can declare the variables and methods that can be used on the JSP page. You can use the Declaration to rush to the JSP page and implement the init and destory methods of the class.

Declare to "<% !" Start and end with "%>.

Disable script elements

On the JSP page, use EL to access server objects without writing Java code.

You can define a scripting-invalid element in the deployment descriptor <jsp-property-group> to disable the script element.

<Jsp-property-group>

<Url-pattern> *. jsp </url-pattern>

<Scripting-invalid> true </scripting-invalid>

</Jsp-property-group>

  Action

Actions are the third type of syntax elements, which are converted into Java code to perform operations, such as accessing a Java object or calling a method.

Action

Description

UseBean

UseBean creates a script variable associated with the Java object.

SetProperty

The setProperty action can be used to set attributes for a Java object.

GetProperty

The getProperty action outputs an attribute of the Java object.

Include

The include action is used to dynamically introduce another resource. You can introduce another JSP page or a Servlet or a static HTML page. You can also use the include action to pass parameters.

Forward

Forward redirects the current page to another resource.

  Error Handling

JSP provides good error handling capabilities. In addition to using the try statement in Java code, you can also specify a special page. When the application page encounters an uncaptured exception, the user will see a well-designed page to explain what happened, rather than an error message that the user cannot understand. You can use the isErrorPage attribute of the page command (the attribute value must be True) to identify a JSP page as an error page.

  Expression language syntax

The EL expression starts with $ {and ends. The EL expression structure is as follows:

${expression}

It is also commonly used to connect two expressions. For a series of expressions, their values are from left to right, the calculation result type is String, and they are connected together. If the EL expression is used in the attribute value of the custom tag, the result string of the expression will be forcibly converted to the type required by the attribute:

   

 <my:tag somAttribute="${expression}"/>

The character sequence like $ {indicates that it is the beginning of an EL expression. If you only need the text $ {, you need to add an escape character before it, for example, \ $ {.

  Keywords

The following are keywords that cannot be used as identifiers: and eq gt true instanceof or ne le false empty not lt ge null div mod.

  [] And. Operators  

An EL expression can return any type of value. If the EL expression returns an object with an attribute, you can use the [] or. Operator to access this attribute. "[]" And ". "The operator is similar;" [] "is a more standard form ,". "operator is a convenient method. However, if the variable name (the following propertyName) is not a valid Java variable name, you can only use the" [] "operator. Example:

${object["propertyName"]}${object.propertyName}

 

  Value rules

  The value of the EL expression is from left to right. For an expression in the form of expr-a [expr-B], the EL expression value is as follows:

(1) Calculate expr-a first to obtain value-.

(2) If value-a is null, null is returned.

(3) Calculate expr-B to get value-B.

(4) If value-B is null, null is returned.

(5) If value-a is java. util. Map, the system checks whether value-B is a key in Map. If yes, the value-a.get (value-B) is returned, and if not, null is returned.

(6) If value-a is java. util. List, or add it as an array, perform the following processing:

A. force value-B to be int. If the force fails, an exception is thrown.

B. If the value-a.get (value-B) throws IndexOutOfBoundsException, or adds Array. get (value-a, value-B) To throw ArrayIndexOutOfBoundsException, null is returned.

C. otherwise, if value-a is a List, value-a, get (value-B) is returned. If value-a is an array, Array is returned. get (value-a, value-B ).

(7) If value-a is not a Map, List, or array, value-a must be a JavaBean. In this case, the value-B String must be forced. If value-B is a readable attribute of value-a, call the getter method of this attribute and return the value from it. If the getter method throws an exception, the expression is invalid. Otherwise, the expression is valid.

Access JavaBean

You can use the "." or "[]" operators to access bean attributes. Its structure is as follows:

${beanName["propertyName"]}${beanName.propertyName}

   

  EL implicit object

  

Object

Description

PageContent

This is the javax. servlet. JSP. PageContent of the current jsp.

InitParam

This is a Map that contains all environment initialization parameters and uses the parameter name as the key.

Param

This is a Map that contains all request parameters and uses the parameter name as the key. The value of each key is the first parameter value of the specified name. Therefore, if the two request parameters have the same name, only the first one can use param to obtain the value. To access all parameter values with the same name, use params instead.

ParamValues

This is a Map that contains all request parameters and uses the parameter name as the key. The value of each key is a string array containing all the parameter values of the specified parameter name. Even if the parameter has only one value, it returns an array with one element.

Header

This is a Map containing the request title and using the title name as the key. The value of each key is the first title of the specified title name. In other words, if there are more than one title value, only the first value is returned. To obtain titles with multiple values, use the headerValues object instead.

HeaderValues

This is a Map containing the request title and using the title name as the key. The value of each key is a string array containing all the parameter values of the specified title name. Even if the title has only one value, it returns an array with one element.

Cookie

This is a Map that contains all Cookie objects in the current request object. The Cookie name is the key name, and each key is mapped to a Cookie object.

ApplicationScope

This is a Map that contains all the attributes of the ServletContext object and uses the attribute name as the key.

SessionScope

This is a Map that contains all the attributes of the HttpSession object and uses the attribute name as the key.

RequestScope

This is a Map that contains all the attributes in the current HttpServletRequest object and uses the attribute name as the key.

Pagination

This is a Map that contains all attributes within the entire page. The attribute name is the key of the Map.

 

Use other EL Operators

Arithmetic Operators: Addition (+), subtraction (-), multiplication (*), Division (/and div), remainder/modulo (% and mod ).

Logical operators: And (& and), or (| and or), non (! And not ).

   Relational operators: Equal to (= and eq), not equal (! = And ne), greater than (> and gt), greater than or equal to (> = and ge), less than (<and lt), less than or equal to (<= and le ).

Empty Operator: Empty operator is used to check whether a value is null or empty. For example:

 

${empty X}

 

If X is null, or X is a string with a length of 0, the expression returns True. If it is an empty Map, an empty array, or an empty set, True is returned. Otherwise, False is returned.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.