jsp应用-设置Cookie应用举例
—-设置Cookie:
Cookie是服务器保留在客户端上的一种资源;
public class Cookie
extends Object
implements Cloneable;// Cookie定义了一种信息;
Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie’s value can uniquely identify a client, so cookies are commonly used for session management.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.
/方法:
public Cookie(String name,
String value); // 构造Cookie对象
Constructs a cookie with a specified name and value.
String getName(); // 获取当前Cookie的name属性;
Returns the name of the cookie.
String getValue(); // 获取当前Cookie对象的值;
Returns the value of the cookie.
public int getMaxAge(); // 当前Cookie对象保持有效的最大时间;
Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
public void setValue(String newValue);// 设置当前Cookie对象的值;
Assigns a new value to a cookie after the cookie is created. If you use a binary value, you may want to use BASE64 encoding.
public void setMaxAge(int expiry); // 设置当前Cookie对象的最大生命周期;
Sets the maximum age of the cookie in seconds.
// javax.servlet.http.HttpServletResponse:
void addCookie(Cookie cookie);//添加Cookie
Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
// javax.servlet.http.HttpServletRequest:
Cookie[] getCookies(); // 获取服务器在当前客户端设置的所有cookie;
Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.
——–在服务器端设置到客户端的Cookie:
// setCookie.jsp:
<%@page contentType="text/html;utf8"%>
<%
Cookie c1 = new Cookie(“name”, “xjy”); // 自定义一个Cookie对象
Cookie c2 = new Cookie(“web”, “www.k187.com”);
// 通过response对象设置Cookie到客户端:
response.addCookie(c1);
response.addCookie(c2);
// 实际上Cookie是通过http头信息发送到客户端的,
%>
// 执行setCookie.jsp则客户端会出现自定义的Cookie
——–从客户端请求服务器对当前客户端设置的所有cookie:
// find.jsp
<%@page contentType="text/html;utf8"%>
<%
// 客户端获取服务器对此客户端设置的所有cookie对象:
Cookie[] c = request.getCookies();
for (int x = 0; x < c.length; x++)
{
%>
<%=c[x].getName()%> –> <%=c[x].getValue()%>
<%-- 获取Cookie的名字和对应的值--%>
<%
}
%>
—执行find.jsp:
name –> xjy # 自定义
web –> www.k187.com # 自定义
JSESSIONID –> A22B95B218A2AC7F64C0EF4942012C43 # 系统内置的!当客户端第一次连上服务器时,服务器对当前浏览器设置的Cookie!
Cookie只对当前浏览器生效!
Cookie的保持时间可以增大,以延长Cookie保存在客户端的时间,和当前浏览器可以访问该Cookie对象的时间!
——-设置定长的Cookie保持时间:
// 通过客户端调用以下jsp页面,将产生与服务器的链接,并且可以设置服务器端自定义的Cookie:
<%@page contentType="text/html;utf8"%>
<%
Cookie c1 = new Cookie(“name”, “xjy”); // 自定义一个Cookie对象
Cookie c2 = new Cookie(“web”, “www.k187.com”);
c1.setMaxAge(60);
c2.setMaxAge(60);
// 通过response对象设置Cookie到客户端:
response.addCookie(c1);
response.addCookie(c2);
%>
// 前提:需要执行以上代码两次:
因为,第一次执行,只是连接到服务器,服务器只会设置默认的Session记录Cookie;
第二次执行时才会设置;
<%@page contentType="text/html;utf8"%>
<%
// 客户端获取服务器对此客户端设置的所有cookie对象:
Cookie[] c = request.getCookies();
for (int x = 0; x < c.length; x++)
{
%>
<%=c[x].getName()%> –> <%=c[x].getValue()%>
<%-- 获取Cookie的名字和对应的值--%>
<%
}
%>
// 所有以上操作:设置Cookie和获取cookie 都是通过请求服务器上的页面进行的!
———网站登录程序: 用户名和密码的验证 采用数据库查询验证!
// login.jsp
<%@page contentType="text/html;charset=utf8"%>
<%
request.setCharacterEncoding(“utf8”); // 进行乱码处理
%>
<%
if (request.getAttribute(“err”) != null) // 输出错误信息
{
%>
<%=request.getAttribute("err")%> <%-- 调用toString()方法,String类型覆写了!--%>
<%
}
%>
// check.jsp
<%@page contentType="text/html;charset=utf8" import="java.sql.*"%>
<%!
public static final String DBDRIVER = “com.mysql.jdbc.Driver”;
public static final String DBURL = “jdbc:mysql://localhost:3306/user”;
public static final String DBUSER = “root”;
public static final String DBPASS = “123456”;
%>
<%
request.setCharacterEncoding(“utf8”); // 进行乱码处理
// 首先判断验证码!
// String code = request.getParameter(“code”); // 获取客户端验证码输入
//String rand = (String)session.getAttribute(“rand”); // 获取当前session系统生成的验证码信息
// if (!rand.equals(code))
//{
// request.setAttribute(“err”, “验证码错误!”);
%>
<%--
<%
//}
// ————–数据库验证操作开始—————————
/*数据库脚本
drop database user; # show databases
create database user;
drop table user;
create table user(id int auto_increment premary key, name varchar(20), password varchar(20)) type=InnoDB;
# show engines
*/
Connection conn = null; // 数据库连接
PreparedStatement pstmt = null; // 预处理语句
ResultSet rs = null; // 查询结果
// 客户端的验证,保证以下两个非空或非空格!
String name = request.getParameter(“uname”); // 获取客户端输入的用户名
String pass = request.getParameter(“pass”); // 获取客户端输入的密码
try
{
Class.forName(DBDRIVER); // 加载数据库驱动
}
catch (ClassNotFoundException e)
{
out.println(“驱动加载失败!”);
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 连接数据库
String sql = “select id, name, password from user where name=? and password=?”;
pstmt = conn.prepareStatement(sql); // 获取操作
pstmt.setString(1, name); // 设置客户端输入的用户名为查询条件,这是关键!
pstmt.setString(2, pass);
rs = pstmt.executeQuery(); // 执行查询
}
catch (Exception e)
{
e.printStackTrace(); // 后台处理
}
if (rs.next()) // 判断是否有查询数据
{ // 存在数据
session.setAttribute(“user”, name); // 设置当前session属性,表示用户存在合法登录!
rs.close();
}
// 关闭数据库操作:
pstmt.close();
conn.close();
// ——————数据库验证完毕———————————–
if (session.getAttribute(“user”) != null)
{ // 用户存在
//response.sendRedirect(“welcome.jsp”); // 登录成功,重定向到登录成功页!
%>
<%
}
else
{
request.setAttribute(“err”, “用户名或密码错误,登录失败!”);
%>
<%
}
%>
// welcome.jsp:
<%@page contentType="text/html;charset=utf8"%>
<%
if (session.getAttribute(“user”) != null) // 当前session的登录标识,成功!
{
if (session.isNew())
{
%>
您首次登录服务器,因为对您的cookie还没创建!
<%=session.getId()%>
<%=request.getCookies()[0].getValue()%>
<%
}
else
{
%>
您已经登录服务器了,因为对您的cookie已创建!
JSESSIONID: <%=session.getId()%>
Cookie: <%=request.getCookies()[0].getValue()%>
<%
}
}
else
{
%>
您未登录,请先登录,2秒钟自动跳转到登录页!
<%
response.setHeader(“refresh”, “2;URL=login.jsp”); // 定时跳转
}
%>
// logout.jsp
<%@page contentType="text/html;charset=utf8"%>
<%
session.invalidate(); // 注销session
%>
成功退出!
// image.jsp:
<%@page contentType="image/jpeg"
import=”java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*”%>
<%!
Color getRandColor(int fc, int bc)
{ // 给定范围的随机颜色
Random random = new Random();
if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
int r = fc + random.nextInt(bc – fc);
int g = fc + random.nextInt(bc – fc);
int b = fc + random.nextInt(bc – fc);
return new Color(r, g, b);
}
%>
<%
// 设置页面不缓
response.setHeader(“Pragma”, “no-cache”);
response.setHeader(“Cache-Control”, “no-cache”);
response.setDateHeader(“Expires”, 0);
// 在内存中创建图像
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font(“Times New Roman”, Font.PLAIN, 18));
// 画边框
// g.setColor(new Color());
// g.drawRect(0, 0, width – 1, heigth – 1);
// 随机产生155条干扰线, 使图像的认证码不易被程序探测到:
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x, y, x + x1, y + y1);
}
// 取随机产生的认证码(四位数)
// String rand = request.getParameter(“rand”);
// rand = rand.subString(0, rand.indexOf(“、”));
String sRand = “”;
for (int i = 0; i < 4; i++)
{
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图像中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
// 调用函数获取的颜色相同,可能是因为种子太接近,所以直接生成:
g.drawString(rand, 13 * i + 6, 16);
}
// 将认证码存入SESSION
session.setAttribute(“rand”, sRand);
// 图像生效
g.dispose();
// 输出图像到页面:
ImageIO.write(image, “JPEG”, response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
// 执行结果:
您已经登录服务器了,因为对您的cookie已创建!
JSESSIONID: 97EA9CD8988E03E870B98FD9614888DA # session借助cookie机制,因此cookie是不能关的!
Cookie: 97EA9CD8988E03E870B98FD9614888DA 注销
———————————————————————
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《jsp应用-设置Cookie应用举例》
本文地址:http://www.xiupu.net/archives-191.html
关注公众号:
微信赞赏
支付宝赞赏