Cookie是由服务器端生成并储存在浏览器客户端上的数据。在javaweb开发中Cookie被当做java对象在web服务器端创建,并由web服务器发送给特定浏览器客户端,并且WEB服务器可以向同一个浏览器客户端上同时发送多个Cookie,每一个Cookie对象都由name和value组成,name和value只能是字符串类型,浏览器接收到来自服务器的Cookie数据之后默认将其保存在浏览器缓存中(如果浏览器关闭,缓存消失,Cookie数据消失),只要浏览器不关闭,当我们下一次发送“特定”请求的时候,浏览器负责将Cookie数据发送给WEB服务器。我们还可以使用特殊的方法,将Cookie保存在客户端的硬盘上,永久性保存。这样关闭浏览器Cookie还是存在的,不会消失,比如:实现十天内自动登录。
Cookie cookie = new Cookie(String cookieName,String cookieValue);
cookie.setMaxAge(60 * 60 * 24 * 10); //10天内有效
如果这个有效时间 >0,则该Cookie对象发送给浏览器之后浏览器将其保存到硬盘文件中。
如果这个有效时间 <0,则该Cookie对象也是被保存在浏览器缓存中,待浏览器关闭Cookie消失。
如果这个有效时间 =0,则该Cookie从服务器端发过来的时候就已经是一个已过时的Cookie。
http://127.0.0.1:8080/hcz/getCookie
http://127.0.0.1:8080/hcz/getCookie(相同路径)
http://127.0.0.1:8080/hcz/xxxx(同目录)
http://127.0.0.1:8080/hcz/xxxx/xxxx/xxx(子目录)
http://127.0.0.1:8080/hcz/servlet/getCookie
http://127.0.0.1:8080/hcz/servlet/getCookie(相同路径)
http://127.0.0.1:8080/hcz/servlet/xxxxx(同目录)
http://127.0.0.1:8080/hcz/servlet/xxxxx/xxxx(子目录)
cookie.setPath("/hcz/king");
//从request对象中获取所有提交的Cookie
Cookie[] cookies = request.getCookies();
//遍历cookie数组取出所有的cookie对象
if(cookies != null){
for(Cookie cookie : cookies){
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
System.out.println(cookieName + "=" + cookieValue);
}
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>isLoginwelcome-file>
welcome-file-list>
<servlet-name>isLoginservlet-name>
<servlet-class>com.javaweb.servlet.CheckLoginStatusServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>isLoginservlet-name>
<url-pattern>/isLoginurl-pattern>
servlet-mapping>
<servlet>
<servlet-name>loginservlet-name>
<servlet-class>com.javaweb.servlet.LoginServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>loginservlet-name>
<url-pattern>/loginurl-pattern>
servlet-mapping>
web-app>
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
Cookie[] cookies = request.getCookies();
String username = null;
String password =null;
if (cookies!=null){
for(Cookie cookie:cookies){
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if ("username".equals(cookieName)){
username = cookieValue;
}else if ("password".equals(cookieName)){
password = cookieValue;
}
}
}
if (username != null && password != null){
//JDBC连接数据库验证用户名和密码
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean loginSuccess = false;
String realName = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","hcz","");
String sql = "select id,username,password,realname from t_user2 where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);//将username添加到第一个❓处
ps.setString(2,password);//将password添加到第二个❓处
rs = ps.executeQuery();
if (rs.next()){
loginSuccess = true;
realName = rs.getString("realname");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//判断用户是否登陆成功
if (loginSuccess){
//登录成功跳转到成功页面
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("");
out.print("");
out.print("欢迎页面 ");
out.print("");
out.print("");
out.print("欢迎");
out.print(realName);
out.print("访问");
out.print("");
out.print("");
}else {
//登录失败跳转到失败页面
response.sendRedirect(request.getContextPath() + "/login_error.html");
}
}else {
//跳转到登陆页面
response.sendRedirect(request.getContextPath()+"/login.html");
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
<link href="admin_login.css" rel="stylesheet" type="text/css" />
head>
<body>
<div class="admin_login_wrap">
<h1 align="center">登录管理h1>
<div class="adming_login_border">
<div class="admin_input">
<form action="/hcz20/login" method="post">
<ul class="admin_items">
<li>
<label for="user">用户名:label>
<input type="text" name="username" id="user" size="40" class="admin_input_style" />
li>
<li>
<label for="pwd">密码:label>
<input type="password" name="password" id="pwd" size="40" class="admin_input_style" />
li>
<li>
<input type="checkbox" name="tenDayAutoLoginFlag" value="ok">十天内免登录
li>
<li>
<input type="submit" tabindex="3" value="登录" class="btn btn-primary" />
li>
ul>
form>
div>
div>
<p class="admin_copyright"><a tabindex="5" href="#">返回首页a> © 2020 Powered by <a href="http://jscss.me" target="_blank">有主机上线a>p>
div>
body>
html>
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
request.setCharacterEncoding("UTF-8");//是设置从request中取得的值或从数据库中取出的值
response.setContentType("text/html;charset=UTF-8");//是设置页面中为中文编码
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean loginSuccess = false;//登录成功的标记
String realName = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","hcz","");
String sql = "select id,username,password,realname from t_user2 where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);//将username添加到第一个❓处
ps.setString(2,password);//将password添加到第二个❓处
rs = ps.executeQuery();//把数据库响应的查询结果存放在ResultSet类对象中供使用
if (rs.next()){
loginSuccess = true;
realName = rs.getString("realname");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
String tenDayAutoLoginFlag = request.getParameter("tenDayAutoLoginFlag");
if ("ok".equals(tenDayAutoLoginFlag)){
//创建Cookie对象
Cookie cookie1 = new Cookie("username",username);
Cookie cookie2 = new Cookie("password",password);
//设置有效时间--->10天
cookie1.setMaxAge(60 * 60 * 24 * 10);
cookie2.setMaxAge(60 * 60 * 24 * 10);
//设置关联路径
cookie1.setPath(request.getContextPath());
cookie2.setPath(request.getContextPath());
//发送Cookie给浏览器
response.addCookie(cookie1);
response.addCookie(cookie2);
}
<body>
登录失败,用户名不存在或者密码错误,请<a href="/hcz20/login.html">重新登录a>
body>
注意:十天内免登录完整代码可到个人博客资料下载里面下载