Detailed JSP's nine built-in objects and four scope tutorials

Source: Internet
Author: User
Tags abstract http request sessions throwable valid tomcat tomcat server stringbuffer

Nine large built-in objects


Built-in objects (also called suppressed objects, with 9 built-in objects): You can use them freely in scripting code and expressions without having to declare them in advance.

1-out:

Javax.servlet.jsp.JspWriter type that represents the object of the output stream. Scope is page (page execution period)

A subtype of the request:javax.servlet.ServletRequest that encapsulates a Web browser or other client-generated HTTP

Details of the request (parameters, attributes, headers, and data). The scope is request (user requested period).

method is provided by the viewable API

Response:Javax.servlet.ServletResponse, which encapsulates the output returned to the HTTP client, providing the page author with a way to set response headers and status codes. Often used to set HTTP headers, add cookies, set the type and status of response content, and send HTTP redirects and coded URLs. The scope is page (page execution period).

PageContext:Javax.servlet.jsp.PageContext (abstract Class) type, scoped to page (page execution period). This object provides property query and modification capabilities for all four scoping levels, and it also provides methods for forwarding requests to other resources and including other resources:

The object's methods are abstract methods

Session :Javax.servlet.http.HttpSession type, used primarily for tracking conversations. Scope session (Sessions-).

HttpSession is an object similar to a hash table that is associated with a single Web browser session, which exists between HTTP requests and can store either

What type of named object.

If you do not need to track session objects between requests, you can specify session= "false" in the page directive

Remember that the PageContext object can also get and set session properties in the same way as Session.getattribute (), Session.setattribute ().

Application:Javax.servlet.ServletContext type, servlet environment by calling Getservletconfig

(). GetContext () method obtained. The scope is application (entire program runtime). It provides a way to register information about server versions, application-level initialization parameters, and absolute paths of resources within applications

Config:Javax.servlet.ServletConfig, Scope is page (page execution period)

Exception:Java.lang.Throwable, one of the catch blocks in the JSP error page has been benefited but not captured

Any instance of the java.lang.Throwable, passed to the URI of the ErrorPage. The scope is page (page execution period). Attention

Exception is valid only if you have a property iserrorpage= "true" in the page directive.

page:Java.lang.Object type, pointing to the way the page itself is. Scope is page (page execution period

The nine main built-in objects in JSP are:

Request object Type Javax.servlet.ServletRequest Scope request

Response Response Object Type Javax.servlet.SrvletResponse scope Page

PageContext page Context object type Javax.servlet.jsp.PageContext Scope page

Session conversation Object type Javax.servlet.http.HttpSession scope sessions

Application Application Object type Javax.servlet.ServletContext scope application

Out output Object type Javax.servlet.jsp.JspWriter scope Page

Config configuration object Type Javax.servlet.ServletConfig scope Page

Page Page object Type javax.lang.Object Scope page

Exception exception Object type javax.lang.Throwable Scope page


The Request object represents requests from the client, such as the information we fill in form forms, and the most commonly used objects are: GetParameter, Getparameternames, and Getparametervalues The values of the parameters contained in the request object are obtained by calling these methods.

The response object represents a response to the client, which means that the data sent to the client can be organized through the response object. However, because of the lower level of organization, it is not recommended for ordinary readers to use the text when they need to send to the client directly

PageContext object literal translation can be called a "page Context" object, which represents some properties of the current page running

Common methods are: Findattribute, GetAttribute, Getattributesscope and Getattributenamesinscope

In general, PageContext objects are not used much, only in the case of the project is more complex situation, will use the page properties to assist processing.

The Session object represents the sessions established by the server and the client, and is used in situations where customer information needs to be retained in different JSP pages, such as online shopping, customer tracking, and so on. The session object is built on a cookie, so use it to determine whether the client has a cookie open. Common methods include GetID, GetValue, GetValueNames and Putvalue.

Summary

HTTP is a stateless (stateless) protocol;

Web Server has no historical memory for each client request;

Session is used to save client state information;

Written by web Server;

stored in the client;

Each visit by the client passes the last session record to the Web Server;

Web server reads client-submitted sessions to obtain state information for the client

The Application object is responsible for providing some global information about the application running in the server, and the common methods are GetMimeType and Getrealpath.

The Out object represents the object that sends the data to the client, unlike the "Response" object, the content sent through the "out" object will be what the browser needs to display, is at the text level, and can be written directly to the client by the "out" object to generate an HTML file dynamically from the program. Common methods include clear, Clearbuffer, flush, getbuffersize, and getremaining, in addition to Pirnt and println, because the "Out" object contains a buffer inside. So you need some way to manipulate the buffer.

The "config" object provides some configuration information, and the common methods are getinitparameter and getinitparameternames to get the parameters for servlet initialization.

The "Page" object represents a running class object generated by a JSP file and is not recommended for use by the general reader.

The "Exception" object represents the exception object that is generated by the JSP file runtime, which cannot be used directly in a generic JSP file and can only use four scopes in a JSP file that uses the "<%@ page iserrorpage=" true "%>":

What is a scope

Let's look at the effect first:

Probably the process is like this, when we visit 04-01/index.jsp, respectively to PageContext, request, session,

Application The variables in the four scopes are cumulative. (Of course, first of all, to determine whether this variable exists, if the variable does not exist, then initialize the variable to 1.) After the calculation is complete, jump from index.jsp execution forward to test.jsp. Add one more to the test.jsp and then display the four integers.

From the results shown, we can intuitively draw the conclusion that:

The variables in page cannot be passed from index.jsp to test.jsp. As soon as the page jumps, they are gone.

The variables in the request can span two pages before and after forward. But as soon as the page is refreshed, they are recalculated.

Session and application in the variable has been cumulative, beginning to see no difference, as long as the browser closed, restart the browser to access this page, the session in the variables are recalculated. Source

The variables in the application are accumulating, and unless you restart Tomcat, it will keep getting bigger.

The scope stipulates the validity period of the variable.

If you put a variable in the PageContext, it means that it's scoped to page, and its valid range is only in the current JSP page.

You can use this variable from the beginning of the PageContext to the end of the JSP page.

If you put the variable in the request, it means that its scope is request, and its valid range is the current request cycle.

The so-called request cycle, that is, from the HTTP request, to the end of the server processing, return the entire process of response. In this process, you may use forward to jump through multiple JSP pages, where you can use this variable.

If you put the variable in the session, it means that its scope is the sessions, and its valid range is the current conversation.

The current session, that is, from the user opened the browser to start, to the user to close the browser in the middle of the process. This process may contain multiple request responses. That is, as long as the user does not close the browser, the server has the means to know that these requests are initiated by a person, the whole process is called a session, and placed in the session of the variable, can be used in all the requests of the current conversation.

If you put the variable in the application, it means that its scope is application and its effective range is the whole application.

The entire application is started from the application to the end of the application. We did not say "boot from server to server shutdown" because a server might deploy multiple applications, and of course, if you shut down the server, all of the above applications would be shut down.

The variables in the scope of the application, which have the longest surviving time, are always available if they are not deleted manually.

Unlike the three above, the variables in application can be shared by all users. If user A's action modifies a variable in application, User B accesses the modified value. This will not happen in any other scope, page, request,session are completely isolated, no matter how the modification will not affect the data of other people.

We use the public Object getattribute (string name) to get the value of the variable, and use the public void setattribute (string name, Object value) to save the value of the variable to the corresponding scope. An example of a PageContext is:

Page

Integer countpage = (integer) pagecontext.getattribute ("Countpage");

if (countpage = = null) {

Pagecontext.setattribute ("Countpage", 1);

} else {

Pagecontext.setattribute ("Countpage", Countpage + 1);

}

Here we first remove the integer named Countpage from the PageContext, because the Java.lang.Object type is returned, so we need to cast it to the shape we need. The variables obtained here will return NULL if they do not exist, by judging countpage = NULL to determine whether the variable exists, if it does not exist, set to 1, if there is an accumulation, and finally using setattribute () method to put the modified variable value into the PageContext.

Replace the PageContext with request, session, application can manipulate variables in the other three scopes.




HTTP protocol and JSP

The Web pages we visit in the browser are based on the HTTP protocol. Looking back at our first JSP program--hello World, in the browser input localhost:8080/hello.jsp, we can see Hello world displayed in the browser. What's the effect behind this?

When using a browser to get HTML pages from a Web site, we use a very familiar, highly professional protocol--http protocol (Hypertext Transfer Protocol) to participate in the blog HTTP protocol overview.

The HTTP protocol provides a way to transfer information over the Internet, especially by providing a way for browsers to interact with the server and to transmit information. The commonly used methods are get, post and so on. An important element in the HTTP protocol is the HTTP message, which is a block of data sent between HTTP applications and is the carrier of information transmission. Details see: HTTP Message detailed description

We open a Web page with a simple process that includes both the request and response phases.

First, the browser wants the target host to issue an open connection and a request message to the appropriate resource. When the server receives the request, it sends a response message to the client, and the core of the HTTP protocol is the request and response.

Now back to the content of JSP, the blog post JSP basic syntax, this article introduces the built-in object JSP. Some objects in the JSP page can be used in Java patches and expressions, which is the built-in object of the JSP.

JSP contains 9 kinds of built-in objects: request, response, out, page, session, and so on. The request and response respectively represent requests and response objects, which are more important two. These two objects provide control over the server and browser communication methods. If you have the basis of the HTTP protocol, you can see the meaning of the two objects, as well as some commonly used methods, quickly master JSP is also very simple. The knowledge of HTTP protocols is very important in web programming.

1.request: Request Object

This object encapsulates the information submitted by the user, and it can get the encapsulated information by calling the object to the appropriate method. The main methods are as follows:

Request.getparameternames (); Enumeration<string>
Request.getparameter (String name);//string
Request.getheader (sring name); String
Request.getheadersnames (); Enumeration<string>
Request.getrequestdispatcher ("/somepage.jsp"). Forward (request, response);
Request Forwarding

Get Request Headers

Enumeration<string> headernames =request.getheadernames ();
while (Headernames.hasmoreelements ()) {
String headername=headernames.nextelement ();
System.out.print (headername+ ":");
System.out.println (Request.getheader (headername));
}

Gets the post data, Request.getparameter (String s) is invalidated

StringBuffer sb = new StringBuffer ();
BufferedReader br = new BufferedReader (New InputStreamReader (
Request.getinputstream ()));
String s = "";
while ((s = br.readline ())!= null) {
Sb.append (s);
}
System.out.println (Sb.tostring ());

Solve Chinese garbled

Post method
Request.setcharacterencoding ("Utf-8");
Response.setcharacterencoding ("Utf-8");
Get mode
String string = Request.getparamers ("");
string = new String (String.getbytes ("Iso8859-1", "Utf-8"));

2.response: Response Object

This object responds to the customer's request and sends data to the client.

Response.sendredirect ("index.jsp"); redirect
Response.setcontentype (String s);
Response.AddHeader (String name,string value);
Response.addcookie (Cookie c);

A typical response HTTP response packet Header

http/1.0 200OK
Date:mon,31dec200104:25:57gmt
server:apache/1.3.14 (Unix)
Content-type:text/html
Last-modified:tue,17apr200106:46:28gmt
content-length:39725426


3.session: Session Object

The Tomcat server can use the session to record information about the connection. This session object has a string ID, and when the client requests the server, the server sends the ID number to the client, which is stored in the client's cookie.

Lifecycle: The client sends the first request to the server, and the server creates a session object to close the browser destroy (approximate so to understand).

Session.getid (); String
Session.setattribute (String key,object obj);
Session.getattribute (String key); Object
Session.isnew ();

4.application: Application objects

This application object was generated after the server was started, and all users shared the Application object. Until the server shuts down.

Application.setattribute (String key,object obj);
Application.getattribute (String key); Object

5.cookie: Client Object

A cookie is a piece of text that a Web site saves on a user's hard disk and is recorded as a "key-value pair."

Sending cookies to clients

Cookies c=new Cookies ("username", "Guang");
Response.addcookie (c);

Read cookies saved on the client

Cookie cookies[]=request.getcookies ();
for (Cookie c:cookies) {
if ("username". Equals (C.getname ()) {
Out.println (C.getvalue ());
}
}

Set the valid time for cookies

Cookie C=new Cookies ("username", "Tom");
C.setmaxage (3600);//3600 seconds


6.out: Output Object

Out.println ();
Out.newline ();
Out.close ();

7.config: Configuring Objects

8.page: Page objects

9.pageContext: Page Context

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.