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 apply Cookie and Session mechanisms in Java Servlet

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to apply Cookie and Session mechanisms in Java Servlet". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Servlet Cookies

Cookies definition: Cookies is a text file stored on the client computer and keeps all kinds of tracking information about the user.

Cookies function: session persistence, such as completing user login and state retention

How Cookies works:

The client initiates a login request to the service area

The server script (code) sends a set of Cookies to the browser, such as name, age, etc.

Browsers store this information on the local computer for future use

The next time the browser sends any request to the web server. The browser will send this Cookies information to the server, which will use this information to identify the account

1.1 Cookies composition

Cookies is usually set in the HTTP header. If you set the http request of Cookie, the following information will be sent to Servlet.

The Set-Cookie header contains a name-value pair, a GMT date, a path and a field, both of which are encoded by URL

The expires field is a command that tells the browser to pass ("forget") the Cookie after a given time and date.

If the browser is configured to store Cookies, it will keep this information until the expiration date

If the browser on the user side points to any page that matches the path and domain of the Cookie, he will resend the Cookie to the server, and the header information of the browser may be as follows:

At this point, Servlet can access Cookie through the request method request.getCookies (), which will return an array of Cookie objects

1.2 Servlet operation Cookie method 1.3 code example:

For the specific steps, create two back-end classes, which are:

Set cookie information

Get cookie information

Set the cookie information code

Import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;public class SetCookieServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ / 1. To create a Cookie object / / first you need a cookie object. Here we need two cookie objects, one to store the user name (username--java) and one to store the password (pwd--javas) Cookie username = new Cookie ("uesrname", "java"); Cookie pwd = new Cookie ("pwd", "javas") / / after we have created two cookie objects, we can perform a series of operations on them / / for example: set his expiration time, here we set the expiration time of username to permanent username.setMaxAge (- 1); / / set the expiration time of password pwd to one minute, and note that its expiration time is pwd.setMaxAge (60) in seconds / / 2. Associate the Cookie object to the response resp.addCookie (username); resp.addCookie (pwd); / / the information displayed to the user part resp.setCharacterEncoding ("utf-8"); resp.setContentType ("text/html"); / / then write the response to the client PrintWriter writer = resp.getWriter (); writer.println ("Cookie set successfully") @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet (req, resp);}}

Note: don't forget to configure the web.xml file

Get cookie information code

Import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter Public class GetCookieServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ / read Cookie information / / because the client may have multiple cookie, so we use an array to receive. Note: cookie is Cookie [] cookies = req.getCookies () obtained from request; resp.setContentType ("text/html"); resp.setCharacterEncoding ("utf-8") PrintWriter writer = resp.getWriter (); / / then read the contents of the cookie for (Cookie item: cookies) {writer.println ("Cookie key:% s Cookie value:% s", item.getName (), item.getValue ());} @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet (req, resp) }}

Note:

1. Don't forget to configure the web.xml file

two。 Because when we set cookie information above, the expiration time of pwd is one minute, and there is not enough time when we want to get cookie information, so it is recommended to modify a longer expiration time.

II. Servlet Session

Session definition: session is a text file stored on the server and keeps all kinds of tracking information about the user.

Session function: session persistence, such as completing user login and state maintenance, is relatively secure because it is on the server side.

The storage form of Session in Servlet

2.1 session method for Servlet operation

Session is implemented with cookie

HttpSession object

Servlet provides a HttpSession interface, which provides a way to identify users and store information about users when requesting or visiting websites across multiple pages

The Servlet container uses this interface to create a session session between the HTTP client and the HTTP server that lasts for a specified period of time. Request across multiple connections or pages

You can get the HttpSession object (for example: HttpSession session = request.getSession ()) by calling HttpServletRequest's public method getSession (), and you need to call request.getSession () before sending any document content to the client.

Several important methods are available in the HttpSession object:

Small knowledge: session operates through request, while cookie operates through request and response.

2.2 Code example

About the read and write operation code of session

Import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.io.PrintWriter;import java.util.Date;public class SessionServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ / about session read / write / 1. First get session to the object HttpSession session = req.getSession (); / / 2. Get the attribute of session / / 2.1get the ID String sessionID = session.getId () of session; / / return the response information resp.setContentType ("text/html"); resp.setCharacterEncoding ("utf-8"); PrintWriter writer = resp.getWriter (); writer.println ("Welcome to the page") / / output sessionID writer.println (String.format ("SessionID:% s", sessionID)); / / output the creation time of session. Because the creation time of session is a timestamp, we need to force it into a time writer.println that we can read (String.format ("Session creation time:% s", new Date (session.getCreationTime () / / output the last access time of session writer.println (String.format ("last access time of Session:% S", new Date (session.getLastAccessedTime ();} @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet (req, resp) This is the end of the introduction of "how to apply Cookie and Session mechanisms in Java Servlet". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report