Four scopes of web development

Source: Internet
Author: User

Four domain objects in Web development (range from small to large):

Page (JSP valid) request (one request) session (one session) application (current web App)

The page field refers to PageContext.

The request domain refers to the HttpServletRequest

The session field refers to the HttpSession

Application field refers to ServletContext

The reason they are domain objects is that they all have built-in map collections, all with the SetAttribute getattribute method. And their name is a string type, and value is the object type.

They all have their own fixed life cycle and scope.

The life cycle of these four objects (the life cycle is the creation of value objects into the period of destruction):

The page:jsp page is executed, the life cycle begins, the JSP page executes, and the declaration period ends.

Requests: The user sends a request, starts, the server returns a response, the request ends, and the life cycle ends.

Session: The user opens the browser access, creates the session (start), the session timeout or is declared invalid, the object life cycle ends.

Application:web is created when the application loads. The web app is removed or the server shuts down and the object is destroyed. [end].

--------------------------------------------------------------------------------------------------------------- ----------------------------------------------

Attention:

1.Page is valid only in the current JSP, and each request corresponds to a different requests.

2.Request, valid only for the current request, each request corresponds to the different request domain

The request domain can invoke the GetAttribute () method of the implied object of request to access an object with this scope type. You can also use the GetParameter (string name) return string to get the arguments passed to it in the XML.

String data = "Xby request";
Request.setattribute ("data4", data);
Request.getrequestdispatcher ("/1.jsp"). Forward (request, response);

Request can be used for forward

String data = (string) request.getattribute ("Data");
Out.write (data);

The forward method throws a IllegalStateException exception if some of the content written to the servlet program before forward is actually delivered to the client. "The key is to return after the jump."
  If the content is written to the servlet engine's buffer (response) before the forward method is called, as long as the content written to the buffer is not actually output to the client, the forward method can be executed normally, the contents of the original write to the buffer The   will be emptied, but the response field information that has been written to the HttpServletResponse object remains valid.
  Forward Request Forwarding features:
   1. The client only makes one request, and the server side has multiple resource calls
   2. The client browser-side Rul does not change.
----------------------------------------------------------------------------------------------------------- --------------------------------------------------
3.Session is valid only in one session, the session ends and the data cannot be taken. GetAttribute (String name) return Object
 httpsession session = Request.getsession ();
  Session.setattribute ("name", "TV");

Response.setcharacterencoding ("UTF-8");//handling Chinese garbled problem
Response.setcontenttype ("Text/html;charset=utf-8");//handling Chinese garbled problem
PrintWriter out = Response.getwriter ();//handling Chinese garbled problem

HttpSession session = Request.getsession ();
String product = (string) session.getattribute ("name");
Out.write (product);

The server creates a session for the browser only when GetSession (), and his life cycle defaults to 30min.
<session-config>
<session-timeout>10</session-timeout>
</session-config>
When using Request.getsession (FALSE), the session is viewed without generating a session. For example, when viewing a purchased item, it is used. IE8 words, open 2 browser or share a SESSION,IE7 is the server to write SessionID into the browser process, and IE8 is the server to achieve a number of the same browser session sharing.

"Cookie" If you do not specify the expiration date of the cookie object, the cookie object only exists in the client's memory. Cookies expire when the browser is closed.
HttpSession session = Request.getsession ();
String SessionID = Session.getid ();
Cookie cookie = new Cookie ("Jsessionid", SessionID);
Cookie.setpath ("/servlet");
Cookie.setmaxage (30*60);
Response.addcookie (cookie);
Session.setattribute ("name", "TV");//re-write the cookie. Set the time.
If you disable cookies, use URL rewriting techniques to bring the URL of the browser to the SessionID.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

4.application: In the JSP auto-generated servlet file, this is defined as: final Javax.servlet.ServletContext application;
ServletContext Domain:

1. This is a container

2. Indicate that the scope of this container is the entire application scope


public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
String data= "Xby OK";
This.getservletcontext (). SetAttribute ("Data", data);
System.out.println ("Write ok!");
}

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
String value = (string) this.getservletcontext (). getattribute ("Data");
System.out.println (value);
}
The ServletContext can forward the servlet, but the servlet is not easy to display.

Forward
String data= "Xby yes!";
This.getservletcontext (). SetAttribute ("Data", data);

RequestDispatcher rd = This.getservletcontext (). Getrequestdispatcher ("/1.jsp");
Rd.forward (request, response);
This is not good because ServletContext is shared by all servlets in the same app because it involves multithreading issues.

To read Web resources through ServletContext:
InputStream in= This.getservletcontext (). getResourceAsStream ("/web-inf/classes/db.properties");
Properties Props = new properties ();
Props.load (in);

String username = props.getproperty ("username");
String passwd = Props.getproperty ("passwd");

Get the resource file path (for upload download):
String path= This.getservletcontext (). Getrealpath ("/web-inf/classes/db.properties");
FileInputStream in = new FileInputStream (path); "

Use ServletContext to manage related resources. WebApp are executed under the JVM, so the absolute path is the path to the JVM.
ServletContext will be created at server startup, directory in WebApps The ServletContext will be destroyed when the server is stopped.---------------------------------------------------------------------------------------------- --------------------------------------------------------------- -

Four domain objects, when selected, can be used in a range of small ranges:

Page: The data is only temporarily present in the collection, used elsewhere in the JSP page, with page (custom map in the page)

(When you need to use a map, just use page)

Request: "The program generates data and the data is not used after it is displayed."
The data is only shown, and it is useless to read it. In the request domain, requests are forwarded, the servlet produces processing results (data) to the JSP display. Data forwarding can take data.


Session: "The program produces data, display, etc. will also need to use"
The data to the user to read, must also use, the session is over the useless

User login, user information to the client to see, after reading, a visit to other pages also depends on user information.

Shopping cart, Shopping cart success, to the user to see the shopping cart, will be able to view the shopping cart over time

Request redirection, because it is two requests, each request data, the second request also to see.

Application: "ServletContext in JSP another name is application, after the data display, and so will need to use, but also to others, such as chat room"
Data to a user ran out, others need to use;
Chat rooms, chat logs, need to be read to all users; Statistics website online number, all see should be a number

"Summary": four domain objects when selected, can not use a range of small range.
1. When you need to define a map, use page,
2. Request the servlet, forwarded to the JSP data store request,
3. Request redirect with past data storage session,
4. Global data storage application.
4.servletcontext:web container at startup, he creates a corresponding ServletContext object for each "Web application" that represents "the current Web application" and resides in the server's memory.
The data in a contex is shared, and it is the configuration information and configuration parameters of the Web application.

(Transferred from Http://www.cnblogs.com/boyangx/p/4081050.html)

Web Development Four scopes (RPM)

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.