1.Cookie
1.1.什么是Cookie?
1、Cookie翻译过来是饼干的意思。
2、Cookie是服务器通知客户端保存键值对的一种技术。
3、客户端有了Cookie后,每次请求都发送给服务器。
4、每个Cookie的大小不能超过4kb。
1.2.如何创建Cookie
Servlet程序中的代码:
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.创建cookie对象
Cookie cookie = new Cookie("key1", "cookie1");
//2.通知客户端保存cookie
resp.addCookie(cookie);
resp.getWriter().write("cookie创建成功!");
}
1.3.服务器如何获取Cookie
服务器获取客户端的Cookie只需要一行代码:req.getCookies():Cookie[]
Cookie的工具类:
package com.tedu.util;
import javax.servlet.http.Cookie;
/**
* @author: zyy
* @date: 2021/6/17 10:42
* @description: TODO
* @version: 1.0
* @描述:
**/
public class CookieUtils {
public static Cookie findCookie(String name,Cookie[] cookies) {
if (name == null || cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cook:cookies){
if (name.equals(cook.getName())){
return cook;
}
}
return null;
}
}
Servlet程序中的代码:
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cook : cookies){
resp.getWriter().write("cookie["+cook.getName()+"]=value["+cook.getValue()+"]<br>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
}
1.4.Cookie值的修改
方案一:
1、先创建一个要修改的同名(指的就是key)的Cookie对象
2、在构造器,同时赋于新的Cookie值。
3、调用response.addCookie(Cookie);
//方案1:县创建一个要修改的相同名字的cookie对象
Cookie cookie = new Cookie("key1","newValue1");
//2.在构造器,同时赋予新的cookie值
//3.调用response.addCookie(Cookie)
resp.addCookie(cookie);
方案二:
1、先查找到需要修改的Cookie对象
2、调用setValue()方法赋于新的Cookie值。
3、调用response.addCookie()通知客户端保存修改。
//方案二
/**
* 1.先查找需要修改的Cookie对象
* 2.调用setValue()方法赋于新的Cookie值
* 3.调用response.addCookie()通知客户端保存修改
*/
Cookie cookie1 = CookieUtils.findCookie("key2",req.getCookies());
if (cookie1!=null){
cookie1.setValue("newCookie2");
resp.addCookie(cookie1);
}
1.5.浏览器查看Cookie:
谷歌浏览器如何查看Cookie:
火狐浏览器如何查看Cookie:
1.6.Cookie生命控制
Cookie的生命控制指的是如何管理Cookie什么时候被销毁(删除)
setMaxAge()正数,表示在指定的秒数后过期负数,表示浏览器一关,Cookie就会被删除(默认值是-1)
零,表示马上删除Cookie
protected void timeCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* Cookie生命控制
* cookie的生命控制指的是如何管理Cookie什么时候被销毁(删除)
* setMaxAge(); 证书表示过了多长时间后过期 负数表示浏览器一关,cookie就会被删除(默认是-1)
* 零,表示马上删除Cookie
*/
Cookie cookie = new Cookie("defaultLife", "default");
cookie.setMaxAge(-1);//设置存活时间
}
protected void deleteCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//先找到删除的cookie
Cookie key1 = CookieUtils.findCookie("key1", req.getCookies());
if (key1 != null) {
//表示马上删除,不需要等到浏览器关闭
key1.setMaxAge(0);
resp.addCookie(key1);
}
}
1.7.Cookie有效路径Path的设置
Cookie的path属性可以有效的过滤哪些Cookie可以发送给服务器。哪些不发。
path属性是通过请求的地址来进行有效的过滤。
CookieA path=/工程路径
CookieB path=/工程路径/abc
请求地址如下:http://ip:port/工程路径/a.html
CookieA发送
CookieB不发送
http://ip:port/工程路径/abc/a.html
CookieA发送
CookieB发送
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1");
cookie.setPath(req.getContextPath()+"abc");
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有path路径的cookie");
}
1.8.Cookie练习---免输入用户名登录
login.jsp页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/6/17
Time: 14:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/11_Cook/loginServlet" method="post">
用户名:<input type="text" name="username" value="${cookie.username.value}"><br>
密码:<input type="password" name="password" ><br>
<input type="submit" value="登录">
</form>
</body>
</html>
LoginServlet程序:
package com.tedu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author: zyy
* @date: 2021/6/17 14:29
* @description: TODO
* @version: 1.0
* @描述:
**/
public class LoginServlet extends BaseServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if ("123456".equals(username)&&("123456".equals(password))){
//登陆成功
Cookie username1 = new Cookie("username", username);
username1.setMaxAge(60*60*24*7);
resp.addCookie(username1);
System.out.println("cookie中username保存成功");
Cookie password1 = new Cookie("password", password);
password1.setMaxAge(60*60*24*7);
resp.addCookie(password1);
System.out.println("cookie中password保存成功");
}else {
System.out.println("登录失败");
}
}
}
2.Session会话
2.1.什么是Session会话?
1、Session就一个接口(HttpSession)。
2、Session就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个Session会话。
4、Session会话中,我们经常用来保存用户登录之后的信息。
2.2.如何创建Session和获取(id号,是否为新)
如何创建和获取Session。它们的API是一样的。
request.getSession()
第一次调用是:创建Session会话
之后调用都是:获取前面创建好的Session会话对象。
isNew();判断到底是不是刚创建出来的(新的)
true表示刚创建
false表示获取之前创建
每个会话都有一个身份证号。也就是ID值。而且这个ID是唯一的。
getId()得到Session的会话id值。
2.3.Session域数据的存取
/**
* 往session中保存数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1","value1");
}
/**
* 从session中获取数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object key1 = req.getSession().getAttribute("key1");
resp.getWriter().write("从Session中获取key1的数据时"+key1);
}
2.4.Session生命周期控制
public void setMaxInactiveInterval(int interval)
设置Session的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。
值为正数的时候,设定Session的超时时长。负数表示永不超时(极少使用)
public int getMaxInactiveInterval()
获取Session的超时时间
public void invalidate()让当前Session会话马上超时无效。
Session默认的超时时长是多少!
Session默认的超时时间长为30分钟。因为在Tomcat服务器的配置文件web.xml中默认有以下的配置,它就表示配置了当前Tomcat服务器下所有的Session超时配置默认时长为:30分钟。<session-config>
<session-timeout>30</session-timeout>
</session-config>
如果说。你希望你的web工程,默认的Session的超时时长为其他时长。你可以在你自己的web.xml配置文件中做以上相同的配置。就可以修改你的web工程所有Seession的默认超时时长。
<!--设置session的超时时间-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
如果你想只修改个别Session的超时时长。就可以使用上面的API。setMaxInactiveInterval(intinterval)来进行单独的设置。
session.setMaxInactiveInterval(intinterval)单独设置超时时长。
Session超时的概念介绍:
示例代码:
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
//设置session3秒后超时
session.setMaxInactiveInterval(3);
resp.getWriter().write("当前session已设置为3秒超时");
}
2.5.浏览器和Session之间关联的技术内幕
Session技术,底层其实是基于Cookie技术来实现的。
3.表单重复提交之-----验证码
表单重复提交有三种常见的情况:
一:提交完表单。服务器使用请求转来进行页面跳转。这个时候,用户按下功能键F5,就会发起最后一次的请求。造成表单重复提交问题。解决方法:使用重定向来进行跳转
二:用户正常提交服务器,但是由于网络延迟等原因,迟迟未收到服务器的响应,这个时候,用户以为提交失败,就会着急,然后多点了几次提交操作,也会造成表单重复提交。
三:用户正常提交服务器。服务器也没有延迟,但是提交完成后,用户回退浏览器。重新提交。也会造成表单重复提交。
3.1.谷歌kaptcha图片验证码的使用
谷歌验证码kaptcha使用步骤如下:
1、导入谷歌验证码的jar包
kaptcha-2.3.2.jar
2.在web.xml中去配置用于生成验证码的Servlet程序
<servlet>
<servlet-name>KaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KaptchaServlet</servlet-name>
<url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>
3.在表单中使用img标签去显示验证码图片并使用它
<formaction="http://localhost:8080/tmp/registServlet"method="get">
用户名:<inputtype="text"name="username"><br>
验证码:<inputtype="text"style="width:80px;"name="code"><imgsrc="http://localhost:8080/tmp/kaptcha.jpg"alt=""style="width:100px;height:28px;"><br>
<inputtype="submit"value="登录"></form>
4.在服务器获取谷歌生成的验证码和客户端发送过来的验证码比较使用。
@Override
protected void doGet(HttpServletRequestreq,HttpServletResponseresp) throws ServletException,IOException{
//获取Session中的验证码
Stringtoken=(String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);//删除Session中的验证码
req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);Stringcode=req.getParameter("code");//获取用户名Stringusername=req.getParameter("username");
if(token!=null&&token.equalsIgnoreCase(code))
{
System.out.println("保存到数据库:"+username);
resp.sendRedirect(req.getContextPath()+"/ok.jsp");
}else{
System.out.println("请不要重复提交表单");
}
}
5.切换验证码:
//给验证码的图片,绑定单击事件
$("#code_img").click(function(){
//在事件响应的function函数中有一个this对象。这个this对象,是当前正在响应事件的dom对象//src属性表示验证码img标签的图片路径。它可读,可写//alert(this.src);
this.src="${basePath}kaptcha.jpg?d="+newDate();
});