使用步骤:
new Cookie(String name, String value)
response.addCookie(Cookie cookie)
Cookie[] request.getCookie()
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/29 21:32
* Cookie快速入门
*/
@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建Cookie对象
Cookie c = new Cookie("msg","hello");
//2.发送Cookie
response.addCookie(c);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/29 21:32
* Cookie快速入门
*/
@WebServlet("/cookieDemo2")
public class CookieDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//3.获取Cookie
Cookie[] cs = request.getCookies();
//获取数据,遍历Cookies
if(cs != null){
for (Cookie c : cs) {
String name = c.getName();
String value = c.getValue();
System.out.println(name+":"+value);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
set-cookie:name:value
cookie:name:value
一次可不可以发送多个cookie?
cookie在浏览器中保存多长时间?
默认情况下,当浏览器关闭后,Cookie数据被销毁
持久化存储:
setMaxAge(int seconds)
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/29 21:32
* Cookie快速入门
*/
@WebServlet("/cookieDemo4")
public class CookieDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建Cookie对象
Cookie c1 = new Cookie("msg","setMaxAge");
//2.设置cookie的存活时间
c1.setMaxAge(30);//将cookie持久化到硬盘,30秒后会自动删除cookie文件
//c1.setMaxAge(-1);
//c1.setMaxAge(300);
//c1.setMaxAge(0);
//3.发送Cookie
response.addCookie(c1);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
cookie能不能存中文?
cookie共享问题?
setPath(String path)
:设置cookie的获取范围。默认情况下,设置当前的虚拟目录setDomain(String path)
:如果设置一级域名相同,那么多个服务器之间cookie可以共享
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/29 22:24
*/
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应的消息体的数据格式以及编码
response.setContentType("text/html;charset=utf-8");
//1.获取所有Cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;//没有cookie为lastTime
//2.遍历cookies数组
if(cookies != null && cookies.length > 0){
for (Cookie cookie : cookies) {
//获取cookie的名称
String name = cookie.getName();
//判断名称是否是lastTime
if("lastTime".equals(name)){
//不是第一次访问
flag = true;//有lastTime的cookie
this.replaceCookie(cookie,response);
break;
}
}
}
if(cookies == null || cookies.length == 0 || flag == false){
//没有,第一次访问
this.setCookie(response);
response.getWriter().write("你好,欢迎您首次访问
");
}
}
/**
* 不是首次访问
* @param cookie
* @param response
* @return
*/
protected void replaceCookie(Cookie cookie,HttpServletResponse response) throws IOException {
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前:"+str_date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后:"+str_date);
cookie.setValue(str_date);
//设置cookie的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
response.addCookie(cookie);
//响应数据
//获取cookie的value
String value = cookie.getValue();
System.out.println("解码前:"+value);
//URL解码
value = URLDecoder.decode(value,"utf-8");
System.out.println("解码后:"+value);
response.getWriter().write("欢迎回来,您上次访问时间为:"
+value+"");
}
/**
* 首次访问
* @param response
*/
protected void setCookie(HttpServletResponse response) throws UnsupportedEncodingException {
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前:"+str_date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后:"+str_date);
Cookie cookie = new Cookie("lastTime",str_date);
//设置cookie的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
response.addCookie(cookie);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
URLEncoder.encode(String s,String enc)
编码URLDecoder.encode(String s,String enc)
解码<% 代码 %>
:定义的java代码,在server方法中。server方法中可以定义什么,该脚本就可以定义什么<%! 代码 %>
:定义的java代码,在jsp转换后的java类的成员位置<%= 代码 %>
:定义的java代码,会输出页面上。输出语句可以定义什么,该脚本就可以定义什么response.getWriter()
类似
response.getWriter()
和out.print
的区别
response.getWriter()
数据输出永远在out.write()
之前<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
home
<%
//1.获取所有Cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;//没有cookie为lastTime
//2.遍历cookies数组
if(cookies != null && cookies.length > 0){
for (Cookie cookie : cookies) {
//获取cookie的名称
String name = cookie.getName();
//判断名称是否是lastTime
if("lastTime".equals(name)){
//不是第一次访问
flag = true;//有lastTime的cookie
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前:"+str_date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后:"+str_date);
cookie.setValue(str_date);
//设置cookie的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
response.addCookie(cookie);
//响应数据
//获取cookie的value
String value = cookie.getValue();
System.out.println("解码前:"+value);
//URL解码
value = URLDecoder.decode(value,"utf-8");
System.out.println("解码后:"+value);
%>
欢迎回来,您上次访问时间为:<%= value %>
<%
break;
}
}
}
if(cookies == null || cookies.length == 0 || flag == false){
//没有,第一次访问
//设置cookie的value
//获取当前时间的字符串,重新设置cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前:"+str_date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后:"+str_date);
Cookie cookie = new Cookie("lastTime",str_date);
//设置cookie的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
response.addCookie(cookie);
%>
你好,欢迎您首次访问
<%
}
%>
HttpSession session = request.getSession();
Object getAttribute(String name)
removeAttribute(String name)
set-cookie:JSESSIONID=456465U1545
456465U1545
的对象
cookie:JSESSIONID=456465U1545
当客户端关闭后,服务器不关闭,两次获取Session对象是否为同一个?
默认情况下,不是
如果需要相同,则可以创建Cookie,键为JSESSIONID,设置最大存活时间,让cookie持久化保存
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/30 0:03
*/
@WebServlet("/sessionDemo3")
public class SessionDemo3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用session共享数据
//1.获取session
HttpSession session = request.getSession();
//期望客户端关闭后,session也能相同
Cookie cookie = new Cookie("JSESSIONID",session.getId());
cookie.setMaxAge(60*60);
response.addCookie(cookie);
System.out.println(session);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
客户端不关闭后,服务器关闭后,两次获取Session对象是否为同一个?
session的失效时间?
invalidate()
中可以修改默认失效时间,默认单位是分钟CheckCodeServlet.java
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/28 18:05
*/
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(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 填充背景色
Graphics g = image.getGraphics();//画笔对象
g.setColor(Color.PINK);//设置画笔颜色
g.fillRect(0,0,width,height);
//2.2 画边框
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);
//2.3 写验证码
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//生成随机角标
Random ran = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);//随机字符
sb.append(ch);
g.drawString(ch+"",width/5*i,height/2);
}
String checkCode_session = sb.toString();
//将验证码存入session
request.getSession().setAttribute("checkCode_session",checkCode_session);
//2.4 画干扰线
g.setColor(Color.green);
// 随机生成坐标点
for (int i = 0; i < 10; 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.将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
login
<%=request.getAttribute("cc_error") == null ? "":request.getAttribute("cc_error")%>
<%=request.getAttribute("login_error") == null ? "":request.getAttribute("login_error")%>
LoginServlet.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
/**
* @author zhuxianglong
* @version 1.0
* @date 2021/8/30 1:07
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置request编码
request.setCharacterEncoding("utf-8");
//2.获取参数
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkCode = request.getParameter("checkCode");
//3.先获取生成的验证码
HttpSession session = request.getSession();
String checkCode_session = (String)session.getAttribute("checkCode_session");
//删除session中存储的验证码,保证安全性
session.removeAttribute(checkCode_session);
//4.判断验证码是否正确
if(checkCode_session != null && checkCode_session.equalsIgnoreCase(checkCode)){
//忽略大小写比较字符串
//验证码正确
//判断用户名和密码
if("zhangsan".equals(username) && "123".equals(password)){
//需要调用UserDao查询数据库
//登录成功
//存储用户信息
session.setAttribute("user",username);
//重定向到success.jsp
response.sendRedirect(request.getContextPath()+"/success.jsp");
}else{
//登录失败
//存储提示信息到request
request.setAttribute("login_error","用户名或密码错误");
//转发到登录页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}else{
//验证码不一致
//存储提示信息到request
request.setAttribute("cc_error","验证码错误");
//转发到登录页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
loginSuccess
<%=request.getSession().getAttribute("user")%>,欢迎您
作用:用于配置JSP页面,导入资源文件
格式:
<%@ 指令名称 属性名1=属性值1 属性名2=属性值2...%>
分类:
contentTye
:等同于response.setContentType()
pageEncoding
属性设置当前页面的字符集)import
:导包errorPage
:当前页面发生异常后,会自动跳转到指定的错误页面isErrorPage
:标识当前页面是否是错误页面
<%@include file="top.jsp"%>
<%@ talib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
prefix
:前缀,自定义的
:只能注释html代码片段<%-- -->
:可以注释所有在jsp页面中不需要创建,直接使用的对象
一共有9个隐式对象:
什么是隐式对象呢?它指的是在jsp中,可以不声明就直接使用的对象。
它只存在于jsp中,因为java类中的变量必须要先声明再使用。
其实jsp中的隐式对象也并非是未声明,只是它是在翻译成.java文件时声明的。所以我们在jsp中可以直接使用。
隐式对象名称 | 类型 | 备注 |
---|---|---|
request | javax.servlet.http.HttpServletRequest | 一次请求访问多个资源(转发) |
response | javax.servlet.http.HttpServletResponse | 响应对象 |
session | javax.servlet.http.HttpSession | Page指令可以控制开关 一次会话的多个请求间 |
application | javax.servlet.ServletContext | 所有用户间共享数据 |
page | Java.lang.Object | 当前jsp对应的servlet引用实例对象 this |
config | javax.servlet.ServletConfig | Serlvet的配置对象 |
exception | java.lang.Throwable | page指令有开关 异常对象 |
out | javax.servlet.jsp.JspWriter | 字符输出流,相当于printwriter |
pageContext | javax.servlet.jsp.PageContext | 当前页面共享数据,还可以获取其他八个内置对象 |
PageContext
它是JSP独有的对象,Servlet中没有这个对象。本身也是一个域(作用范围)对象,但是它可以操作其他3个域对象中的属性。而且还可以获取其他8个隐式对象。
它是一个局部变量,所以它的生命周期随着JSP的创建而诞生,随着JSP的结束而消失。每个JSP页面都有一个独立的PageContext。
优点
缺点