Javaweb (iii) JSP 3 instructions, 6 actions, 9 built-in objects, and 4 large scopes

Source: Internet
Author: User



Objective



The previous introduction about what is JSP, today I will introduce you to JSP three instructions, 6 actions and its 9 large built-in objects. Then we'll go straight to the chase.


I. 3 Instructions for JSP


JSP directives (Directive) 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 .



Directives are used to declare some properties of a JSP page , such as encoding and document type. We also affirm the type of encoding and response that we use in the servlet, and the JSP is declared with an instruction. We also talked about an instruction, the page directive.



JSP instruction format:<%@ directive {attribute=value}*%>(<%@ directive name attribute 1 = "Property value 1" Property 2 = "Property value 2" ...) %>)



Analysis:



Directive: Directive name, such as page directive



Attribute=value: Following the instruction name is a variety of properties, written in the form of key-value pairs



*: Represents the following can be followed by 0 or more attributes.


1.1. Page directive (used to declare properties of JSP pages, etc.)


<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> page directive followed by three attributes, language, ContentType, pageencoding, respectively.



This is just a few of the properties and is not written in full, the page directive allows the properties as shown in the following table:



Property Name Value Range description



       language Java explains the JSP file in the language, generally Java language, the default is Java



extends which class the JSP file inherits when compiling the full name of any class, the JSP is a servlet, so it is necessary to implement the servlet's Init, destroy, and so on when indicating that the generic class is inherited



       Import Any package name, class name introduces the class, package, etc. used in the JSP, import is the only page directive attribute that can be declared multiple times , an import can refer to Uogelei, separated by commas in the middle,



such as <%@ page import= "Java.util.list,java.util.arraylist"%>



       session True, False if the JSP built-in Session object, if true, the built-in session object, can be used directly, otherwise, the default is True



AutoFlush True,false whether to run the cache, if true, the string output using methods such as OUT.PRINTLN () is not immediately reachable to the client server, but is temporarily stored in the cache, the cache is full



Either the program finishes or the Out.flush () operation is performed to the client, which defaults to true.



Buffer None or the number KB specifies the cache size, which is valid when AutoFlush is set to true, such as <%@ page buffer=10kb%>



IsThreadSafe True,false is thread safe, if true, runs multiple threads at the same time to run the JSP program, otherwise it runs only one thread, the remaining threads wait, and the default is False



       iserrorpage true,false Specifies whether the page is an error display page, if true, the JSP has a built-in exception object exception, can be used directly, otherwise, the default is false



       errorpage A JSP page relative path indicates an error page, if the JSP program throws an exception that is not caught, go to errorpage specified page, errorpage the specified page is usually



The Iserrorpage property is True, and the built-in exception object is an exception that is not caught



       contentType Valid document type the client browser determines the document type based on this property , such as HTML format text/html, plain text format text/plain, JPG image image/jpeg, GIF The image is Image/gif,



The Word document is Application/msword, which is often encoded along with the CharSet setting to inform the server and browser that the same Code table is used



Info Any string indicates the information of the JSP, which can be obtained through the Servlet.getservletinfo () method



Trimdirective Whitespaces True, false whether to remove whitespace characters before and after the instruction, default to False



       pageencoding UTF-8,ISO-8859-1, etc. specify a code table to encode the JSP page


1.2. include directive


Relatively simple, there is only one form <%@ include file= "Relativeurl"%> relativeurl: The path to another JSP file or HTML file within the application , for example, All pages in the Web site have a unified style navigation bar and footer copyright, then you can use the directive to include it.



Features: the include directive adds the source code that contains the page to the page that uses the include directive, compiles it into a class file , and so on, a JSP behavior, <jsp:include page= " Relativeurl "> function as with the include directive,



But the difference is that the include behavior is that the runtime executes the included page separately, and then contains the results of the execution to this page, which belongs to the first run after the inclusion.



Attention:



Static inclusions: Include other resources in the current page.
<%@ include file= "/include/header.jsp"%>
Dynamic includes:
<jsp:include page= "/include/header.jsp" ></jsp:include>



The difference between the two: the time period of translation is different
The former: Merge two documents when translating
The latter: The file is not merged and the contents of another file are included when the code executes to the include.



Principle: You can use static without moving.


1.3. taglib directive


JSP support Tag technology, will later talk about the use of tags, jstl tag library usage, etc.



function: Used to indicate the JSP tag library used in JSP page, taglib directive has two attributes, URI is the address of the class library, prefix is the prefix of the tag



<%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>


Ii. 6 actions (behavior) of JSP


In front of the JSP syntax, introduced the JSP page of the content of what, respectively, what role, on two things, module data and elements. The elements include scripts, directives, tags, scripts are embedded in the JSP Java code, instruction function is to declare the properties of the page,



What is the label for, the tag is divided into JSP with built-in tags, and through the taglib instructions to use the JSP tag library , or custom tags. Now let's start with some JSP built-in tags.



JSP built-in tags are called JSP behavior (JSP Actions). As long as writing very little markup code can use the rich features of JSP, JSP behavior is in fact the common JSP function abstraction and encapsulation, can replace the JSP script, so that the JSP less embedded in the Java code Place .



In simple terms, a piece of Java code is represented by a label.



Format: <jsp:elements {attribute= "value"}*/>



Analysis:



JSP: Tag prefix, description is JSP built-in tag,



Elements: The name of the behavior,



Attribute=value: Writing properties using key-value pairs



*: can specify 0 or more attribute pairs


2.1. <jsp:include/> Behavior (Dynamic inclusion)


<jsp:include page= "/include/header.jsp" ></jsp:include>



The include behavior is used to include a file at run time, and if the contained file is a JSP program, the JSP program is executed before the results of the execution are included .



The role is the same as the include directive, the only difference is that the includedirective is to include the source of the files contained in the JSP program, and then compile, belong to the static inclusion, and the include behavior is only to include the results of the files contained in their own. belongs to the dynamic inclusion.



    


2.2. Java Bean Behavior


is a set of behavior related to Java beans, including usebean behavior, setproperty behavior, getproperty behavior , and so on    



Java Bean is a common Java class, also known as Pojo, only the private properties and corresponding getter method and setter method, note that when the private property is a Boolean type, usually the Getter method is generally written isxxx (); Rather than getxxx ();



1) Userbean Behavior



    <jsp:usebean id= "Beanobject" class= "ClassName" scope= "Value" > role: Define a Java Bean object in the JSP .



Analysis:



ID: Indicates the name of the Java Bean object, which can be used by the JSP to refer to the Java Bean object, which is equivalent to taking a variable name for the new object.



Class:java the full name of the Bean class



Scope: The scope of the Java Bean object, can write four, that is, the four main scope of JSP, page, request, session, application



Page: can only be used in the current JSP page, if not on the JSP page, then will be invalidated



Request: This previous study, a page request forwarded to the B page, then the use of the same request, then A/b page is the scope of the request, that is, the page is the scope of requests forwarded



Session: The scope should be read access anywhere under a Web project, as long as the cookie is not turned off, and the access path for the cookie setting is "/",



Application: In fact, ServletContext in the servlet, all projects under the server can be accessed.



2) setproperty behavior



    <jsp:setproperty name= "Beanname" property= "PropertyName" Value= "" >



Analysis:



      Setting properties on a Java Bean object



The name of the Name:java Bean object, which is the ID in the Usebean behavior



Property: The name of the attribute in the object,



Value: Values whose properties are to be assigned



3) GetProperty Behavior



    <jsp:getproperty name= "Beanname" property= "PropertyName"/>



Analysis:



      Get a property value for a JavaBean object



The name of the Name:java Bean object, which is the ID in the Usebean behavior



Property: The attribute name of the object



Example: Javabean:User.java, newfile.jsp



User.java


 
package a; public class User { private int id; private String username; private String password; public int getId() { return id;
    } public void setId(int id) { this.id = id;
    } public String getUsername() { return username;
    } public void setUsername(String username) { this.username = username;
    } public String getPassword() { return password;
    } public void setPassword(String password) { this.password = password;
    }
    
    
}
User


newfile.jsp


<body>
     <!-- Create a new javabean object user, will first determine whether there is a javabean called user object in the page scope, if it is, take it, if not create a new javabean object -->
     <jsp:useBean id="user" class="a.User" scope="page"></jsp:useBean>
     <!-- Assign the username of the javabean object -->
     <jsp:setProperty property="username" name="user" value="faker"/>
     <!-- Get the username attribute of the javabean object -->
     <jsp:getProperty property="username" name="user"/>
</body>
newfile.jsp


You can see the source code after newfile.jsp becomes a servlet and see what kind of statement our JavaBean behavior will be converted to:






Here is a JSP nine large built-in object of one, PageContext. Now, simply put, PageContext is the manager (context) of the JSP page, where the GetAttribute (Name,scope) method is to get the data in the specified scope,



If the GetAttribute (name) method is used, the default is to manipulate the page scope, and Findattribute (name) obtains the content from page, request, session, application in turn.



In the first red box, it represents our usebean behavior, which makes a judgment that if the user object is not found in the page scope, a new one is created, or the user object found is used.



The second red box, which represents our setproperty behavior, first finds the user object, and then assigns its properties to a value



The third red box, which represents our getproperty behavior, is also the first to find the user object and then get the value of its property.



Note: For the javabean behavior, there is a feature where the requested parameter corresponds to the JavaBean attribute, you can set all the values for it once.



<jsp:setproperty name= "User" property= "*"/>//Set all properties of user, property values are automatically obtained from request, * represents all attributes.


2.3. <jsp:forward/> Behavior


  implements the request forwarding function , through Request.getrequestdispatcher ("Someservlet") in the servlet. Forward (Request,response); And in the JSP can also achieve the same function, but with the <jsp:forward/> behavior, in fact forward behavior is to encapsulate it.



Format:




 <jsp:forward page="someServlet">
           <jsp:param name="param1" value="value1"/>
           <jsp:param name="param2" value="value2"/>
        </jsp:forward>


Analysis:page: Need to jump to the pages or servlet, <jsp:param/> parameter behavior, with some parameters in the past, name, value is a key-value pair in the form of the past    



Example:



In the newfile.jsp






In the Forwardtestservlet






Visit: http://localhost:8080/Web_Jsp/NewFile.jsp






The browser address bar has not changed, the description is request forwarding


2.4. <jsp:directive/> Behavior


Directive behavior is equivalent to JSP directives, such as <jsp:directive.page/> equivalent to <%@ page%> instructions, and so on other instructions are the same writing format.



Summarize:



  in our development, the 6 behaviors that are often used are :



<jsp:include > Dynamic Inclusion
<jsp:forward> Request Forwarding
<jsp:param> Set Request Parameters



<jsp:useBean> Create an Object
<jsp:setProperty> assigning values to the specified object properties
<jsp:getProperty> Remove property values for the specified object


Third, the JSP hidden nine large built-in objects


We know that there are only two content in the JSP, template data and elements , the elements include instructions, scripts, tags (behavior), the script will slowly be replaced by the label , that is, JSP basically does not embed Java code , but we also know that JSPs are converted to Servlets,



In a servlet, when outputting data, it is necessary to pass response.getwrite (), but in the JSP, the output is used directly from the Out object. This is because out is a hidden object of the JSP, JSP has built up 9 hidden objects, making JSP easier to use than the servlet, more convenient.


3.1, nine large built-in objects overview





Analysis:



Request: Requested object, type: HttpServletRequest



Response: Response Object type: HttpServletResponse



Session: The technique of recording user-like information on the server side



Application: Identity Web App context, type: ServletContext, see the use of ServletContext in the servlet for details



Exception indicates that an exception object occurred, type Throwable, when we introduced a ErrorPage attribute in the page directive.



The Page:page object represents the current JSP page and is the object of the current JSP-compiled servlet class. Equivalent to this.



Config: Identity servlet configuration, type: Servletconfig,api is the same as the ServletConfig object in the servlet, can get some configuration information of the servlet, can get the ServletContext



    out: Output response body type: JspWriter



    PageContext: Represents the JSP page context (JSP Manager) Type: PageContext



Note: Objects marked with red are unique to JSPs, and others are old things in the servlet.






In this file that is converted from JSP to servlet, only 8 built-in objects are seen, and the exception object is less, because when we put the page directive, we said a Iserrorpage property, the default is False, is closed, So there is no exception object.


3.2. PageContext (important)


This feature is more powerful, basically what he has, because it is the JSP Page Manager (context), so the JSP built-in object Yes, it can be obtained, the following describes its API:



1) Get other eight built-in objects getXxx ()



Other JSP implicit objects can be obtained through PageContext in the normal class . Use when customizing labels.



Pagecontext.getout (); Get Out Object



Pagecontext.getapplication (); Get Application Object



Wait a minute....



2) manipulate the properties of the scope (four scopes)



The properties of the default scope are manipulated. Page



Object getattribute (String name); Get page Scope data



void SetAttribute (String name,object o); Set content to page scope



void RemoveAttribute (String name); To remove content from a page scope



3) Manipulate the properties of the specified scope



Object getattribute (String name,int Scope); Get the data in the specified scope



void SetAttribute (String name,object o,int Scope); Setting content to a specified scope



void RemoveAttribute (String name,int Scope); Removes the contents of the specified scope (page/request/session/application)



4) Provide scope constants



Pagecontext.page_scope PAGE



Pagecontext.request_scope REQUEST



Pagecontext.session_scope response



Pagecontext.application_scope Application



5) Get the specified name at once



The most powerful method in page is:



 Findattribute (String name); Automatically from page request session application in turn, find the value, end the lookup.



Instance:



In 1.jsp:






In the 2.jsp






6) provides a simple method



Pagecontext.forward ("2.jsp");
Pagecontext.include ("2.jsp");


3.3. Out Object


Type: JspWriter



JSP output is used Response.getwriter (); What do you mean? This is the way to explain the JSP cache and the servlet cache, which is the process of output






After the JSP page is converted to a servlet, the out object used is the JspWriter type, so the data to be sent is stored in the JSP output cache, and the JSP output cache is full when it is automatically flushed to the servlet output cache.



When the Serlvet output cache is full, or the program ends, it will be output to the browser. Unless manually out.flush ().



Verify that the servlet output cache and the JSP output cache and what we said above are correct:






Results:






Analysis:








3.4. config Object


Type: ServletConfig



Be able to get the initialization parameters of the servlet, get the ServletContext object, get the Servletname.



This I explained in detail in the servlet, can go to check!


3.5. Exception Exception Object


The information that contains the exception



With it, you must combine the Iserrorpage property and the ErrorPage property in the page directive .



Exception.jsp throws an abnormal nullpointexception, and jumps to the error.jsp error Display page The ErrorPage property means that if an unexpected exception occurs, it jumps to the error.jsp page



Example:






Error.jsp Iserrorpage Property Description The page is an error display page, you can use the exception object






Visit: Visit http://localhost:8080/Web_Jsp/exception.jsp






Summary: Relationship between nine built-in objects and objects in a servlet



The page is the JSP converted to the Servletservlet object itself, which is this



Config--ServletConfig in the servlet



Application--ServletContext in the servlet



Request-Request in the servlet



Response--Response in the servlet



Session-session in the servlet



Out--JspWriter



Exception--Exception object



PageContext--Represents the JSP page context (JSP Manager) Type: PageContext



Where PageContext is the most powerful because it can get the other 8 built-in objects


Four, JSP four scopes


These four scopes, in fact, is the four of its nine built-in objects, why say they are also the four big scope of JSP?



Because these four objects can store data , such as Request.setattribute () Note and Request.setparameter () distinguish, one is stored in the domain, one is the request parameter, Session.setattribute (), application is actually serlvetcontext, Nature also has SetAttribute () method.



The page-scoped operation relies on the PageContext object. In the above we also refer to the four scopes of JSP.



1) Page scope



The delegate variable can only take effect on the current page



2) Request scope



The delegate variable can take effect in a single request, one request may contain a page, or it may contain multiple pages , such as page a request forwarding to page B.



3) Session Scope



Representing variables can be effective in a single session, basically can be valid under the Web project , the use of the session is also very much related to the cookie. In general, as long as the browser does not close, the cookie will remain in effect, and the use of the session will not be affected .



4) Application scope



The delegate variable can be applied under one application (multiple sessions), and can be used between multiple projects under the server . such as Baidu, Wenku and other shared accounts.









Like on the point of a "recommendation" Oh!



Javaweb (iii) JSP 3 instructions, 6 actions, 9 built-in objects, and 4 large scopes


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.