JSP pages and JSP nine implicit objects

Source: Internet
Author: User

? The JSP full name is Java Server Pages, which, like Servle technology, is a technology defined by sun to develop dynamic Web resources.

? The biggest feature of JSP technology is that writing JSP is like writing HTML, but it can only provide static data to the user compared to HTML, while JSP technology allows to nest Java code in the page and provide dynamic data to the user.

? JSP QuickStart: Output The current time in a JSP page.

    • ? JSP template elements
    • ? JSP expressions
    • ? JSP script Fragment
    • ? JSP annotations
    • ? JSP directives
    • ? JSP tags
    • ? JSP built-in objects
    • How to find errors in JSP pages
? The HTML content in the JSP page is called the JSP template element. The JSP template element defines the basic skeleton of a Web page, which defines the structure and appearance of the page.

? JSP script expressions (expression) are used to output program data to the client

Syntax: <%= variable or expression%>

Example: Current time: <%= new Java.util.Date ()%>

? When the JSP engine translates the script expression, it turns the program data into a string and then loses the data to the client at the appropriate location with Out.print (...).

You cannot have a semicolon (;) after a variable or expression in a JSP script expression.

? The JSP script fragment (scriptlet) is used to write multiple lines of Java code in a JSP page. Grammar:

<% Multi-line Java code%>

Note: The JSP script fragment can only appear in Java code, no other template elements, the JSP engine in the translation JSP page, the JSP script fragment will be in the Java code will be left intact in the servlet _jspservice side. The Java code in the JSP script fragment must strictly follow the Java syntax, for example, each execution statement must end with a semicolon (;). There can be multiple script fragments in a JSP page that can embed text, HTML tags, and other JSP elements between two or more script fragments.

Example:

<% int x = 10; OUT.PRINTLN (x);%>

<p> This is the JSP page text </p>

<% int y = 20; Out.println (y);%>

? The code in multiple script fragments can be accessed from one another as if all the code were placed in a pair of <%%>. such as: Out.println (x);? The Java statements in a single script fragment can be incomplete, but the result of a combination of multiple script fragments must be a complete Java statement, for example:

<%for (int i=1; i<5; i++) {%

<H1>www.it315.org</H1>

>%}

JSP declaration

? All code written in the JSP page is translated by default into the Servlet's service method, and the Java code in the JSP declaration is translated outside the _jspservice method. Grammar:

<%!

Java code

%>

? Therefore, JSP declarations can be used to define the static code blocks, member variables, and methods of the servlet program that the JSP page transforms into. Multiple static code blocks, variables, and functions can be defined in a JSP declaration or individually in multiple JSP declarations. JSP implicit objects are scoped only to the _jspservice method of the servlet, so these 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!");

? Format of JSP annotations:

<%--Annotation Information--%>

? When the JSP engine translates a JSP page into a servlet program, it ignores the content that is commented on the JSP page. ? JSP directives(Directive) is designed for the JSP engine, which does not directly produce any visible output, but simply tells the engine how to handle the rest of the JSP page. Three directives are defined in the JSP 2.0 specification: page Directive include Directive taglib directive? Basic syntax format for JSP directives:

<%@ directive Property name = "Value"%>

Example: <%@ page contenttype= "text/html;charset=gb2312"%>

? If a directive has multiple properties, these attributes can be written in one instruction or separately.

For example:

<%@ page contenttype= "text/html;charset=gb2312"%>

<%@ page import= "Java.util.Date"%>

You can also write:

<%@ page contenttype= "text/html;charset=gb2312" import= "Java.util.Date"%>

The page directive is used to define the various properties of a JSP page, regardless of where the page directive appears in the JSP page, it is the entire JSP page, in order to maintain the readability of the program and follow good programming habits, the page directive is best placed in the entire JSP page start position. The full syntax of the page directive defined in the JSP 2.0 specification:

<%@ page

[language= "Java"]

[extends= "Package.class"]

[import= "{package.class | package.*}, ..."]

[session= "true | false"]

[buffer= "none | 8kb | sizekb"]

[Autoflush= "true | false"]

[Isthreadsafe= "true | false"]

[info= "Text"]

[errorpage= "Relative_url"]

[Iserrorpage= "true | false"]

[contenttype= "MimeType [; Charset=characterset]" | "Text/html; Charset=iso-8859-1 "]

[Pageencoding= "CharacterSet | Iso-8859-1 "]

[Iselignored= "true | false"]

%>

The JSP engine automatically imports the following packages:

üjava.lang.*üjavax.servlet.*

javax.servlet.jsp.

? You can introduce multiple classes or packages in the Import property of one page directive, with each package or class separated by commas:

<%@ page import= "java.util.date,java.sql.*,java.io.*"%>

The above statement can also be rewritten to use the Import property of multiple page directives to introduce each package or class individually:

<%@ page import= "Java.util.Date"%>

<%@ page import= "java.sql.*"%>

<%@ page import= "java.io.*"%>

The setting value of the ErrorPage property must use a relative path, which, if preceded by "/", indicates relative to the current Web application's root directory (note that it is not the site root), otherwise, represents the current page. You can use <error-page in the Web. xml file The > element sets the error handling page for the entire Web application, where the <exception-type> child element specifies the fully qualified name of the exception class,<location> element specifies the path to the error-handling page starting with "/".

If you set the ErrorPage property of a JSP page, error handling set in the Web. xml file will not work on the page

? The JSP engine generates a corresponding statement that calls the Servletresponse.setcontenttype method based on the ContentType property of the page directive. The ContentType property of the page directive also has the function of explaining the character encoding of the JSP source file. use the page directive to solve JSP garbled characters? JSP program exists with the servlet program exactly the same Chinese garbled problem u output response body when the Chinese garbled problem U read the browser passed the parameter information when the Chinese garbled problem? When the JSP engine translates the JSP page into a servlet source file, it can also cause Chinese garbled problems The üjsp engine translates the JSP source files into a servlet source file that is UTF-8 encoded by default, and the JSP developer can write JSP source files with various character set encodings, so When the JSP engine translates the JSP source file into a servlet source file, a character encoding conversion is required. ü If the JSP file does not describe the character set encoding it uses, the JSP engine treats it as the default Iso8859-1 character set encoding. How to solve the Chinese garbled problem of JSP engine when translating JSP pages ü The ContentType property of the page directive explains the character set encoding of the JSP source file Üpage The Pageencoding property of the JSP source file character set encoding? include DirectivesFor the introduction of other JSP pages, if you introduce other JSP pages using the include directive, the JSP engine translates these two jsps into a servlet. So the introduction of include directives is often referred to as static ingestion. Syntax:

<%@ include file= "Relativeurl"%>

Where the file property is used to specify the path to the document being introduced. The path begins with "/" and represents the current web app.

? Details: ü The file you are introducing must follow the JSP syntax. ü The introduced file can use any extension, even if its extension is the HTML,JSP engine will handle the content of the JSP page, in order to see knowingly, the JSP specification recommends using the. JSPF (JSP fragments) as the extension of the static ingest file. ü Since the use of the include directive will involve 2 JSP pages and will translate 2 jsps into a servlet, the instructions for these 2 JSP pages do not conflict (except for pageencoding and guide packages). The taglib directive is used to import a tag library into a JSP page, speaking of custom label technology. tip:jsp operating principle and nine implicit objects? Each JSP page is accessed for the first time, and the Web container will give the request to the JSP engine (a Java program) to process. The JSP engine first translates the JSP into a _jspservlet (essentially a servlet) and then invokes it in the same way that the servlet is called. Because the JSP is translated into a servlet on its first visit, the first visit is usually slower, but the second access, If the JSP engine finds that the JSP has not changed, it will not translate, but directly call, so the execution efficiency of the program will not be affected. When the JSP engine invokes the _jspservlet of a JSP, it passes or creates 9 web-development-related objects for _jspservlet to use. JSP technology designers for developers to write JSP pages when they get references to these Web objects, deliberately defined 9 corresponding variables, developers in the JSP page through these variables can quickly get these 9 large object reference. What are these 9 objects, As well as the role of the written test often examined knowledge points.
    • ? Request
    • ? Response
    • ? Session
    • ? Application ServletContext
    • ? Config ServletConfig
    • ? Page this
    • ? Exception
    • ? Out JspWriter
    • ? pagecontext
an out implicit object is used to send text data to a clientThe.? Out object is returned by calling the Getout method of the PageContext object, and its role and usage is very similar to the PrintWriter object returned by the Servletresponse.getwriter method. The type of an out implicit object in a JSP page is jspwriter,jspwriter equivalent to a printwriter with a cache function, and the buffer property of the page directive that sets the JSP page can be resized, or even closed, by its cache. Only if the content is written to an out object and any of the following conditions are met The Out object does not call the Servletresponse.getwriter method, and the PrintWriter object returned by the method actually writes the contents of the Out object's buffer to the buffer provided by the servlet engine: Setting the Buffer property of the page directive closes the object's Cache function The buffer of the Out object is full at the end of the entire JSP page? Use both out and response.getwriter () to output data. The file download is implemented with JSP.? PageContext ObjectIs the most important object in JSP technology, which represents the running environment of JSP page, which not only encapsulates the reference to other 8 large implicit objects, but also is a domain object itself, which can be used to save the data. Also, this object encapsulates common operations often involved in web development, such as introducing and jumping other resources, retrieving properties in other domain objects, and so on. GetException method returns the exception implicit object? GetPage method returns the page implicit object? The Getrequest method returns the request implicit object? The GetResponse method returns the response implicit object? The Getservletconfig method returns the Config implicit object? Getservletcontext method Return application Implicit object? GetSession method returns the session implicit object? The Getout method returns an out implicit object? PageContext encapsulates the meaning of the other 8 large built-in objects, Thinking: If you pass a PageContext object to a plain Java object during programming, what will the Java object do? Method of  ?pagecontext object üpublic void SetAttribute (Java.lang.string name,java.lang.object value) üpublic Java.lang.object getattribute (java.lang.string name) üpublic Void removeattribute ( java.lang.string name)? The PageContext object also encapsulates methods for accessing other domains Üpublic Java.lang.object getattribute ( Java.lang.string name,int scope) üpublic void SetAttribute (Java.lang.string name, Java.lang.Object  value,int scope) üpublic Void removeattribute (java.lang.string name,int scope)? Represents constants for each domain Üpagecontext.application_scopeüpagecontext.sEssion_scopeüpagecontext.request_scopeüpagecontext.page_scope?findattribute Methods     (* Focus, find attributes in each domain) el expression? A forward method and two include methods are defined in the PageContext class to simplify and replace the Requestdispatcher.forward method and the Include method, respectively. The resource received by the method starts with "/" Represents the current web app.? JSP tagsAlso known as the JSP Action (JSP action) element, it is used to provide business logic function in JSP page, avoid writing Java code directly in JSP page, which makes JSP page difficult to maintain.?<jsp:include> tags? <jsp: forward> label?<jsp:param> tag?<jsp:include> tag is used to insert the output of another resource into the output content of the current JSP page, which is introduced in the JSP page implementation called dynamic Introduction. Grammar:

<jsp:include page= "Relativeurl | <%=expression%> "flush=" True|false "/>

The page property is used to specify the relative path to the resource being introduced, and it can also be obtained by executing an expression. The Flush property specifies whether the output of the current JSP page is flushed to the client first when the output of the other resource is inserted.?<jsp:include> tags are dynamically introduced, <jsp:include> The 2 JSP pages involved in the tag are translated into 2 servlets, and the contents of the 2 Servlets are merged at execution time. The include directive is static, and the 2 JSP pages involved are translated into a servlet whose content is merged at the source file level. Whether it's a <jsp:include> tag or an include directive, they all merge two JSP page contents, so the two pages don't have duplicate HTML global schema tags, otherwise the content output to the client will be a cluttered HTML document. <jsp:forward> tags are used to forward requests to another resource. Syntax:

<jsp:forward page= "Relativeurl | <%=expression%> "/>

The page property is used to specify the relative path of the resource to which the request is forwarded, and it can also be obtained by executing an expression. When you use <jsp:include> and <jsp:forward> tags to introduce or forward requests to other resources, you can use the < The jsp:param> tag passes parameters to this resource. Syntax 1:

<jsp:include page= "Relativeurl | <%=expression%> ">

<jsp:param name= "parametername" value= "parametervalue|<%= expression%>"/>

</jsp:include>

? Syntax 2:

<jsp:forward page= "Relativeurl | <%=expression%> ">

<jsp:param name= "parametername" value= "parametervalue|<%= expression%>"/>

</jsp:include>

? When using <jsp:include> and <jsp:forward> tags to introduce or forward requests to other resources, you can use <jsp:param> tags to pass parameters to this resource. Syntax 1:

<jsp:include page= "Relativeurl | <%=expression%> ">

<jsp:param name= "parametername" value= "parametervalue|<%= expression%>"/>

</jsp:include>

? Syntax 2:

<jsp:forward page= "Relativeurl | <%=expression%> ">

<jsp:param name= "parametername" value= "parametervalue|<%= expression%>"/>

</jsp:include>

The Name property of the?<jsp:param> label is used to specify the parameter name, and the Value property is used to specify the parameter value. Multiple <jsp:param> tags can be used to pass multiple parameters in <jsp:include> and <jsp:forward> tags.

<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>

? There is a problem with the JSP syntax format in the JSP page, which prevents it from being translated into a servlet source file, and the JSP engine will prompt for the location (rows and columns) of such errors in the JSP page and related information. JSP page JSP syntax format is not a problem, but the translation of the servlet source file has a Java syntax problem, resulting in the JSP page translation into the servlet source files can not be compiled, The JSP engine will also prompt for such errors in the location (rows and columns) of the JSP page and related information. The servlet program translated by the JSP page has an exception at run time, which is exactly the same as a run-time error for an ordinary Java program, and the Java virtual machine will prompt for errors in the location (rows and columns) of the servlet source file and related information. Whether it's a JSP or a servlet, Although all can be used to develop dynamic Web resources. However, due to the characteristics of these 2 technologies, in the long-term software practice, the servlet is gradually used as the controller component in the Web application, and JSP technology is used as the data display template. The original reason is that the data of the program is usually beautified and then output: Let the JSP use Java code to generate dynamic data, and landscaping will cause the page difficult to maintain. Having the servlet produce both data and nested HTML code inside the data will also result in poor program readability and difficult maintenance. So the best way is based on the characteristics of these two technologies, so that they are responsible for each, the servlet is responsible for responding to requests to generate data, and the data through the forwarding technology to JSP, the data display JSP to do. So far, Web development has reached 4 domain objects, These 4 domain objects are the focus of the learning web, and also the knowledge points PageContext (called the page domain) request (called the request domain) session (called the Session field) that the written test often examines. ServletContext (called application domain)? Clear the following question: What is a domain? The life cycle of these 4 objects? Which type of domain object to use.

JSP pages and JSP nine implicit objects

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.