Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the JavaWeb component of shared data by Servlet

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces Servlet how to achieve shared data JavaWeb components of the relevant knowledge, the content is detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that everyone after reading this Servlet how to achieve shared data JavaWeb components article will have a harvest, let's take a look at it.

The three major components of Servlet JavaWeb include Servlet components (accept requests and response data), Filter components (filter and intercept requests), and Listener components (listeners). These three components constitute the core content of javaWeb, and are also the most important content of JavaWeb as a back-end.

A brief introduction to Servlet

Servlet is a technology provided by sun Company for developing dynamic web resources.

Sun provides a servlet interface in its API. If you want to send a dynamic web resource (that is, to develop a Java program to output data to the browser), you need to complete the following two steps:

1. Write a Java class to implement the servlet interface.

2. Deploy the developed Java class to the web server.

According to an established calling habit, we usually call the java program that implements the servlet interface Servlet.

II. The running process of Servlet

The Servlet program is called by the WEB server. After the web server receives the Servlet access request from the client:

The ① Web server first checks to see if the instance object of the Servlet has been loaded and created. If so, perform step ④ directly; otherwise, perform step ②.

② loads and creates an instance object of the Servlet.

③ calls the init () method of the Servlet instance object.

④ creates a HttpServletRequest object that encapsulates the HTTP request message and a HttpServletResponse object that represents the HTTP response message, then calls the service () method of Servlet and passes the request and response objects as parameters.

Before the ⑤ WEB application is stopped or restarted, the Servlet engine uninstalls Servlet and calls the destroy () method of Servlet before uninstalling.

Servlet components:

What is a Servlet component: the process of processing requests and sending responses is done by a program called Servlet, and Servlet is a derivative of implementing dynamic pages.

The whole process is as follows:

The client sends the request to the server; the server sends the request information to the Servlet;Servlet to generate the response content and transmits it to the server. The response content is generated dynamically, usually depending on the client's request; the server returns the response to the client.

Implementation of data sharing among multiple Servlet

Four data sharing schemes are provided in the Servlet specification:

ServletContext interface

HttpServletRequest interface

HttpSession interface

Cookie class

Request and Response

The principles of request and response objects:

= = are created by the server, let's use them

The request object is to get the request message, and the response object is to set the response message

= = request object inheritance architecture:

ServletRequest interface

HttpServletRequest interface

(tomcat class) org.apache.catalina.connector.RequestFacade

Forwarding and redirection

The first kind of request.getRequestDispatcher (). Forward (request,response):

1. It belongs to forwarding, which is also a server jump, which is equivalent to a method call. In the process of executing the current file, it turns to the target file. The two files (current file and target file) belong to the same request, and the front and back pages share a request. You can transfer some data or session information, request.setAttribute () and request.getAttribute ().

2. After two executions, the address bar remains unchanged and remains the address of the current file.

3. You can't turn to pages and websites other than this web application, so the speed of the turn should be fast.

4. The "/" contained in the URL represents the path of the application (project).

The second response.sendRedirect ():

1. It belongs to redirection, which is also a client jump, which means that after the client sends a request to the server, the server returns a response. After receiving the response, the client sends another request to the server, a total of two requests. The front and back pages do not share a request, and cannot read the attribute values set by request.setAttribute () before redirection.

2. After two executions, the address bar is changed to be the address of the target file.

3. You can turn to pages and websites other than this web application, so the speed of the turn is relatively slow.

4. The "/" contained in the URL species represents the path to the root directory.

Special applications: response.sendRedirect () should be used when modifying, deleting, or adding data. If request.getRequestDispatcher (). Forward (request,response) is used, then the address bar before and after the operation will not change, and it will still be the modified controller. If you refresh the current page at this time, you will re-send a request to modify the data, which is why some people add a piece of data every time they refresh the page.

How to pass data in the second way:

1. You can select session, but delete it in the second file

2. You can include parameters in the requested url, such as "add.htm?id=122".

Typical application scenarios:

Forward: access the Servlet processing business logic, and then forward to jsp to display the processing result. The URL in the browser remains unchanged.

Redirect: submit the form and redirect it to another jsp after successful processing to prevent the form from being submitted repeatedly. The URL in the browser has changed.

Global scope object

6. Developers are used to calling ServletContext objects [global scope objects]

7. How it works: there is a global scope object for every website [equivalent to] a Map

Save the data to the global operation domain object, which can be obtained from the global scope object and used by other servlet at this time

8. Life cycle: during the startup of the Http server, a global scope object is automatically created in memory. During the run, the global scope object is only one, and it is always alive. When the Http server is shut down, it is destroyed.

The life cycle of global scope objects runs through the entire running cycle of the website.

ServletContext global scope object, which is shared by all Servlet

Is a domain object

Can read global configuration parameters

You can search for resource files under the current project directory

You can get the current project name (understand)

All domain objects have the following three methods:

SetAttribute (name,value); name is the String type, and value is the Object type; add data to the domain object and add it in the form of key-value when added

GetAttribute (name); reads the data in the domain object according to the specified key

RemoveAttribute (name); deletes data from the domain object according to the specified key

The HttpServletRequest object represents the request of the client. When the client accesses the server through the HTTP protocol, all the information in the HTTP request header is encapsulated in this object. Through the method provided by this object, all the information requested by the client can be obtained.

The technology of HttpSession server

The server creates a separate HttpSession for each user.

HttpSession principle

When a user accesses Servlet for the first time, the server creates a separate Session for the user.

And generate a SessionID, the SessionID will be loaded into the cookie in response to the browser, and thus saved in the browser. When the user visits the Servlet again, the request will carry the SessionID in the cookie to visit, and the server will check whether there is a corresponding Session object according to this SessionID.

Take it out and use it if you have it; create a Session without it (equivalent to the user's first visit)

Scope of the domain:

Context domain > Session domain > Request domain

The Session domain exists as long as the session does not end, but Session has a default survival time (30 minutes).

Cookie

Client session technology to save data to the client

Using QuickStart:

Create Cookie objects and bind data

New Cooike (String name,String value)

3. Send Cookie object

Response.addCookie (Cookie cookie)

4. Get Cookie, get data

Cookie [] request.getCookie ()

Timing of Cookie destruction

1. Destroyed by default when the browser is closed

two。 In the case of manual setting, setting the Cookie survival time and closing the browser will not cause Cookie to be deleted.

Cookie.setMaxAge (60); / / set cookie to survive on the hard disk for 1 minute

Session

Server-side session technology

For Servlet:

If Servlet is the resource of the first WEB application accessed by the client, the HttpSession object will be created only if request.getSession () or request.getSession (true) is called.

1)。 How do I get a HttpSession object in Servlet?

Request.getSession (boolean create): create is false. If there is no HttpSession object associated with the current JSP page, null is returned.

If true create is returned as true, a HTTPSession object must be returned. If there is no HttpSession object associated with the Anqian JSP page, the server creates a new HttpSession object to return, and if so, returns the association directly.

Request.getSession () is equivalent to request.getSession (true)

two。 When to destroy the HttpSession object:

1)。 Directly call the invalidate () method of HttpSession: invalidate HttpSession

2)。 The server uninstalls the current Web application.

3)。 The expiration time of the HttpSession is exceeded.

Set the expiration time of HttpSession (in S)

Session.setMaxInactiveInterval (5); out.print (session.getMaxInactiveInterval ()); 30

This time is the timeout of Session. If you do not access the server after the timeout, Session will automatically fail.

Session has the following characteristics:

(1) the data in Session is saved on the server.

(2) any type of data can be saved in Session

(3) the default life cycle of Session is 30 minutes, which can be set manually for a longer or shorter time.

This is the end of the article on "how Servlet implements shared data JavaWeb components". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to share data JavaWeb components in Servlet". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report