Introduction to Jsp

Source: Internet
Author: User

Introduction to Jsp

I have talked about servlet getting started practice. Now I am going to introduce jsp getting started practice. For the establishment of the development environment, please refer to my previous tomcat article. The jsp getting started tutorial is divided into two sections: jsp syntax specifications, as well as three compilation commands, seven action commands, nine built-in objects, and life cycle explanations.


Download all code: Link

1. jsp introduction:

The full name of JSP is Java Server Pages, and the Chinese name is java Server Page. It is a simplified Servlet design, it [1] is a dynamic web page technical standard, proposed by Sun Microsystems and jointly established by many companies. JSP technology is a bit similar to ASP technology, it is in the traditional web page HTML (a subset of standard General Markup Language) file (. Htm,Insert the Java program segment (Scriptlet) and JSP tag in. html to form a JSP file with the suffix (*. jsp ). Web applications developed using JSP are cross-platform. They can run both on Linux and other operating systems.
The first jsp program:
1. Create a dynamic web project in eclipse
2. Right-click WebContent and choose create jsp file.
3. Enter the following in the jsp file:

<%@ page language=java contentType=text/html; charset=UTF-8    pageEncoding=UTF-8%>
<% out.print(hello peace); %> Enter http: // localhost: 8080/project name/NewFile. jsp in the browser
Shown as follows:
JSP is a servlet variant. jsp files are translated into servlet files. The file location is Tomcat, and the file is saved to your directory: apache-tomcat-7.0.64/work/Catalina/localhost/stuJsp/org/apache/jsp

Open the java file and you can see that the file of the root servlet of this file is similar to: _ jspInit (), jspDestroy (), _ jspService. The code in the jsp file is generated in the _ jspService () method.
2. JSP Syntax: 2.1.JSP script:

A script program is used to insert java code into HTML. It can contain any java statement, variable, method, or expression with true syntax. When the servlet Source Code is generated, the code is put in the _ jspService () method.
1. Script Syntax:
<% Code snippet %>
Just like the first jsp program

<%  out.print(hello peace);%>
Note:: The tag and jsp elements cannot appear in the script. Remember to write only java, but you can insert them as follows:
<% For (int I = 0; I <5; I ++) {out. print (hello peace + I); %> <% out. print (line breaks are interspersed in the middle, and will be output cyclically);} // for Loop end %>
2.2.JSP statement:

A declaration statement can declare one or more variables and methods for later Java code. In JSP files, you must declare these variables and methods before using them. When the servlet Source Code is generated, the Code becomes the attributes and methods of the class;
1. Syntax declared by JSP:
<%! Declaration; [declaration;] +... %>
2. the demo is as follows:

<%! private int i=10; %>  <%!    public void test(){     int a=0;     int b=2;     a=a+b;     System.out.print(a); } %>
View the generated servlet File to know the variables and Methods declared in jsp just now, and become the corresponding property and method 2.3JSP expression:

The script language expression contained in a JSP expression is first converted to a String and then inserted to the place where the expression appears. The function is equivalent to the out (output) in the script)
Because the expression value is converted to a String, you can use an expression in a text line without worrying about whether it is an HTML Tag.
Expression elements can contain any expressions that comply with the Java language specifications, but cannot end the expressions using semicolons.
When the servlet Source Code is generated, the code is put in the _ jspService () method.
1. Syntax format of JSP expressions
<% = Expression %>
2. the demo is as follows:

<% -- The local variable declared in the script cannot contain the modifier -- %> <% String nick = sisi; int a = 10, B = 10; %> 3. jsp expression: <% -- the expression can output an output equivalent to out. write does not need to end with a semicolon -- %> <% = (a-B) %> <% = nick %>
2.4JSP notes:

JSP comments will not appear in the source code of html and can be used to comment jsp code. html comments will appear in the source code of html;
1. Syntax format of JSP comment:
<%-Enter the JSP comment here-%>
2. the demo is as follows:

1. jsp comments: <% -- these comments will not appear in the html source code and can be used to annotate jsp code -- %>
3. Three compilation commands:

JSP compilation instructions are used to set attributes related to the entire JSP page;
There are three major compilation commands:

<% @ Page... %> define page dependency attributes, such as script language, error page, and cache requirements <% @ include... %> include other files <% @ taglib... %> introduce the tag library definition. It can be a custom tag.
3.1page instructions:

The Page command provides instructions for the container to use the current Page. A JSP page can contain multiple page commands.
1. Syntax format of the Page command:
<% @ Page attribute = "value" %>
2. attributes:

3. the demo is as follows:

<%@ page language=java contentType=text/html; charset=UTF-8    pageEncoding=UTF-8 import=java.util.Random%>
3.2include command Introduction: (static include)

JSP can use the include command to include other files. The contained files can be JSP files, HTML files, or text files. The contained file is like a part of the JSP file and will be compiled and executed at the same time.
1. The syntax format of the Include command is as follows:
<% @ Include file = "url" %>
2. The file name in the Include command is actually a relative URL. If you do not associate a file with a path, the JSP compiler searches for the path by default.
3. the demo is as follows:

<% -- 1. the principle is to put the contained page (header. jsp) content is translated to the include page (index. jsp), merged into a java source file, and then compiled and run !!, This type of inclusion is called static inclusion (source code inclusion). 2. The contained page does not need to contain global html tags !!! (Such as html, head, body) -- %> <% @ include file =/common/header. jsp %>
3.3taglib instructions:

JSP APIs allow users to customize tags. A custom tag library is a set of custom tags. The Taglib command introduces a set of custom tags, including library paths and custom tags.
1. syntax of the taglib command:
<% @ Taglib uri = "uri" prefix = "prefixOfTag" %>
2. uri is the tag location determined by the attribute. The prefix attribute specifies the prefix of the tag library. This will be further introduced later;
3. the demo is as follows:

Custom tag library <% @ taglib uri = http://rlovep.com prefix = rlovep %>
4. Seven major action commands:

Unlike the compilation command, the Action Command notifies the servlet engine to process messages when compiling the command, while the Action Command is only the action during running. The compilation command works when compiling JSP into Servlet, and the processing command can usually be replaced with JSP script, which is just a standardized way of writing JSP scripts.
(1) JSP: forward the execution page to forward request processing to the next page.
(2) JSP: param is used to pass parameters. It must be used together with other tags that support parameters.
(3) JSP: include is used to dynamically introduce a JSP page.
(4) JSP: plugin is used to download JavaBean or Applet to the client for execution.
(5) JSP: useBean: Create a Javabean instance
(6) JSP: setProperty: Set the attribute value of the JavaBean instance
(7) JSP: getProperty: Get the attribute value of the JavaBean instance

4.1jsp: forward Command

Jsp: forward action transfers the request to another page. Jsp: forward only has one property page.
1. The syntax format is as follows:

2. page attribute: The page attribute contains a relative URL. The page value can be provided directly or dynamically calculated during the request. It can be a JSP page or a Java Servlet.
3. When the forward Command is executed, the address of the user request remains unchanged and is still a request, but the page content completely changes to the content of the target page of the forward. When the forward request is executed, the client's request parameters are not lost. Similar to
GetRequestDispatcher ("/GetData"). forward (request, response );
4. Additional request parameters can be added with JSP: param action commands.

<% -- Forward jsp: foward parameter jsp: param
      
       
    
   
  -- %>
4.2jsp: include command (Dynamic inclusion)

Jsp: include> action elements are used to contain static and dynamic files. This action inserts the specified file into the page being generated
1. Syntax format:

2. the preceding include compilation commands are different from the previous ones. Dynamic inclusion is used here. Static inclusion is used to import files when JSP files are converted to servlets. jsp: the include action is different. The file insertion time is when the page is requested. If the page to be included is jsp, another servlet will be generated;
3. attributes:
Page: the url of the contained page
Flush: Boolean attribute, which defines whether to refresh the cache before the resource is included.
4. Additional request parameters can be added with JSP: param action commands.

<% -- Dynamic include -- %> dynamic include:
       
   
  

4.3jsp: userBean, setProperty, getProperty command

These three commands are related to JavaBean. The userBean command is used to initialize a java instance on the JSP page, and the setProperty command is used to set values for the properties of the JavaBean instance; the getProperty command is used to output attributes of a JavaBean instance.
1. Syntax of jsp: useBean simple action:

The id attribute is the Instance name of JavaBean, and the class attribute determines the implementation class of the JavaBean. The scope attribute is used to specify the scope of a JavaBean instance.
2. Syntax format of jsp: setProperty:

The name attribute determines the Instance name of the JavaBean, the property attribute determines the attribute name of the set attribute, and the value Attribute determines the value corresponding to the attribute name.
3. Syntax format of jsp: getProperty:

For the name attribute, you must determine the Instance name of the JavaBean instance. The name attribute specifies the value corresponding to the attribute name to be obtained.
4. the demo is as follows:

<% -- UseBean setProperty getProperty -- %> <% -- the name of the instance where Student is created is in the property range of "page -- %>
<% -- Set the name value of student -- %> <% -- Output the name value of student -- %> name: 4.3jsp: param, plugin command

Param is used to set the parameter value. This command cannot be used independently. Therefore, a separate param command has no practical significance. The param command can be used in combination with the following command.
Jsp: include jsp: forward jsp: plugin. The usage method is described above;
The plugin command is mainly used to download the server-side JavaBean or Applet to the client for execution. Because the program is executed on the client, the client must install the virtual machine. This command is rarely used and is not described;

4.4 The overall demonstration is as follows:

The action. jsp file needs to be created to forward action2.jsp pages in a level. It contains the/common/header1.jsp and JavaBean: Student Class.

<% -- Forward jsp: foward parameter jsp: param
      
       
    
   
  -- %> <% -- Dynamic include -- %> dynamic include:
       
   
  <% -- UseBean setProperty getProperty -- %> <% -- the name of the instance where Student is created is in the property range of "page -- %>
<% -- Set the name value of student -- %> <% -- Output the name value of student -- %> name: 5. 9 Introduction to large built-in objects

The JSP script contains nine built-in objects, all of which are examples of Servlet API interfaces, only JSP specifications initialize them by default (these instances are created by the _ jspService () method of the Servlet corresponding to the JSP page ). That is, they are already objects and can be used directly.

Where JSP initializes the nine objects, you can see the following through the generated servlet class:

The request and response objects are the form parameters of the _ jspService () method. When Tomcat calls this method, these two objects are initialized. Page, pageContext, application, config, session, and out are all local variables of the _ jspService () method, which completes initialization.

5.1 Brief Introduction: For details, refer to my Servlet getting started application: javax. servlet. servletContext instance, which represents the Web application to which the JSP belongs. It can be used for JSP pages or for information exchange between servlets. Common methods include getAttribute (StringattName), setAttribute (String attName, String attValue), and getInitParameter (StringparamName. Config: the instance of javax. servlet. ServletConfig. This instance represents the configuration information of the JSP. Common methods include getInitParameter (StringparamName) and getInitParameternames. In fact, JSP pages do not need to be configured, so there is no configuration information. Therefore, this object is more effective in Servlet. Exception: java. lang. Throwable instance. This instance represents exceptions and errors on other pages. This object can be used only when the isErrorPage attribute of the compiled command page is true. Common methods include getMessage () and printStackTrace. Out: an instance of javax. servlet. jsp. JspWriter. This instance represents the output stream of the JSP page and is used to output content to form an HTML page. Page: indicates the page itself, which is usually of little use. That is, this in Servlet. Its type is the generated Servlet class, which can be used in pages. PageContext: an instance of javax. servlet. jsp. PageContext. This object represents the context of the JSP page and can be used to access Shared data on the page. Common methods include getServletContext () and getServletConfig. This object stores the reference of the request object and response object. Application object, config object, session object, and out object can be exported by accessing the properties of this object. The PageContext class defines some fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE. It also provides more than 40 methods, half of which are inherited from the javax. servlet. jsp. JspContext class. One important method is removeArribute (), which can accept one or two parameters. For example, pageContext. removearriname ("attrName") removes the attributes of Four Scopes. However, the following method only removes the attributes of a specific scope:
PageContext. removeAttribute ("attrName", PAGE_SCOPE); request: javax. servlet. http. httpServletRequest instance. This object encapsulates a request, and all client request parameters are encapsulated in this object. This is a common object, which must be used to obtain client request parameters. Common methods include getParameter (String paramName), getParameterValues (StringparamName), setAttribute (String 8. 8/attrName, Object attrValue), getAttribute (StringattrName), and setCharacterEncoding (String env. Response: The instance of javax. servlet. http. HttpServletResponse, representing the server's response to the client. Usually this object is rarely used for direct response, but the out object is used unless a non-character response needs to be generated. Response objects are often used for redirection. Common methods include getOutputStream () and sendRedirect (java. lang. String location. Session: an instance of javax. servlet. http. HttpSession. This object represents a session. When the client browser establishes a connection with the site, the session starts. When the client closes the browser, the session ends. Common methods include getAttribute (String attrName) and setAttribute (StringattrName, Object attrValue. 5.2 Four domain objects:
PageContext --- page domain
Request --- request domain
Session --- session domain
Application --- context:
Stores and obtains data for data sharing. Domain object method:
SetAttribute ("name", Object) stores data
GetAttribute ("name") to get data
RemoveAttribute ("name:
Page field: can only be used on the current jsp page (current page)
Request domain: can only be used (forwarded) in the same request)
Session domain: can only be used in the same session (session Object) (private)
Context field: can only be used in the same web application. (Global) 5.3 overall demonstration is as follows:
<%@ page language=java contentType=text/html; charset=UTF-8    pageEncoding=UTF-8    %>
<% -- Out object: corresponding to jspwriter -- %> <%/* for (int I = 0; I <= 1024; I ++) {out. write (a);} System. out. println (current cache size: + out. getBufferSize (); System. out. println (size of the remaining cache zone: + out. getRemaining (); * /// if not refreshed, 123 is output first; // out. flush (); response. getWriter (). write (123); %> <% -- application Object: corresponds to the attributes stored in the context in the servlet, which are shared by the entire application. configuration parameters can also be obtained; -- %> <% // storage attribute application. setAttribute (name, peace); %> <% = application. getInitParameter (ke Ys) %> <% -- config object: The config In the servlet is not very useful -- %> <% = config. getServletName () %> <% -- exception object: This object is valid on the error page and can be used to obtain the incorrect attribute: this object is valid only when isErrorPage = true of the compiled command page <% = exception. getMessage () %> -- %> <% -- request object: request -- %> <% = request. getLocalName () %> <% -- response object: corresponding to response -- %> <% response. getWriter (). println (hello respose); %> <% -- session object: The session in the servlet -- %> <% session. SetAttribute (pass, 567); %> <% -- pagecontext object: jsp page object can get the other eight objects: -- %> <% // get other objects response. getWriter (). write (are they equal? + (Out = pageContext. getOut () +
); %> <% -- Objects can be stored in different domains -- %> <% pageContext. setAttribute (message, wang); pageContext. setAttribute (age, 22, PageContext. REQUEST_SCOPE); pageContext. setAttribute (qq, 374126165, pageContext. SESSION_SCOPE); pageContext. setAttribute (tl, 1881679, pageContext. APPLICATION_SCOPE); // redirect to another page to obtain data: response. sendRedirect (request. getContextPath () +/pageget. jsp); // Delete the stored object pageContext. removeAttribute (age, PageContext. REQUEST_SCOPE); %>
6. JSP lifecycle explanation:

The key to understanding the underlying functions of JSP is to understand the lifecycle they observe. The JSP lifecycle is the entire process from creation to destruction. Similar to the servlet lifecycle, the difference is that the JSP lifecycle also includes compiling JSP files into servlets.

6.1JSP execution process:

Access: http: // localhost: 8080/project name/NewFile. jsp
1. Access the NewFile. jsp page. tomcat scans the jsp file and translates the jsp file into a java source file in/work/Catalina/localhost/stuJsp/org/apache/jsp.
(NewFile. jsp-> NewFile_jsp.java) (translation)
2. the tomcat server compiles the java source file into a class bytecode file (Compilation)
(NewFile_jsp.java-> NewFile_jsp.class)
3. Construct NewFile_jsp class object on the tomcat server
4. the tomcat server calls the method in the NewFile_jsp class and the returned content is displayed in the browser.

The first access to jsp: Go (1) (2) (3) (4)
Subsequent access: Go (4)
Note:: The jsp file has been modified or the jsp temporary file has been deleted, and the process of translation (1) and compilation (2) needs to be re-performed.

6.2JSP lifecycle: JSP Compilation:
When a browser requests a JSP page, the JSP Engine first checks whether the file needs to be compiled. If this file has not been compiled or changed after the last compilation, compile the JSP file. Compiled as servlet; JSP initialization:
After the container loads the JSP file, it will call the jspInit () method before providing any service for the request. You can rewrite this method: In the jsp declaration Section
<%! Public void jspInit () {initVar ++; System. out. println (jspInit (): JSP is initialized + initVar + times);} %>
JSP execution:
This stage describes all request-Related interactions in the JSP lifecycle until they are destroyed. The _ jspService () method is executed for each service request. JSP cleanup:
The destruction stage of JSP lifecycle describes what happens when a JSP page is removed from the container. Generally, jspDestroy () is executed only when the container stops deploying the project () method you can rewrite
<%! Public void jspDestroy () {destroyVar ++; System. out. println (jspDestroy (): JSP destroyed + destroyVar + times);} %>
Lifecycle comparison between JSP and servlet
Servlet lifecycle: 1) constructor (1st visits) 2) init method (1st visits) 3) service method 4) destroy method Jsp lifecycle: 1: jsp-> java file 2) Compilation: java file-> class file (servlet program) 3) constructor (1st accesses) 4) init method (1st accesses ): _ jspInit () 5) service method: _ jspService () 6) destroy method: _ jspDestroy ()
6.3 Demo:
<%@ page language=java contentType=text/html; charset=UTF-8    pageEncoding=UTF-8%>
<%! // Record execution times: private int initVar = 0; private int serviceVar = 0; private int destroyVar = 0; %> <%! Public void jspInit () {initVar ++; System. out. println (jspInit (): JSP is initialized + initVar + times);} public void jspDestroy () {destroyVar ++; System. out. println (jspDestroy (): JSP is destroyed + destroyVar + times); }%> <% serviceVar ++; // System. out. println (_ jspService (): JSP has responded to + serviceVar + requests); // String content1 = initialization times: + initVar; string content2 = Customer response times: + serviceVar; String content3 = destruction times: + destroyVar; %> <% -- output display -- %> <%=content1 %> <%=content2 %> <%=content3 %>

Shown as follows:

 

Related Article

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.