会话技术( Cookie ,Session)

时间:2023-03-09 07:01:52
会话技术( Cookie  ,Session)

会话技术:
    会话:浏览器访问服务器端,发送多次请求,接受多次响应。直到有一方断开连接。会话结束。
    
    解决问题:可以使用会话技术,在一次会话的多次请求之间共享数据。
        
    分类:
        客户端会话技术    Cookie
        服务器端会话技术    Session

客户端会话技术:Cookie 小饼干的意思
会话技术( Cookie  ,Session)
        服务器端不需要管理,方便。但是不安全。
        
        原理:
            1.客户端第一次请求服务器端,服务器作出响应时,会发送set-cookie头,携带需要共享的数据
            2.当客户端接受到这个响应,会将数据存储在客户端
            3.当客户端再次请求服务器端时,会通过cookie请求头携带着存储的数据。
            4.服务器接受带请求,会获取客户端携带的数据。
        
        Java代码实现:
            1.发送cookie
                //1.创建Cookie对象。
                Cookie c = new Cookie("name","zhangsan");
                //2.通过response发送cookie
                response.addCookie(c);
                
            2.接收cookie
                //1.获取所有cookie数组
                Cookie[] cs = request.getCookies();
                //2.遍历数组
                if(cs != null){
                    for (Cookie c : cs) {
                        //获取cookie的名称
                        String name = c.getName();
                        //判断名称,得到目标cookie
                        if("name".equals(name)){
                            //获取值
                            String value = c.getValue();
                            System.out.println(name+":"+value);
                        }
                    }
                }
        
        Cookie的细节:
            1.默认情况下,cookie保存在客户端浏览器内存中。
              需要将数据持久化存储在客户端的硬盘上。
              设置cookie的存活时间。setMaxAge(int s);
            
            2.Cookie是不支持中文数据的。如果要想存储中文数据。需要转码。
                URL编码
        
        功能:记住用户名和密码

服务器端会话技术:Session  主菜的意思
        会话技术( Cookie  ,Session)
        服务器端需要管理数据,麻烦,但是安全。
        
        原理:
            1.客户端访问服务器端,在服务器端的一个对象(Session)中存储了数据
            2.服务器给客户端作出响应时,会自动将session对象的id通过响应头 set-cookie:jsessionid=xxx 发送到客户端
            3.客户端接受到响应,将头对应的值存储到客户端
            4.客户端再次请求时,会携带着请求头 cookie:jsessionid=xxx.
            5.服务器接受到请求,通过jsessionid的值,找到对应的session对象。就可以获取对象中存储的数据了。
            
            Session技术依赖于cookie。
        
        获取session
            HttpSession session = request.getSession();
        
        域对象:
            setAttribute():
            getAttribute():
            removeAttribute():
        
        session细节:
            1.客户端关闭了,两次session一样吗?
                不一样。因为客户端浏览器内存释放了,jsessionid没了。
              服务器关闭了,两次session一样吗?
                不一样。因为服务器内存释放了,session对象没了。
                    session的钝化:
                        当服务器正常关闭时,会将session对象写入到服务器的硬盘上。
                    session的活化:
                        当服务器正常启动时,会将session文件还原为session对象
        
            2.session对象的销毁
                1.session超时
                    <session-config>
                        <session-timeout>30</session-timeout>
                    </session-config>
                
                2.invalidate():session销毁
                
                3.服务器关闭。
                
            3.session依赖于cookie,如果客户端禁用了cookie,那么session该咋办?
                URL重写。

4.getSession方法的重载:
                boolean:
                    true:默认值
                        通过id查找session,如果没找到,新创建一个
                    false:
                        通过id查找session,如果没找到,返回null
                        第一次创建一个新的对象

  代码演示:

 package cookie;

 import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { private static final long serialVersionUID = -4372317815130787297L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//1.获取验证码
String checkCode = request.getParameter("checkCode");
//2.获取生成的验证码
HttpSession session = request.getSession();
String checkCode_pro = (String) session.getAttribute("checkCode_pro"); //1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//3.操作数据库,获取数据库连接
//4.定义sql
//5.获取pstmt对象
PreparedStatement pstmt = JDBCUtils.getConnection().prepareStatement("select * from user where username = ? and userpassword = ?");
//6.设置参数
pstmt.setString(1, username);
pstmt.setString(2, password);
//7.执行sql
//8.验证,判断
//判断验证码是否正确
if(checkCode_pro.equalsIgnoreCase(checkCode)){
//正确
//注册 或 登录
session.setAttribute("regist_msg", "验证码正确");
if(pstmt.executeQuery().next()){
//登陆成功
request.setAttribute("username", username);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
//登陆失败
request.setAttribute("msg", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}else{
//错误
session.setAttribute("regist_msg", "验证码错误");
response.sendRedirect("/colloquy/login.jsp");
//将session中存储的验证码清空
session.removeAttribute("checkCode_pro");
}
} catch (SQLException e) {
e.printStackTrace();
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
 package cookie;

 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 RemServlet extends HttpServlet { private static final long serialVersionUID = -3477344209817695234L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.获取用户名和密码,复选框
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.判断用户名和密码是否正确
if("zhangsan".equals(username) && "123".equals(password)){
//登陆成功
if(request.getParameter("rem") != null){
//记住密码
//1.创建cookie
Cookie c_username = new Cookie("username", username);
Cookie c_password = new Cookie("password", password);
//2.设置存活时间
c_username.setMaxAge(60 * 60 * 24 * 7);
c_password.setMaxAge(60 * 60 * 24 * 7);
//3.发送cookie
response.addCookie(c_username);
response.addCookie(c_password);
}
request.setAttribute("username", username);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
//登陆失败
request.setAttribute("msg", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
 package cookie;

 import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random; import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 生成验证码
* @author rongsnow
*
*/
public class CheckCodeServlet extends HttpServlet { private static final long serialVersionUID = 8583894656985684165L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { int width = 100;
int height = 50;
//1.创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.装饰图片
//2.1设置背景色
//2.1.1 获取画笔对象
Graphics g = image.getGraphics();
//2.2.2 设置画笔的颜色
g.setColor(Color.pink);
//2.2.3 填充背景色
g.fillRect(0, 0, width, height); //2.2 画边框
g.setColor(Color.GREEN);
g.drawRect(0, 0, width - 1, height - 1); //2.3 写入验证码
g.setColor(Color.RED); String msg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random ran = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(msg.length());//随机生成角标
String s = String.valueOf(msg.charAt(index));
sb.append(s); g.drawString(s, width/5 * i, height/2);
}
String checkCode_pro = sb.toString();
//将生成的验证码 存入session
request.getSession().setAttribute("checkCode_pro", checkCode_pro); //2.4画干扰线
g.setColor(Color.BLUE); for (int i = 0; i < 5; i++) {
//动态生成坐标点
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1, y1, x2, y2);
} //3.将图片数据 写入到 response输出流中
ImageIO.write(image, "jpg", response.getOutputStream());
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doGet(request, response);
}
}
 package cookie;

 import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* JDBC 工具类
* @author rongsnow
*
*/
public class JDBCUtils {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null; static{
/*
* 加载配置文件,为每一个值赋值
*/
try {
//1.创建properties对象
Properties pro = new Properties();
//获取配置文件的真实路径
//2.关联资源文件
pro.load(new FileReader(JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath()));
//3.获取数据
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driverClass = pro.getProperty("driverClass");
//4.注册驱动
Class.forName(driverClass); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} /**
* 获取数据库连接
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{ return DriverManager.getConnection(url, user, password);
} /**
* 释放资源
* @throws SQLException
*/
public static void close(Connection conn,Statement stmt,ResultSet rs) throws SQLException{
if(rs != null){//预防空指针异常
rs.close();
}
if(stmt != null){//预防空指针异常
stmt.close();
}
if(conn != null){//预防空指针异常
conn.close();
}
}
public static void close(Connection conn,Statement stmt) throws SQLException{
if(stmt != null){//预防空指针异常
stmt.close();
}
if(conn != null){//预防空指针异常
conn.close();
}
}
public static void close(Connection conn) throws SQLException{
if(conn != null){//预防空指针异常
conn.close();
}
}
}

  web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name> <servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>cookie.LoginServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>RemServlet</servlet-name>
<servlet-class>cookie.RemServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>checkcode</servlet-name>
<servlet-class>cookie.CheckCodeServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RemServlet</servlet-name>
<url-pattern>/remServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>checkcode</servlet-name>
<url-pattern>/checkCodeServlet</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

  jdbc.properties配置文件内容

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql:///mydb
user=root
password=123

login.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
<script type="text/javascript">
function changeImg(){
document.getElementById("img").src = "/colloquy/checkCodeServlet?time="+new Date().getTime();
}
function changeImg2(obj){
obj.src = "/colloquy/checkCodeServlet?time="+new Date().getTime();
}
</script>
</head>
<body>
<%
//1.获取所有cookie
Cookie[] cs = request.getCookies();
String username = "";
String password = "";
//2.遍历cookie数组
if(cs != null){
for(Cookie c : cs){
//获取名称
String name = c.getName();
if("username".equals(name)){
username = c.getValue();
}
if("password".equals(name)){
password = c.getValue();
}
}
}
%> <form action="/colloquy/loginServlet" method="post">
<table align="center" bgcolor="pink">
<caption>用户登陆</caption>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" name="checkCode"></td>
<td><img src="/colloquy/checkCodeServlet" id="img" onclick="changeImg2(this);"></td>
<td><a href="javascript:void(0);" onclick="changeImg();">看不清?</a><br></td>
<tr>
<tr>
<td>记住密码</td>
<td><input type="checkbox" name="rem"></td>
</tr>
<tr>
<td colspan="2" align="center" ><input type="submit" value="登陆"></td>
</tr>
</table>
</form>
<div align="center" style="color:red;"><%=request.getAttribute("msg")==null ? "" : request.getAttribute("msg") %></div>
<div align="center" style="color:#FF0000;"><%=session.getAttribute("regist_msg")==null ? "" : session.getAttribute("regist_msg") %></div>
</body>
</html>
success.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'success.jsp' starting page</title>
</head>
<body> <%=
request.getAttribute("username")
%>,欢迎您! </body>
</html>

所使用的MySQL语句

 -- 创建用户信息表 user,并指定主键且自增长
CREATE TABLE USER(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
userpassword VARCHAR(32)
); -- 查询所有列
SELECT * FROM USER; -- 添加数据
INSERT INTO USER(username,userpassword) VALUE ('zhangsan','');
INSERT INTO USER(username,userpassword) VALUE ('lisi','');
INSERT INTO USER(username,userpassword) VALUE ('wangwu','');
INSERT INTO USER(username,userpassword) VALUE ('zhaoliu','');
INSERT INTO USER(username,userpassword) VALUE ('sisi','');