JSP data Interaction (ii) and Servlet basics

Source: Internet
Author: User
Tags session id

01.Application Principle and application

The scope of a 01.application object is the entire application service, and its responsibilities in the application are similar to a global variable. The Application object exists as long as the service is started.

02. There is only one application in an application, and each user will share this Application object.

03. Explain the usage of application by counting the number of visits to the website

02. Object Scope

03.Cookie Introduction

Parsing: A cookie is a series of textual information held by a Web server on the client, which distinguishes between a file and a file size of 4k, depending on the domain name and port number. Note: Http://localhost:8080/news and Http://localhost:8080/news/util will form two cookie files.

1. What is a cookie?

The browser communicates with the Web server using the HTTP protocol, and when a user makes a page request, the Web server simply responds and then closes the connection to that user. So when a request is sent to a Web server, whether or not it is the first visit, the server treats it as if it were the first time, which is a bad thing to imagine. To compensate for this flaw, Netscape has developed a cookie as an effective tool to keep a user's identifying information, so people are nicknamed "cookies." Cookies are a means by which a Web server stores information on a visitor's hard disk via a browser: Netscape Navigator uses a local file called Cookies.txt to hold cookie information received from all sites, while IE stores cookie information in a directory similar to C:\windows\cookies. When a user accesses a site again, the server will ask the browser to find and return the cookie information previously sent to identify the user.

2. Use of cookies

Analytical:

Gets the core code for the specified key value cookie

<%

cookie[] cookies = request.getcookies ();

if (cookies!=null) {

for (int i=0;i<cookies.length;i++) {

if (Cookies[i].getname (). Equals ("uname")) {

Response.sendredirect (path+ "/welcome.jsp");

}

}

}

%>

3.JavaBean

Analysis: The function of JavaBean can be divided into encapsulation data and package business JavaBean

A javabean at least meets the following conditions

01. is a public class

02. Property Private

03. Getter and Setter methods

04. Non-parametric public structure

3. Add the session to use

The TTP protocol is stateless, that is, the information cannot be passed in via the HTTP protocol itself. To track the user's operation status, the ASP applies the Session object. JSPs use an object called HttpSession to achieve the same functionality. HTTPSession is a high-quality interface built on cookies and url-rewriting. The session information is stored on the server side, and the session ID is stored in the client's cookie. In fact, on many servers, cookies are used if supported by browsers, but automatically converted to Url-rewriting,session automatically provides a convenient way to store information for each process if it is not supported or repealed.

Session typically sets a 30-minute expiration time on the server and automatically expires when the customer stops the activity. The information saved and retrieved in Session cannot be a basic data type such as int, double, etc., but must be the corresponding object of Java, such as Integer, double.

HttpSession has the following APIs:

GetId This method returns a unique identity, which is generated for each session. When there is only one single value associated with a session, or if the log information is related to the previous sessions, it is used as the key name.

GetCreationTime returns the time that the session was created. The minimum unit is 1 per thousand seconds. To get a value that is useful for printouts, you can pass this value to the method Settimeinmillis of date constructor or GregorianCalendar.

Getlastaccessedtime returns the time that the session was last sent by the client. The minimum unit is 1 per thousand seconds.

Getmaxinactiveinterval returns the total time (in seconds), and a negative value indicates that the session never times out.

GetAttribute take a session with the information associated with it. (for GetValue in jsp1.0)

Integer item = (integer) session.getattrobute ("item")//retrieves the value of the session and converts it to an integer type

SetAttribute provides a keyword and a value. will replace any previous value. (for Putvalue in jsp1.0)

Session.setattribute ("Itemvalue", itemname); Itemvalue must not be a must simple type

The most used in the app are GetAttribute and setattribute. A simple example is given to illustrate the application of the session, test1.jsp (information is written to the session), test2.jsp (read the information from the session).

Test1.jsp 2  4  6 7  Document  8 9 10 one 12 session.setattribute ("str", New String ("This is Test"), 14 
     20   New Document 21 23 25 <%26 String ls_str=null; 27 Ls_str= (String) session.getattribute ("str"); Out.println ("The value taken from the session is:" +ls_str);%>30 
       

Servlet Basics

Onclass

As long as the class that can handle the client request can be considered a servlet.

00.HttpServletRequest and ServletRequest difference?

Parsing: The methods in the HttpServletRequest interface are easier to operate, and the ServletRequest application scenario is more extensive (can handle any protocol request).

01.servlet and JSP parallel technology

Servlets are two sets of techniques for developing dynamic Web sites in parallel with JSP

02. Describe what a servlet is?

Parsing: A servlet is a Java class that implements a particular interface or parent class.

A Servlet is a Java program that runs on a server (in a Tomcat container) to handle client requests and respond. The role of the servlet is to receive the client's request and respond to the request.

03. Implement the servlet three scenarios:

01.Servlet Interface: 5 methods

Init () {

Initialization

}

Service () {

Processing requests

}

The mudslide destroyed the whole village.

Destory () {

Destroyed

}

Getservletconfig () {

Get servlet configuration information

}

Getservletinfo () {

Get information about Servlets, such as version authors.

}

5 methods: Init (): initialized, only executed once

Destory (): Tomcat executes when it is closed, frees resources, executes once

Service (): Handles client requests and responds to client requests

Getservletconfig (): Get Configuration

Getservletinfo (): Version and other information

02. Implement Genericservlet Abstract class

Modify the Servlet class to restart the server, and modify the JSP page can not restart

03. Implement HttpServlet Abstract class

Service (): Scheduling role

If our own Servlet class inherits the HttpServlet abstract class, then there is no need to rewrite the service () of the parent class, and the service () method is just a dispatch function.

Doxxx:dopost (httpservletrequest request,httpservletresponse response) doget ()

04. Manually implement your own servlet

01.Servlet is a Java class that runs on the server side to handle client requests, if a

A common class implements a servlet interface or inherits from Genericservlet or inherits from HttpServlet, then the class becomes a servlet

02. If the class implements a servlet interface, then the service () method is required to process the request

If the class inherits the HttpServlet abstract class, then the Doget () and Dopost () methods are processed, where

Service () is only a function of scheduling.

05.ServletContext Commentary

ServletContext we can consider ServletContext as a global variable, similar to the one in JSP

The Appliction object.

06.URI and URLs

URI: Uniform Resource Identifier, abstract resource identification method.

URL: A Uniform Resource locator that not only identifies a resource, but also specifies how to navigate to that resource.

Life cycle of 07.Servlet

Life cycle:

Code that is bound to execute at a specific point in the execution of a program

Born: Bathing!!!! 20-30-year-old married 80-year-old death

08. Modify the servlet template

How lazy??

Please pay attention to the following 2 minutes

Modify the Serverlet template

Found under the Plugins folder (plugins) of the common folder

Com.genuitec.eclipse.wizards_9.0.0.me201108091322.jar

08. How do I use servlets for forwarding and redirection?

Parse: Identical to JSP

09. How the servlet gets the session object and gives the inside set data.

Parsing: Request.getsession (). SetAttribute (name, value)

10.init () and Destory () and service () number of executions

Parsing: Init () and Destory () in the servlet are executed only once, and each time the client accesses the corresponding Servlet class, the service () is invoked once Focus

11. Get servlet Initialization parameters

12. Get servlet Context Parameters

Get Scenarios:

Add!

Servlet Initialization parameters:
The servlet initialization parameters are defined in a servlet element in Web. XML, for example:
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.bk.Test</servlet-class>
<init-param>
<param-name>default-time</param-name>
<param-value>60</param-value>
</init-param>
</servlet>
There can be a number of <init-param> pairs.

How do I get the servlet initialization parameters?
A acquisition of a single parameter value

The Getinitparameter (java.lang.String name) method through the ServletConfig interface.

Getservletconfig () This method defines a reference to the ServletConfig interface that is returned in the Servlet interface.
All servlets inherit the method. When the container instantiates a servlet, it reads the servlet's initialization parameters from Web. XML and gives them to ServletConfig, and then, when the init () method is called, The container transmits this servletconfig reference to the servlet. Each servlet will have a unique servletconfig reference. Once you have a servletconfig reference, you can call the Getinitparameter () method to
Get the initialization parameters that we set in the servlet.

2 Getting the way:

public void Service (ServletRequest req,servletresponse res) throws

servletexception,ioexception{
...
Out.println ("init parameters");
Enumeration Myenum=getinitparameternames ();
while (Myenum.hasmoreelements ()) {
String Name= (String) myenum.nextelement ();//Get parameter name
Out.println (name+ ":" +getinitparameter (name));//Get parameter values
}
...
}


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Context Initialization Parameters:

The context initialization parameter is similar to the servlet initialization parameter, except that the context initialization parameter is for the entire Web application, not the servlet

The initialization parameter corresponds to only one servlet.
The context initialization parameters exist throughout the life of the Web app, and any servlet and JSP can access it anytime, anywhere.
The configuration examples in Web. xml are as follows:
<context-param>
<param-name>default-time</param-name>
<param-value>60</param-value>
</context-param>
The context initialization parameter corresponds to the entire Web application, so it is not within a servlet element. A Web application has a servletcontext, and a servlet has a servletconfig.


How do I get context initialization parameters?

The ServletConfig object of the servlet has a reference to the servlet's servletcontext, so that context initialization parameters can be obtained;
Getservletconfig (). Getservletcontext (). Getinitparameter ()
You can also call Getservletcontext () directly in the servlet (). Getinitparameter (), the two are equivalent.

Discussion of 13.MVC mode

Mvc:model (model), view (view) and controller (controllers)

01. All requests are attributed to the controller, and today's servlet acts as the controller's role

Only parse the request (detach the properties of request) and give a response (forwarding determines which JSP page to render the view to)

Collection of 13.HTTP protocols with status hold

The HTTP protocol itself is stateless, which is consistent with the HTTP protocol's original purpose, the client simply needs to request to the server to download some files, both the client and the server do not need to record each other's past behavior, each request is independent, Like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.

Yet clever (or greedy?) People quickly discovered that providing some on-demand dynamic information would make the web more useful, like adding on-demand functionality to cable TV. This demand on the one hand, forcing HTML to gradually add the form, script, Dom and other client behavior, on the other hand on the server side of the CGI specification in response to the client's dynamic request, as a transport carrier HTTP protocol also added file upload, cookie these features. The purpose of the cookie is to resolve the HTTP protocol's stateless flaws in the efforts made. The subsequent session mechanism is another solution for maintaining state between the client and the server.

Let's use a few examples to describe the difference and connection between a cookie and a session mechanism. I used to go to a coffee shop to drink 5 cups of coffee free of charge for a cup of coffee, but a one-time consumption of 5 cups of coffee is very little, then need some way to record a customer's consumption quantity. Imagine the fact that there are several options below:

1, the shop clerk is very strong, can remember each customer's consumption quantity, as long as the customer walked into the coffee shop, the clerk knew how to treat. This approach is the protocol itself that supports the state.

2, issued to customers a card, the above record the amount of consumption, there is generally a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption. This practice is to keep the state on the client.

3, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presented the card, the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side.

Since the HTTP protocol is stateless and does not want to be stateful due to various considerations, the next two scenarios become a realistic choice. In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.

14. The Web Digest does not use the cookie mechanism to complete the session

The Java Servlet API references the Session mechanism to track the state of the customer. The Javax.servlet.http.HttpSession interface is defined in the servlet API, and the servlet container must implement this interface. When a session starts, the servlet container creates a HttpSession object, and the servlet container assigns a unique identifier, called the Session ID, to HttpSession. The Servlet container stores the Session ID as a Cookie in the client's browser. Each time a customer makes an HTTP request, the Servlet container can read the session ID from the HttpRequest object and then find the corresponding HttpSession object based on the session ID to obtain the customer's status information.

It is not possible to track customer status when the client browser prohibits the Cookie,servlet container from obtaining a Session ID as a Cookie from the client browser.

Another mechanism for tracking the session is presented in the Java Servlet API, where the client browser does not support the Cookie,servlet container to rewrite the URL of the client request and add the session ID to the URL information.

The HttpServletResponse interface provides a way to rewrite the URL: public java.lang.String encodeurl (java.lang.String URL)

The implementation mechanism of this method is:

First, determine whether the current Web component is session-enabled, and if not, return the parameter URL directly.

Again determine whether the client browser supports cookies, if a cookie is supported, directly returns the parameter URL, if the cookie is not supported, the Session ID information is added to the parameter URL, and then the modified URL is returned.

We can modify the links in the webpage to solve the above problems:

Before modification:

<a href= "maillogin.jsp" >

After modification:

<a href= "<%=response.encodeurl (" maillogin.jsp ")%>" >

JSP data Interaction (ii) and Servlet basics

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.