JSP Technology Summary

Source: Internet
Author: User

In this section, we summarize the relevant techniques of JSP.

1. What is JSP

JSP is Java Server Pages, which, like servlet technology, is a technology defined by sun to develop dynamic Web resources. The biggest feature of this technique is that writing a JSP is like writing HTML, but it can only provide static data to the user compared to HTML, and JSP technology allows nested Java code in the page to provide dynamic data to the user.

2. JSP principle1) How does a Web server invoke and execute a JSP page?

The server first translates the JSP into a servlet, and the translated servlet can be viewed in the \tomcat home directory \work\catalina\localhost\ the project name \org\apache\jsp directory, which is the server's working directory. Open the appropriate servlet to see that the translated Servlet inherits the Org.apache.jasper.runtime.HttpJspBase, and Httpjspbase inherits the Httpserrvlet. In this case, we understand that JSP is a servlet, and accessing a JSP is a servlet.

2) How is the HTML layout tag in the JSP page sent to the client and how is the Java code server executed?

Continue to browse the JSP translated servlet, there is a service method _jspservice (request, response), in this method can be seen, all the contents of the JSP will be translated into the service method, The HTML code passes out, just like before the JSP is learned, the Java part of the code is moved to the service method in the same way as the out HTML statement in the servlet.

3) What Java objects will the Web server provide to the JSP when invoking the JSP?

When a Web server translates a JSP into a servlet, it provides all of the Web development objects in the service method, so that we can use the objects directly in the JSP page without having to get them. The objects provided by the Web server (these objects are analyzed in detail below) are:

Final Javax.servlet.jsp.PageContext PageContext;         PageContext object Javax.servlet.http.HttpSession session = NULL;           Session object final Javax.servlet.ServletContext application;          Application Object final Javax.servlet.ServletConfig config;                Config object javax.servlet.jsp.JspWriter out = null;                  Out Object Final Java.lang.Object page = this;                      Page object Javax.servlet.jsp.JspWriter _jspx_out = null;            
There are also parameter request and response for the service method. So what the servlet can do, JSP can do. But both have their own characteristics, and we continue to look down.

3. Best Practices for JSP

Whether JSP or servlet, although can be used to develop dynamic Web resources, but because of the characteristics of these 2 technologies, in the long-term software practice, the servlet as a controller component in the Web application to use, and JSP technology as a data display template to use. The reason is that the program's data is usually beautified and then output. Let JSP use Java code to generate dynamic data, and landscaping will make the page difficult to maintain, so that the servlet both produce data, and nested HTML code inside the data, it will also lead to poor program readability, difficult to maintain, so the best way is to let the servlet responsible for the data generated by the corresponding request , and the data through the forwarding technology to jsp,jsp used to do data display.

4. JSP Syntax1) JSP template element

The JSP template element is the HTML content in the JSP page. The JSP template element defines the basic skeleton of a Web page, which defines the structure and appearance of the page.

2) JSP script expression

JSP script expressions are used to output program data to the client.

Syntax:<%= variable or expression%> such as: Current time: <%= new Java.util.Date ()%>
When the JSP engine translates the script expression, it turns the program data into a string and then uses the Out.print (...) in the appropriate location. Lose data to the client.
Note:you cannot have a semicolon after a variable or expression in a JSP script expression (;)

3) JSP script fragment

JSP script fragments are used to write multiple lines of Java code in a JSP page.
Syntax:<% multi-line Java code%>
Note:JSP script fragments can only appear in Java code, no other template elements , the JSP engine in the translation JSP page, the JSP script fragment in the Java code is left intact in the servlet's _jspservice method. The Java code in the JSP script fragment must strictly follow the Java syntax.
You can have multiple script fragments in a JSP page that can embed text, HTML tags, and other JSP elements between two or more script fragments. The code in different script fragments can be accessed from one another as if all the code were put into a <%%>. But all the script fragments together must be a complete Java code.

4) JSP declaration

The Java code in the JSP declaration is translated to the outside of the _jspservice method. (Interview questions)
Syntax:<%! java code%>
Therefore, JSP declarations can be used to define a static block of code, member variables, and methods that the JSP page translates into a servlet program. Multiple static code blocks, variables, and methods can be defined in a JSP declaration or individually in multiple JSP declarations.
JSP implicit objects are scoped to the _jspservice method of the servlet, and JSP-declared code is translated to the outside of the method, so these implicit objects cannot be used in JSP declarations.

5) JSP annotations

Syntax: <%-annotation information-%>
When the JSP engine translates a JSP page into a servlet, it ignores the annotated content in the JSP page.
If you use <!--comment content in a JSP--the comment will be called to the browser, and the browser will recognize the comment, so it won't be displayed to the user. The JSP comment does not call the comment content to the browser.

6) JSP instructions

JSP directives are designed for the JSP engine, and they do not directly produce any visible output, but simply tell the engine how to handle the rest of the JSP page.
Syntax:<%@ directive Property name = "Value"%>
Example: <%@ page contenttype= "text/html;charset=utf-8"%> <%@ page import= "Java.util.Date"%>
If a directive has multiple properties, these attributes can be written in a single instruction, separated by a space. That is, the above two instructions are equivalent:

Three directives were defined in the JSP2.0 specification:
1)page directive :

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, which is the entire JSP page. To maintain the readability of the program, the page directive is best placed at the beginning of the entire JSP page.
Grammar:

<%@ page              [import= "{package.class | package.*},..."]              [session= "true | false"]              [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 will automatically import the following packages: java.lang.*/java.servlet.*/javax.servlet.jsp.*/javax.servlet.http.*
When the JSP imports multiple packages, you can write them separately, or you can put them together and put them together, using commas to separate them:
<%@ Paga import= "java.util.date,java.sql.*,java.io.*"%>    
When the session property is set to True, the session object is automatically created in the translated servlet, and false is not created.
The ErrorPage property is used to set the appropriate page for the error. Its value 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, it is relative to the current page. You can also use the <error-page> element in the Web. xml file to set the error-handling page for the entire application, where the <exception-type> child element specifies the fully qualified name of the exception class,<location> ELEMENT specifies an error-handling page path that begins with "/". If you set the ErrorPage property of a JSP page, the error handling set in the Web. xml file will not work for that page.
When Iserrorpage is true, it means that the page is handling error pages, and when the JSP engine translates into a servlet, it defines a exception object so that error information can be obtained with the exception implicit object.
The JSP engine generates a corresponding statement that calls the Servletresponse.setcontenttype method based on the ContentType property of the page directive.

2) include directive :
The include directive is used to introduce other JSP pages, and if a different JSP page is introduced with the include directive, the JSP engine translates the two jsps into a servlet, so include directives are often referred to as static ingestion. Since the JSP engine translates multiple JSP pages into a servlet, the code for the global schema can be removed (Grammar:

<% include file= "Relativeurl"%>
Where the file property is used to specify the path of the introduced files. Begins with "/", representing the current web app.

Several details need to be noted:
· The file being introduced must follow the JSP syntax;
· The introduced file can use any extension, even if the extension html,jsp engine will be processed as a JSP page, in order to see the name, the JSP specification recommends using the. JSPF (JSP fragments) as the extension of the static introduction 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 two JSP pages do not conflict (except for pageencoding and guide packages). For example, now to introduce two JSP pages, one JSP session= "true", the other JSP session= "false", so when the introduction of these two JSP pages will create a conflict, the server will error.
In JSP, you can also use Java code to implement dynamic inclusion:

<% request.getrequestdispather ("Relativeurl"). Include (Request,response);%>
In this way, the JSP engine translates different JSP pages into different servlets, dynamically containing only the results of introducing other JSP pages. When dynamically included, the server invokes multiple Web resources, and when statically contained, it is translated into a servlet, and the server only needs to invoke a Web resource, so the static inclusion is a bit better, and the development is statically included.

3)taglib Directive : Used to import the custom tag library, see the contents of the Custom Label section later

5. JSP operating principle and 9 large implicit objects

From the above: 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 now translates the JSP into a _jspservlet (essentially a servlet) and then invokes it in the way the servlet calls. Because the JSP is translated into a servlet on the first visit, the first access is usually slower, but the second access, if the JSP engine finds that the JSP has not changed, is no longer translated, but is called directly, 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 in order to facilitate the developers in writing JSP pages to obtain these Web object references, deliberately defined 9 corresponding variables, developers in the JSP page through these variables can quickly get these 9 large object references, 9 large implicit objects and what their respective role?

REQUEST://is the requestresponse in the servlet://The Responsesession in the servlet://The Sessionapplication in the servlet:// Is the servletcontextconfig in the servlet://Is the servlet servletconfigpage://Is the servlet himself exception://exception, only errorpage have out:// JSP page Output Pagecontext:<span style= "Font-family:microsoft Yahei;" The >//</span>pagecontext object is one of the most important objects in JSP technology, which represents the running environment of JSP pages.
PageContext object is the most important object in JSP technology, which represents the 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 from other domain objects, and so on.

Getexception<span style= "Font-family:microsoft Yahei;" > ()  //</span> method returns exception implicit object Getpage<span style= "Font-family:microsoft Yahei;" The > ()  //</span> method returns the page implicit Object Getrequest ()  //method returns the request implicit Object GetResponse ()  // The response method returns an implicit object Getgetservletcontext ()  //method return application Implicit Object Getservletconfig ()  // The method returns a Config object GetSession ()  //method returns session implicit Object Getout ()  //method returns an out implicit object
PageContext, as a domain object, also encapsulates the following methods:

PageContext method for domain object: public void SetAttribute (string name, object value) public Object GetAttribute (string name) public The void RemoveAttribute (string name)//pagecontext object also encapsulates methods that access other domains (important) public void SetAttribute (string name, object value, int scope) Public Object getattribute (string name, int scope) public void RemoveAttribute (string name, int scope)//constant representing each domain PageContext.APPLICATION_SCOPEpageContext.SESSION_SCOPEpageContext.REQUEST.SCOPEpageContext.PAGE_SCOPE
So far, it should be possible to see the power of the PageContext object! There is also a Findattribute method (* Important, to find the attributes in each domain, the EL expression depends on this method), you can call Pagecontext.findattribute (String name) directly, This property is first looked up from the PageContext and, if not, in the following order in the corresponding field: request, session, ServletContext, returns null if not found, otherwise returns the property value.
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, and the method receives a resource that begins with "/" Represents the current web app. However, the include is dynamically included and is not recommended for use.

6. JSP tags

JSP tags, also known as JSP action elements, are used to provide business logic functionality in JSP pages, avoiding the ability to write Java code directly in JSP pages, which makes JSP pages difficult to maintain. JSP has three kinds of tags

1) <jsp:include> label

The <jsp:include> tag is used to insert the output of another resource into the output of the current JSP page, which is called dynamic Introduction when the JSP page executes.
Grammar:

<jsp:include page= "Relativeurl | <%= expression%> "Flush=" true | False "/>
Equivalent to calling Pagecontext.include ("Relativeurl")
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 contents of the current JSP page are flushed to the client first when the output of the other resource is inserted.

2) <jsp:forward> label

<jsp:forward> tags are used to forward requests to another resource
Grammar:

<jsp:forward page= "Relativeurl | <%= expression%> "/>
The page property is used to specify the relative path of the resource to which the request is forwarded, which can be obtained by executing an expression.

3) <jsp:param> label

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

<jsp:include page= "Relativeurl | <%=expression%> ">      <jsp:param name=" parametername "value=" parametervalue | <%=expression%> "/ ></jsp:include>
Equivalent to relativeurl?name=...&value= ....
Syntax 2:
<jsp:forward page= "Relativeurl | <%=exception%> ">      <jsp:param name=" parametername "value=" parametervalue | <%=expression%> "/ ></jsp:forward>
Equivalent to relativeurl?name=...&value= ....
The Name property of the <jsp:param> tag 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.

7. JSP Mappings

JSPs can also be mapped as Servlets, because JSPs are inherently servlets.

<servlet>    <servlet-name>SimpleJspServlet</servlet-name>    <jsp-file>/jsp/ Simple.jsp</jsp-file></servlet><servlet-mapping>    <servlet-name>simplejspservlet </servlet-name>    <url-pattern>/xxx/yyy.html</url-pattern></servlet-mapping>
/JSP/SIMPLE.JSP represents the simple.jsp file in the webroot/jsp directory

8. Four domain objects

So far, web development has been exposed to 4 domain objects, and these 4 domain objects are the focus of the learning web, as well as the knowledge points often examined in written examinations:

PageContext (called page field): Data stored in//pagecontext can be removed from the page range request (called request domain): The  data stored in the//request can be removed from the session ( Called Session field): The  data stored in the//session can be removed from the session range ServletContext (called the application domain): The data stored in the//servletcontext can be removed from the entire application range
Clear the following two questions: The life cycle of these four objects? What kind of object is used?
Request: If the client sends the requested data to the server, it is useless for the user to read it, and the request domain is present to such data. As users see the news.
Session: If the client sends the request data to the server, the user has run out of wait for a while to be useful, to such data exists in the session domain. If the user buys the thing, because the checkout also needs to use.
ServletContext: If the client sends the request data to the server, the user is exhausted and is used for other users, the data exists in the ServletContext domain. If you say something in a chat room, you should see it in your own page, as well as others.
In practice, you can use small containers do not use large, that is, request can not be satisfied with the session,session can not be used ServletContext

9. Summary

Since JSPs are generally forwarded through the servlet, the servlet brings the data through the container, so the data is taken out of the container using a JSP and then displayed. Take the data with the script fragment <%%> to fetch, display the script expression <%=%> processing. After learning about El expressions and custom tags, script fragments can be replaced with custom tags, and script expressions can be substituted with El expressions.

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----More articles please see: http://blog.csdn.net/eson_15

JSP Technology Summary

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.