Servlet笔记9--Cookie
Cookie:
使用Cookie机制实现十天内免登陆:
Servlet程序:
package com.bjpowernode.javaweb.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 检查登录时服务器是否接收到前端页面发送的Cookie,
* 若收到则直接登录,登录成功则跳转到成功页面,登录失败则跳转到失败页面,
* 若没收到则再跳转到登录页面
* @author qjj
*
*/
public class CheckLoginStatusServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从request中获取所有的Cookie
Cookie[] cookies = request.getCookies();
String username = null;
String password = null;
if(cookies != null){
//遍历Cookie
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){
//接收到Cookie
//连接数据库验证用户名和密码
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/test1", "root", "248xiaohai");
String sql = "select id,username,password,realname from t_user where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, 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){
//这里的成功页面已响应的方式发送到前端,是因为有动态参数realname的存在,之后学了JSP就不用这么写了
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>欢迎页面</title>");
out.print("</head>");
out.print("<body>");
out.print("欢迎");
out.print(realName);
out.print("访问");
out.print("</body>");
out.print("</html>");
}else{
response.sendRedirect(request.getContextPath() + "/login_error.html");
}
}else{
//没接收到Cookie,则跳转到登录页面
response.sendRedirect(request.getContextPath() + "/login.html");
}
} }
package com.bjpowernode.javaweb.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 登录页面的响应,登录成功先判断是否选择十天内免登录,若选择则先向浏览器发送Cookie,
* 然后跳转到成功页面
* 若登录失败,则跳转到失败页面
* @author qjj
*
*/
public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符编码方式
request.setCharacterEncoding("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/test1", "root", "248xiaohai");
String sql = "select id,username,password,realname from t_user where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, 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){
//登陆成功之后,获取用户是否选择了十天内免登陆
String tenDayAutoLoginFlag = request.getParameter("tenDayAutoLoginFlag");
if("ok".equals(tenDayAutoLoginFlag)){
//创建Cookie对象
Cookie cookie1 = new Cookie("username",username);
Cookie cookie2 = new Cookie("password",password);
//设置有效时间
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);
} response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>欢迎页面</title>");
out.print("</head>");
out.print("<body>");
out.print("欢迎");
out.print(realName);
out.print("访问");
out.print("</body>");
out.print("</html>");
}else{
response.sendRedirect(request.getContextPath() + "/login_error.html");
}
}
}
前端HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>登录页面</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <form action="/prj-servlet-20/login" method="post">
用户名
<input type="text" name="username">
<br>
密码
<input type="password" name="password">
<br>
<input type="checkbox" name="tenDayAutoLoginFlag" value="ok">十天内免登陆<br>
<input type="submit" value="登录">
</form> </body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>登录失败</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> 登录失败,用户名不存在或者密码错误,请<a href="/prj-servlet-20/login.html">重新登录</a> </body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 设置isLogin为欢迎页面 -->
<welcome-file-list>
<welcome-file>isLogin</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.bjpowernode.javaweb.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>isLogin</servlet-name>
<servlet-class>com.bjpowernode.javaweb.servlet.CheckLoginStatusServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>isLogin</servlet-name>
<url-pattern>/isLogin</url-pattern>
</servlet-mapping>
</web-app>
Servlet笔记9--Cookie的更多相关文章
- servlet种下cookie后如何携带cookie继续往下走
事情是这样的,今天我在应用1里面手动种下了一个cookie,然后它会发接着访问应用2,因为是我手动setCookie,所以它还没来得及携带cookie继续前往下一站,于是,apple pen,炸了. ...
- IT兄弟连 JavaWeb教程 Servlet会话跟踪 Cookie常用方法
以下是在Servlet中操作Cookie时可使用的有用的方法列表 ● public void setDomain(String pattern) 该方法设置cookie适用的域,例如 itxdl.c ...
- Servlet(3):Cookie
概念 Cookie是存储在客户端计算机上的文本文件,并保留了各种跟踪信息.Java Servlet支持HTTP Cookie. 识别返回用户包括三个步骤: (1) 服务器脚本向浏览器发送一组Cooki ...
- 4、Servlet中的Cookie 用于存储 web 页面的用户信息。
Servlet Cookie 处理 Cookie 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息.Java Servlet 显然支持 HTTP Cookie. 识别返回用户包括三个步骤: 服务 ...
- Servlet 笔记-Cookie 处理
Cookie 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息. 识别返回用户包括三个步骤: 服务器脚本向浏览器发送一组 Cookie.例如:姓名.年龄或识别号码等. 浏览器将这些信息存储在本地 ...
- servlet中的cookie
cookie的机制是:从客户端(浏览器)发送请求到服务器,然后服务器把接受的信息回写到客户端,这个信息在客户端跟服务器之间进行交互. 下面是一个创建cookie的小案例 //如何创建cookie pa ...
- Servlet课程0426(十)Servlet如何删除cookie
//如何删除Cookie案例 package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class Coo ...
- Servlet课程0426(九)Servlet服务器端创建Cookie和客户端读取Cookie
服务器端创建Cookie: Win7默认Cookie位置 C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Cookies Cookie ...
- servlet方式通过Cookie记住登录时的用户名和密码
1.建立web工程 2.创建存放servlet的包 3右键包,新建servlet,路径将前面的servlet去掉,只需要doPost和doGet方法 编写servlet CookieServlet.j ...
- servlet笔记
开发servlet有三种方法: (1) 实现 Servlet接口 (2) 通过继承 GenericServlet (3) 通过继承 HttpServlet get提交和post提交的 ...
随机推荐
- Notes of Daily Scrum Meeting(12.20)
今天是周六,大家空余的时间还是挺多的,也都主动完成了当天工作,最后由于我的失误,在晚上12点 之前没有把进度签入进TFS里面,所以周六的燃尽图是错误的,我把进度加进周日,总的进度会在周日的燃尽 图里面 ...
- 【Alpha】功能规格说明书
更新说明:从用户需求分析中剥离有关用户场景分析部分,加入功能规格说明书. Github地址:https://github.com/buaase/Phylab-Web/blob/master/docs/ ...
- 评审other's意见
评审意见 1.组 a.界面不友好 b.没连数据库 2.组 a.没连数据库 b.无智能匹配当前时间 3.组 a.基本功能实现 b.界面未优化 4.组 ourselves 5.组 a.各反面较为完善 6. ...
- C++:多态浅析
1.多态 在C++中由两种多态性: • 编译时的多态性:通过函数的重载和运算符的重载来实现的 • 运行时的多态性:通过类继承关系和虚函数来实现的 特别注意: a.运行时的多态性是指程序执行前,无法根据 ...
- 嵌入AppBar并且带搜索建议的搜索框(Android)
先看结果: 相关的官方文档在这里:Creating a Search Interface Android官方提供了两种方式: 弹出一个Dialog,覆盖当前的Activity界面 在AppBar中扩展 ...
- Linux命令(十六) 压缩或解压缩文件和目录 zip unzip
目录 1.命令简介 2.常用参数介绍 3.实例 4.直达底部 命令简介 zip 是 Linux 系统下广泛使用的压缩程序,文件压缩后扩展名为 ".zip". zip 命令用来将文件 ...
- Semantic Versioning Specification & 语义化版本
Semantic Versioning Specification & 语义化版本 Semantic Versioning Specification http://semver.org 16 ...
- emoji & click copy
emoji & click copy document.execCommand("copy"); https://clipboardjs.com/ https://www. ...
- ELK环境配置
一.安装java环境 1.下载jre并安装,安装过程中没有什么特殊的,一直默认下一步即可. 2.配置环境变量 其中变量值为我们安装的jre的路径 二.安装elasticsearch 1.下载es安装包 ...
- java学习三 小数默认为double
前++,后++在独立运算时候 直接计算出值 当后加加和减减和其他代码在一行的时候先使用加加和减减之前的值, 如果不在同一行,后面的一行就会得到加加或减减后的值 &&是逻辑运算符,逻辑运 ...