About cookie in Java

xiaoxiao2021-03-06  141

These days have been watching the information of the user session in Java, in order to save the session between users and specified Server, there are two ways: session and cookies, this already has a lot of information on the Internet, here I haven't described it. .

Imagine such a situation, user user access server Server1, at this time, the content of the user is not on Server1, and on Server2, the role of Server1 is just access control, which controls users to other Server access and control other Server to returned to User information. . In this case, how to save and get session and cookies is a problem.

For the above questions, the solution is this: Do URL rewrite and cookie replacement. The following: Because the user accesses Server1 and Server1 forwarding access requests to Server2, two session or cookies are generated, and they are named JSessionID and XsessionID, respectively, to prevent them from being covered between each other, need to be re-emergence. Name one of the session or cookies. When the user accesses the content on Server2, the Server1 cuts the access request, obtains the value of the cookie domain in the HTTP request header, if in which the cookie information jession of the Access Server1 is included, this information is filtered, and it is determined whether to contain xsessionID, if it contains XsessionID, rename the XsessionID to jsessionID, do not change, rewrite into the HTTP header, then send requests to Server2 via Server1; Server2 receives the request for server1 forwarding, return to Server1 About User Secondary request, this time, you will rename the jsessionID to xsessionID and save the XsessionID to the HTTP response head to save the session information between USER and Server2 to regain the next time the next access server2 will regain this session. information. The whole process is like this, of course, this also contains a problem with a cookie domain, and it is possible to do a corresponding process.

Here is some of the information I have searched about how to handle cookies in Java for your reference.

Handling Cookie Series: Cactus Studio Cookie Overview Cookies is a small amount of plain text information sent to the browser to the browser, and the browser will send them to the server when the user has access to the same web server. By letting the server reads the information you originally saved to the client, the website can provide the viewer to provide a series of convenience, such as the user identity in the online transaction process, and the security requirements are not high to avoid user repeated input name and password, portal The home page is customized, targetedly putting advertisements, and so on. The purpose of cookie is to bring convenience to users, bring value to the website. Although there are many mistakes, in fact, cookies will not cause serious security threats. Cookie will never be executed in any way, so there will be no virus or attack your system. In addition, since the browser is generally only allowed to store 300 cookies, each site stores up to 20 cookies, each cookie size is limited to 4 KB, so the cookie will not be full of your hard drive, and it will not be used as "refusal." Service "attack means. Servlet's cookie API To send cookies to the client, servlet first creates one or more cookies (2.1) with the appropriate name and value, set various properties with cookie.setxxx (2.2 Section), add cookie to your response head (Section 2.3) via response.addcookie (cookie). To read from the client, servlet should call the request.getCookies (), and the getCookies () method returns an array of cookie objects. In most cases, you only need to use the individual elements of the array to find the cookie of the array, and then call the getValue method to get the value associated with the specified name, this part of this session will be discussed in Section 2.4. Creating a cookie Call the constructor for cookie objects to create a cookie. The constructor of the cookie object has two string parameters: cookie name and cookie value. Names and values ​​cannot contain blank characters and the following characters: [] () =, "/? @:; Read and set the cookie property to add cookies to the response head to be sent, you can view or set various properties for cookies. These methods are described below: Getcomment / setcomment Gets / Sets the annotations of the cookie. GetDomain / setdomain Get / sets the cookies applicable domain. Generally, cookies only returns the same server that is identical to the server name to send it. Use the method You can indicate that the browser returns the cookie to other servers in the same domain. Note The domain must start with a point (for example, .sitename.com), non-national domain (such as .com, .edu, .gov) must contain two points, Country-class domains (such as .com.cn, .edu.uk) must contain three points. GetMaxage / setMaxage Get / set the time before the cookie expires, in seconds. If this value is not set, cookies are only current sessions. Internal valid, that is, it is valid before the user closes the browser, and these cookies will not be saved to disk. See below about longlivedcookie. GetName / SetName Get / set the name of the cookie. Essentially, the name and value are we always care about. Two parts.

Since the GetCookies method of HTTPSERVLETREQUEST returns a Cookie object array, therefore usually uses a loop to access this array to find a specific name, and then check its value with getValue. getPath / SetPath Gets / Sets the path to Cookies. If the path is not specified, the cookie will return to all the pages in the current page where the current page is located and its subdirectory. The method here can be used to set some more general conditions. For example, someCookie.SetPath ("/"), at which time all pages on the server can receive the cookie. GetSecure / SetSecure Gets / Sets a Boolean value that represents whether cookies can only be sent by encrypted connections (ie SSL). GetValue / SetValue Gets the value of / set the cookie. As mentioned earlier, the names and values ​​are actually two aspects we have always cared. However, there are also some exceptions, such as using the name as a logical tag (that is, if the name exists, it means true. GetVersion / SetVersion Gets / Sets the protocol version of the cookies. The default version 0 (complies with the original Netscape specification); version 1 follows RFC 2109, but has not been widely supported. Setting Cookie cookies in your response war You can join the SET-Cookie response head with the AddCookie method of HttpservletResponse. Here is an example: cookie usercookie = new cookie ("User", "UID1234"); response.addcookie (userCookie); Read saved to the client to send cookies to the client, first create a cookie, then use AddCookie Send a SET-Cookie HTTP response. These contents have been described above in Top 2.1. The getCookies method that calls HTTPSERVLETREQUEST when reading cookies from the client. This method returns an array of cookie objects corresponding to content in the HTTP request header. After getting this array, it is generally used to access the individual elements in the loop, call GetName to check the names of each cookie until the target cookie is found. Then, the GetValue is then called to this target cookie, and other processing is performed according to the result. The above processing process often encounters, and provides a getCookieValue method for the convenience meter. Just give the cookie object array, the cookie name, and defaults, the getCookieValue method returns a cookie value that matches the specified name. If you can't find the specified cookie, return the default value. Several Cookie Tools Functions are a few tool functions. Although these functions are simple, it is useful when dealing with cookies. Getting a cookie value of the specified name This function is part of ServletUtilities.java. GetCookieValue sequentially accesses the various elements of the cookie object array via a loop, finds a cookie for specifying the name, if you find it, return the value of the cookie; otherwise, return the default value given in the parameter. GetCookieValue can simplify the extraction of the cookie value to a certain extent.

public static String getCookieValue (Cookie [] cookies, String cookieName, String defaultValue) {for (int i = 0; i

package hall; import java.io *;. import javax.servlet *;. import javax.servlet.http *;. import java.net *;. public class SearchEnginesFrontEnd extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie [] cookies = request.getCookies (); String searchString = ServletUtilities.getCookieValue (cookies, "searchString", "Java Programming"); String numResults = ServletUtilities.getCookieValue (cookies, "numResults", "10" ); String searchEngine = ServletUtilities.getCookieValue (cookies, "searchEngine", "google"); response.setContentType ( "text / html"); PrintWriter out = response.getWriter (); String title = "Searching the Web"; out .printutilities.headwithtitle (title) \N " "

searching the Web \n " "\N" "
\n" "
\N" "Search String: \ N"

\ ">
\ N" "Results to show per page: \n" "
\N " " \N" "Google | \N" " \N" "Infoseek | \N" " \N" "lycos | \N" "

Checked ("Hotbot", Searchengine) "> \N" "Hotbot \" "
\N" " \n" " \N" " \N" "\n" " \n" " \n");} prince string checked (String Name1 String name2) {if (name1.equals (name2)) Return ("Checked"); Else Return ("");}} SearchenginesFrontend servlet in front of CustomizedSearchengines.java Sead SearchenginesFrontend Servlet is sent to CustomizedSearchengines Servlet. In this case, in many ways, the example is similar to the example of the HTTP status code, distinguishably, in addition to constructing a URL for the search engine and sends a redirect response to the user, it is necessary to send a cookies that saves user data.

转载请注明原文地址:https://www.9cbs.com/read-127606.html

New Post(0)