目录
一、会话跟踪概述
二、Cookie
1、cookie的基本使用
@WebServlet("/cookie")
public class ServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//发送cookie
//1、创建cookie对象
Cookie cookie = new Cookie("zhangsan","23");
//2、发送cookie,response
resp.addCookie(cookie);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收cookie
//1、获取cookie对象数组
Cookie[] cookies = req.getCookies();
//2、遍历cookie对象数组,获取需要的cookie数据
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("zhangsan".equals(name)){
String value = cookie.getValue();
System.out.println(name + ":" + value );
break;
}
}
2、cookie原理
Cookie的实现是基于HTTP协议,发送cookie时,响应头中会存放发送的cookie数据,所有的cookie会以键值对形式存放在响应头中,当浏览器在请求服务器资源时,会通过请求头cookie,把cookie的数据携带到服务器的资源中来获取请求数据
3、cookie的使用细节
对于存储中文可以使用URL编码、解码
@WebServlet("/cookieE")
public class ServletDemoEncoder extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//发送cookie
//1、创建cookie对象
String value = "张三";
//URL编码
value = URLEncoder.encode(value, "UTF-8");
System.out.println("存储数据:" + value);
Cookie cookie = new Cookie("username",value);
//设置存活时间 一个星期
cookie.setMaxAge(60*60*24*7);
//2、发送cookie,response
resp.addCookie(cookie);
}
@WebServlet("/cookieD")
public class ServletDemoDecoder extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收cookie
//1、获取cookie对象数组
Cookie[] cookies = req.getCookies();
//2、遍历cookie对象数组,获取需要的cookie数据
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("username".equals(name)){
//对接收到的cookie值进行解码
String value = cookie.getValue();
value = URLDecoder.decode(value, "UTF-8");
System.out.println(name + ":" + value );
break;
}
}
}
三、Session
1、Session的基本使用
@WebServlet("/demo1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建Session,存储数据
HttpSession session = req.getSession();
session.setAttribute("username","zhangsan");
}
@WebServlet("/demo2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取Session数据
HttpSession session = request.getSession();
Object username = session.getAttribute("username");
System.out.println(username);
}
2、Session的原理
当客户端浏览器发送请求1,获取session时,第一次执行获取到的session对象会自动添加一个唯一标识,假设id为10,第一次执行时会对sessio对象封装数据,数据封装结束后,Tomcat会对请求1做出响应,当Tomcat发现这个请求1中获取了session,它会将这个session的id当作一个cookie发送给客户端浏览器,此时客户端浏览器就会接收到这个响应头,并将这个响应头存储到客户端浏览器的内存中,当这个客户端浏览器下一次发送请求2时,就会携带这个cookie头去访问另一个servlet,根据这个cookie头携带的id值,就会在Tomcat的内存中寻找是否有这个id值,如果没有就创建一个,如果存在就直接使用这个session对象,这样保证了在一次会话的两次请求之间获取到的session对象是同一个
3、Session的使用细节
四、Cookie和Session的区别
五、登陆注册案例
1、用户登录
1、Dao/Mapper层
public interface UserMapper {
//根据用户名和密码查询用户对象
User select(@Param("username") String username, @Param("password") String password);
<!--根据用户名和密码登录-->
<select id="select" resultMap="userResultMap">
select * from login where user_name=#{username} and password=#{password};
</select>
2、Service层
public static User selectUser(String username,String password){
//1、加载mybatis核心配置文件获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2、开启SqlSession对象
//SqlSession不能写在工具类,因为SqlSession代表用户与数据库的连接,如果放在工具类,则所有用户共用同一个连接
//这样无法管理事务,使多个用户之间产生影响
SqlSession sqlSession = sqlSessionFactory.openSession();
//3、获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//4、执行接口方法(执行SQL语句)
User user = userMapper.select(username,password);
//5、释放资源
sqlSession.close();
return user;
}
3、Web层
@WebServlet("/login")
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = UserService.selectUser(username, password);
//如果查询到用户就跳转到商品页面
if (user != null){
//使用session共享数据,保证安全性
HttpSession session = req.getSession();
session.setAttribute("user",user);
//页面跳转
String contextPath = req.getContextPath();
resp.sendRedirect(contextPath+"/select");
}else {
//如果没有查询到该账户跳转到登录失败页面
//将用户信息存储到request域中
req.setAttribute("login_msg","用户名或密码错误");
//将信息转发回登陆页面
req.getRequestDispatcher("/html/index.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2、记住密码
@WebServlet("/login")
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
String remember = req.getParameter("remember");
User user = UserService.selectUser(username, password);
//如果查询到用户就跳转到商品页面
if (user != null){
//是否勾选记住密码
if ("1".equals(remember)){
//勾选了开始存储cookie
//创建cookie
Cookie username_cookie = new Cookie("username",username);
Cookie password_cookie = new Cookie("password",password);
username_cookie.setMaxAge(60*60*24);
password_cookie.setMaxAge(60*60*24);
//发送cookie
resp.addCookie(username_cookie);
resp.addCookie(password_cookie);
}
//使用session共享数据,保证安全性
HttpSession session = req.getSession();
session.setAttribute("user",user);
//页面跳转
String contextPath = req.getContextPath();
resp.sendRedirect(contextPath+"/select");
}else {
//如果没有查询到该账户跳转到登录失败页面
//将用户信息存储到request域中
req.setAttribute("login_msg","用户名或密码错误");
//将信息转发回登陆页面
req.getRequestDispatcher("/html/index.jsp").forward(req,resp);
}
}
<tr>
<td class="name">Username</td>
<td class="inputs">
<%--cookie.键名称.value--%>
<input name="username" type="text" id="username" value="${cookie.username.value}">
</td>
</tr>
<tr>
<td class="name">Password</td>
<td class="inputs">
<input name="password" type="password" id="password" value="${cookie.password.value}">
</td>
</tr>
3、注册功能
1、Dao/Mapper层
public interface UserMapper {
//根据用户名和密码查询用户对象
User select(@Param("username") String username, @Param("password") String password);
//注册用户
int add(User user);
//根据用户名查找是否存在
User selectByName(@Param("username") String username);
}
<!--用户注册-->
<insert id="add" >
insert into login(user_name,password,tel) values(#{username},#{password},#{tel});
</insert>
<!--根据用户名判断账户是否存在-->
<select id="selectByName" resultMap="userResultMap">
select * from login where user_name=#{username};
</select>
2、Service层
public static boolean add(User user){
//1、加载mybatis核心配置文件获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2、开启SqlSession对象
//SqlSession不能写在工具类,因为SqlSession代表用户与数据库的连接,如果放在工具类,则所有用户共用同一个连接
//这样无法管理事务,使多个用户之间产生影响
SqlSession sqlSession = sqlSessionFactory.openSession();
//3、获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//先检查账户是否被注册
//获取用户名
String username = user.getUsername();
//根据用户名判断账户是否存在
User user1 = userMapper.selectByName(username);
//如果用户名不存在
if (user1 == null){
//不存在就添加用户
userMapper.add(user);
sqlSession.commit();
sqlSession.close();
/*return true;*/
}/*else {
return false;
}*/
//增强逻辑
return user1 == null;
}
3、Web层
@WebServlet("/addUser")
public class AddUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、接收用户名、密码和手机号
String username = req.getParameter("username");
String password = req.getParameter("password");
String tel = req.getParameter("tel");
User user = new User(username, password, tel);
//调用方法查看用户名是否被注册
boolean flag = UserService.add(user);
if (flag){
//没有被注册,跳转到登陆页面
req.setAttribute("register_msg","注册成功请登录");
req.getRequestDispatcher("/html/index.jsp").forward(req,resp);
}else {
//注册失败,已被注册
req.setAttribute("register_msg","注册失败,账号已存在");
req.getRequestDispatcher("/html/login.jsp").forward(req,resp);
}
}
4、生成验证码
通过验证码生成工具类生成验证码输出到页面
@WebServlet("/check")
public class CheckServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//使用方法
//respose文档输出流,直接输出到页面
ServletOutputStream os = resp.getOutputStream();
String checkCode = CheckCodeUtils.outputVerifyImage(120, 50, os, 4);
req.setAttribute("checkCode",checkCode);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
图片使用Servlet接收
<tr>
<td class="name">验证码</td>
<td class="inputs">
<input name="check" type="text" id="check" placeholder="请输入验证码" style="width: 5vw;">
<img class="check" id="checkimg" src="/jspcase/check" >
<span ><a class="checkother" href="#" id="checks" >换一张</a></span>
<br>
</td>
</tr>
添加JS使点击图片切换验证码
var changeImg = document.getElementById("checks");
changeImg.onclick = checkCode;
function checkCode() {
//由于浏览器缓存问题,要在更换的路径下添加参数才能展示新的验证码图片,添加时间毫秒值就可以不断刷新
document.getElementById("checkimg").src ="/jspcase/check?"+ new Date().getMilliseconds();
}
//点击图片刷新
document.getElementById("checkimg").onclick = function(){
document.getElementById("checkimg").src ="/jspcase/check?"+ new Date().getMilliseconds();
}
5、校验验证码
@WebServlet("/check")
public class CheckServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//使用方法
//respose文档输出流,直接输出到页面
ServletOutputStream os = resp.getOutputStream();
String checkCode = CheckCodeUtils.outputVerifyImage(120, 50, os, 4);
//存Session
HttpSession session = req.getSession();
session.setAttribute("checkCode",checkCode);
}
@WebServlet("/addUser")
//从Session获取生成的验证码
HttpSession session = req.getSession();
String checkCode = (String) session.getAttribute("checkCode");
//先判断验证码是否正确
//忽略大小写比较 equalsIgnoreCase
if (!checkCode.equalsIgnoreCase(check)) {
//验证码校验失败
req.setAttribute("register_msg","验证码校验失败");
req.getRequestDispatcher("/html/login.jsp").forward(req,resp);
return;
}
//校验成功,向下判断