Use of Java cookies

Source: Internet
Author: User
Tags stub

Transferred from: http://www.blogjava.net/tscfengkui/archive/2011/01/21/343341.html

Thank you, let little white understand the reason

Use of Java cookies

What is 1.cookie?

Cookies are a very common technique used in Web applications to store certain user information.

The role of 2.cookie?

When the user logs on the user's information in the cookie, the user in a certain period of time to log in without the need to enter a user name and password to jump directly to the next interface.

3. Setting cookies

Cookie cookie = new Cookie ("Key", "value");

Cookie.setmaxage (SAVETIME*24*60*60);

The lifetime default time is seconds, and if it is set to a negative value, the browser process cookie (saved in memory) is disabled by closing the browser.

Cookie.setpath ("/test/test2");

Sets the cookie path, not set to the current path (for the servlet, the Url-pattern path portion of the servlet configured for Request.getcontextpath () + Web. xml).

Response.addcookie (cookie);

4. Read cookies

The method can read the current path and all cookie objects of the "Direct parent Path", and returns null if there are no cookies. If you set the path using this method there is no value.

cookie[] cookies = request.getcookies ();

5. Delete Cookies

Cookie cookie = new Cookie ("key", null);

Cookie.setmaxage (0);

Set to 0 to delete the cookie immediately;

Cookie.setpath ("/test/test2");

Deletes the cookie on the specified path, without setting the path, by default deleting the current path cookie;

Response.addcookie (cookie);

Here is an example, this is a simulation of 126 mailbox landing small function. Create a project named Autologinfilter, with the following package structure:

Project has three Java files, two JSPs and an HTML,

The Checklogin.java code is as follows:

public class Checklogin{

public static Boolean login (string username, string password){
if ("admin". Equals (username) && "123456". Equals (password)) {
return true;
} else {
return false;
}
}

}

The Indexfilter.java code is as follows:

Package com.bx.course;
/**
* Filter can implement the filtering and redirection of requests, that is, you can manipulate the request and Response,session objects, Listner can only hear the properties of the above object modification.
*/

Import java.io.IOException;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Indexfilter implements Filter{
public void Destroy (){
TODO auto-generated Method Stub
}
public void DoFilter (ServletRequest arg0, Servletresponse arg1,
Filterchain arg2) throws IOException, Servletexception{
SYSTEM.OUT.PRINTLN ("Every request pass here haha");
HttpServletRequest request = (httpservletrequest) arg0;
HttpServletResponse response = (httpservletresponse) arg1;
cookie[] cookies = request.getcookies ();
Cookie cookie = new Cookie ("user", null);
Cookie.setmaxage (0);
Response.addcookie (cookie);
string[] cooks = null;
String username = null;
String password = null;
if (cookie = null){
for (Cookie coo:cookies){
String AA = Coo.getvalue ();
System.out.println ("1");
Cooks = aa.split ("= =");
if (cooks.length = = 2){
System.out.println (Cooks[0]+cooks[1]);
Username = Cooks[0];
Password = cooks[1];
}
}
}
SYSTEM.OUT.PRINTLN ("Cookie username |" + username);
SYSTEM.OUT.PRINTLN ("Cookie password |" + password);
if (Checklogin.login (username, password)){
SYSTEM.ERR.PRINTLN ("Check successfully cookie data");
Request.getsession (). SetAttribute ("username", username);
Request.getrequestdispatcher ("/main126.jsp"). Forward (request, response);
}else{
Arg2.dofilter (Request,response);
}
}
public void init (Filterconfig arg0) throws Servletexception {
TODO auto-generated Method Stub
}
}

The Loginservlet.java code is as follows:

Package com.bx.course;
Import java.io.IOException;

Import javax.servlet.ServletException;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Loginservlet extends HttpServlet{
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException{
This.dopost (request, response);
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException{
String Username=request.getparameter ("username");
String password=request.getparameter ("password");
String savetime=request.getparameter ("Savetime");
System.out.println ("usrename" +username+ "password" +password);
if (Checklogin.login (username, password)){
if (null!=savetime){
int Savetime=integer.parseint (savetime);//The form values accepted here are calculated for days
int seconds=savetime*24*60*60;
Cookie cookie = new Cookie ("User", username+ "= =" +password);
Cookie.setmaxage (seconds);
Response.addcookie (cookie);
}
Request.setattribute ("username", username);
Request.getrequestdispatcher ("/main126.jsp"). Forward (Request,response);
}else{
Request.getrequestdispatcher ("/failure.jsp"). Forward (Request,response);
}
}
}

The Web. XML configuration file code is as follows:

<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.bx.course.IndexFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/login.html</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.bx.course.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>

<welcome-file-list>
<welcome-file>main126.jsp</welcome-file>
</welcome-file-list>

The login.html code is as follows:

<body>
<form action= "Login.do" >
126 Email Login <br/><br/>
User name: <input type= "text" name= "username" ><br/>
Password: <input type= "text" name= "password" ><br/>
<select name= "Savetime" >
<option value= "366" > One year </option>
<option value= "183" > Half year </option>
<option value= "> One month" </option>
<option value= "7" > One week </option>
</select><br/>
<input type= "Submit" value= "Login"/>
</form>
</body>

The main126.jsp code is as follows:

<title> Test cookie</title>
<body>
</body>

The failure.jsp code is as follows:

<body>
Login Failure <br>
</body>

Operating effect:

Enter http://localhost:8080/LoginFilter/login.html in the IE Address bar

The following interface is displayed:

Enter user name: admin password: 123456 Select Save time, then click Login, you will enter the following interface:

In the save time again in the IE Address bar type: http://localhost:8080/LoginFilter/login.html

will be directly into the login success screen. If the user name or password is incorrect, the following interface will be entered:

Use of Java cookies

Related Article

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.