实验七 会话编程实验学生.docx

上传人:b****6 文档编号:3607748 上传时间:2022-11-24 格式:DOCX 页数:16 大小:137.52KB
下载 相关 举报
实验七 会话编程实验学生.docx_第1页
第1页 / 共16页
实验七 会话编程实验学生.docx_第2页
第2页 / 共16页
实验七 会话编程实验学生.docx_第3页
第3页 / 共16页
实验七 会话编程实验学生.docx_第4页
第4页 / 共16页
实验七 会话编程实验学生.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

实验七 会话编程实验学生.docx

《实验七 会话编程实验学生.docx》由会员分享,可在线阅读,更多相关《实验七 会话编程实验学生.docx(16页珍藏版)》请在冰豆网上搜索。

实验七 会话编程实验学生.docx

实验七会话编程实验学生

实验七会话编程实验

实验目的:

掌握会话的基本知识

熟悉会话的生命周期

掌握Cookie和Session实现会话跟踪

实验内容:

1、假设学生登录一个图书管理系统,在登录界面上提供学生输入账号、密码、验证码(可以使用Servlet生成4位随机数的验证码,并保存在会话对象中,同时生成带干扰的验证码图片,登录页面使用此Servlet生成的验证码),并给学生选择是否保存Cookie,如果保存,选择保存时间。

登录成功后,跳转到的页面上显示学生的账号信息,学生也可以自己退出系统。

实验操作步骤

1.新建一个WebProject,工程名为ExperiSevenCookieSession,新建一个登录页面文件login.jsp,设置提示学生用户登录的账号、密码、验证码框,复选框提示用户是否决定选择Cookie的保存时间。

界面如图1所示。

login.jsp的代码如下:

登录页面

用户名:



密 码:



验证码:



一天

一周

一月

时间内不再重新登录

图1登录界面

2.在src目录下新建一个Servlet,类名CheckCodeGet,用于生成验证码,验证码是随机生成的数字,CheckCodeGet.java代码如下:

packagecn.javaee.session;

importjava.awt.Color;

importjava.awt.Font;

importjava.awt.Graphics;

importjava.awt.image.BufferedImage;

importjava.io.IOException;

importjava.util.Random;

importjavax.servlet.ServletConfig;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importcom.sun.image.codec.jpeg.JPEGCodec;

importcom.sun.image.codec.jpeg.JPEGImageEncoder;

//本Servlet的功能用于生成验证码

publicclassCheckCodeGetextendsHttpServlet{

privatestaticfinallongserialVersionUID=1L;

privatefinalintTYPE_NUMBER=0;

privatefinalintTYPE_LETTER=1;

privatefinalintTYPE_MULTIPLE=2;

privateintwidth;

privateintheight;

privateintcount;

privateinttype;

privateStringvalidate_code;

privateRandomrandom;

privateFontfont;

privateintline;

/**

*Constructoroftheobject.

*/

publicCheckCodeGet(){

super();

}

/**

*Destructionoftheservlet.

*/

publicvoiddestroy(){

super.destroy();//Justputs"destroy"stringinlog

//Putyourcodehere

}

/**

*ThedoGetmethodoftheservlet.

*

*Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.

*

*@paramrequesttherequestsendbytheclienttotheserver

*@paramresponsetheresponsesendbytheservertotheclient

*@throwsServletExceptionifanerroroccurred

*@throwsIOExceptionifanerroroccurred

*/

publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

response.setHeader("Pragma","No-cache");

response.setHeader("Cache-Control","no-cache");

response.setDateHeader("Expires",0);//不过期

response.setContentType("image/jpeg");//响应类型为图片

StringreqCount=request.getParameter("count");

StringreqWidth=request.getParameter("width");

StringreqHeight=request.getParameter("height");

StringreqType=request.getParameter("type");

if(reqCount!

=null&&reqCount!

="")

this.count=Integer.parseInt(reqCount);

if(reqWidth!

=null&&reqWidth!

="")

this.width=Integer.parseInt(reqWidth);

if(reqHeight!

=null&&reqHeight!

="")

this.height=Integer.parseInt(reqHeight);

if(reqType!

=null&&reqType!

="")

this.type=Integer.parseInt(reqType);

font=newFont("CourierNew",Font.BOLD,width/count);

BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

Graphicsg=image.getGraphics();

g.setColor(getRandColor(160,240));

g.fillRect(0,0,width,height);

g.setColor(getRandColor(20,100));

g.setFont(font);

validate_code=getValidateCode(count,type);

request.getSession().setAttribute("validate_code",validate_code);//将验证码存放到Session中,用于和输入的进行比较

for(inti=0;i

//

intx=(int)(width/count)*i;

inty=(int)((height+font.getSize())/2)-5;

g.drawString(String.valueOf(validate_code.charAt(i)),x,y);

}

g.dispose();

JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());

encoder.encode(image);

}

//获取随机的颜色

privateColorgetRandColor(intfrom,intto){

Randomrandom=newRandom();

if(from>255)from=255;

if(to>255)to=255;

intrang=Math.abs(to-from);

intr=from+random.nextInt(rang);//红色

intg=from+random.nextInt(rang);//蓝色

intb=from+random.nextInt(rang);//绿色

returnnewColor(r,g,b);

}

//获得验证码字符串

privateStringgetValidateCode(intsize,inttype){

StringBuffervalidate_code=newStringBuffer();

for(inti=0;i

validate_code.append(getOneChar(type));

}

returnvalidate_code.toString();

}

//根据验证码类型取得实际验证字符

//类型0-取得0-9之间的数字

//类型1-取得A-Z之间的字母

//类型2-随机取得数字或是字母的组合

privateStringgetOneChar(inttype){

Stringresult=null;

switch(type){

caseTYPE_NUMBER:

result=String.valueOf(random.nextInt(10));

break;

caseTYPE_LETTER:

result=String.valueOf((char)(random.nextInt(26)+65));

break;

caseTYPE_MULTIPLE:

if(random.nextBoolean()){

result=String.valueOf(random.nextInt(10));

}else{

result=String.valueOf((char)(random.nextInt(26)+65));

}

break;

default:

result=null;

break;

}

if(result==null)

{

thrownewNullPointerException("获取验证码出错");

}

returnresult;

}

/**

*ThedoPostmethodoftheservlet.

*

*Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.

*

*@paramrequesttherequestsendbytheclienttotheserver

*@paramresponsetheresponsesendbytheservertotheclient

*@throwsServletExceptionifanerroroccurred

*@throwsIOExceptionifanerroroccurred

*/

publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

doGet(request,response);

}

/**

*Initializationoftheservlet.

*

*@throwsServletExceptionifanerroroccurs

*/

publicvoidinit(ServletConfigconfig)throwsServletException{

super.init(config);

width=150;

height=50;

count=4;

type=TYPE_NUMBER;

random=newRandom();

line=200;

}

}

3.配置web.xml,添加对CheckCodeGet的配置,配置代码如下:

ThisisthedescriptionofmyJ2EEcomponent

ThisisthedisplaynameofmyJ2EEcomponent

CheckCodeGet

cn.javaee.session.CheckCodeGet

CheckCodeGet

/CheckCodeGet

4.可以发布工程进行测试登录页面,能够打开如图1所示的界面。

输入如图2所示的正确结,点击“提交”按钮后,读取数据库中的记录,查找和用户账号及密码匹配的记录,如果找到,转到主页mainPage.jsp,提示用户登录成功,如图3所示。

如果找不到,再次转到登录界面。

在src下新建一个Servelt类LoginServlet用于处理“提交”表单后的处理,LoginServlet.java的代码如下:

packagecn.javaee.session;

importjava.io.IOException;

importjava.io.PrintWriter;

import.URLEncoder;

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.servlet.ServletConfig;

importjavax.servlet.ServletException;

importjavax.servlet.http.Cookie;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

publicclassLoginServletextendsHttpServlet{

privateConnectioncn=null;

publicLoginServlet(){

super();

}

//销毁方法,关闭数据库连接,释放对象占用内存

publicvoiddestroy(){

//TODOAuto-generatedmethodstub

super.destroy();

try{

if(cn!

=null&&(!

cn.isClosed())){

cn.close();

cn=null;

}

}catch(Exceptione){

System.out.println("DestroyError:

"+e.getMessage());

}

}

publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

doPost(request,response);

}

publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

StringuserID=request.getParameter("userName");

Stringpassword=request.getParameter("password");

Stringsql="select*fromstudent_infowherestu_id='"

+userID+"'";

Statementst=null;

try{

st=cn.createStatement();

}catch(SQLExceptione1){

//TODOAuto-generatedcatchblock

e1.printStackTrace();

}

ResultSetrs=null;

try{

rs=st.executeQuery(sql);

}catch(SQLExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

try{

if(rs.next()){

StringdbPassword=rs.getString("stu_pwd").toString();

StringdbUserName=rs.getString("stu_name").toString();

if(dbPassword.equals(password)){//输入的密码正确

StringcookSelected=request.getParameter("chkSelect");

if(cookSelected!

=null){//设置Cookie的保存时间

Cookiename=newCookie("myname",URLEncoder.encode(userID,"utf-8"));

Cookiepass=newCookie("mypass",URLEncoder.encode(password,"utf-8"));

StringageString=newString(request.getParameter("selectTime").getBytes("ISO-8859-1"),"UTF-8");

//System.out.println(ageString);

if(ageString.equals("一天")){

name.setMaxAge(24*60*60);

pass.setMaxAge(24*60*60);

}elseif(ageString.equals("一周")){

name.setMaxAge(7*24*60*60);

pass.setMaxAge(7*24*60*60);

}elseif(ageString.equals("一月")){//假定一月就按30天算,不计详细的哪个月份

name.setMaxAge(30*24*60*60);

pass.setMaxAge(30*24*60*60);

}

response.addCookie(name);

response.addCookie(pass);

}

HttpSessionsession=request.getSession(true);

session.setAttribute("userName",dbUserName);

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高中教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1