实验七 会话编程实验学生Word文档格式.docx
《实验七 会话编程实验学生Word文档格式.docx》由会员分享,可在线阅读,更多相关《实验七 会话编程实验学生Word文档格式.docx(16页珍藏版)》请在冰豆网上搜索。
密&
nbsp;
码:
password"
验证码:
10"
checkCode"
imgsrc="
CheckCodeGet"
width="
110"
height="
30"
/>
<
checkbox"
chkSelect"
selectname="
selectTime"
<
optionvalue="
一天"
一天<
/option>
一周"
一周<
一月"
一月<
/select>
时间内不再重新登录<
submit"
value="
提交"
reset"
重置"
/form>
/center>
/body>
图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"
);
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!
reqWidth!
)
this.width=Integer.parseInt(reqWidth);
if(reqHeight!
reqHeight!
this.height=Integer.parseInt(reqHeight);
if(reqType!
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<
count;
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();
size;
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));
caseTYPE_MULTIPLE:
if(random.nextBoolean()){
result=String.valueOf(random.nextInt(10));
}else{
result=String.valueOf((char)(random.nextInt(26)+65));
}
default:
result=null;
if(result==null)
{
thrownewNullPointerException("
获取验证码出错"
returnresult;
*ThedoPostmethodoftheservlet.<
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
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的配置,配置代码如下:
servlet>
description>
ThisisthedescriptionofmyJ2EEcomponent<
/description>
display-name>
ThisisthedisplaynameofmyJ2EEcomponent<
/display-name>
servlet-name>
CheckCodeGet<
/servlet-name>
servlet-class>
cn.javaee.session.CheckCodeGet<
/servlet-class>
/servlet>
servlet-mapping>
url-pattern>
/CheckCodeGet<
/url-pattern>
/servlet-mapping>
4.可以发布工程进行测试登录页面,能够打开如图1所示的界面。
输入如图2所示的正确结,点击“提交”按钮后,读取数据库中的记录,查找和用户账号及密码匹配的记录,如果找到,转到主页mainPage.jsp,提示用户登录成功,如图3所示。
如果找不到,再次转到登录界面。
在src下新建一个Servelt类LoginServlet用于处理“提交”表单后的处理,LoginServlet.java的代码如下:
importjava.io.PrintWriter;
import.URLEncoder;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
importjavax.servlet.http.Cookie;
importjavax.servlet.http.HttpSession;
publicclassLoginServletextendsHttpServlet{
privateConnectioncn=null;
publicLoginServlet(){
//销毁方法,关闭数据库连接,释放对象占用内存
//TODOAuto-generatedmethodstub
try{
if(cn!
=null&
(!
cn.isClosed())){
cn.close();
cn=null;
}catch(Exceptione){
System.out.println("
DestroyError:
+e.getMessage());
doPost(request,response);
StringuserID=request.getParameter("
Stringpassword=request.getParameter("
Stringsql="
select*fromstudent_infowherestu_id='
+userID+"
'
"
;
Statementst=null;
st=cn.createStatement();
}catch(SQLExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
ResultSetrs=null;
rs=st.executeQuery(sql);
}catch(SQLExceptione){
e.printStackTrace();
if(rs.next()){
StringdbPassword=rs.getString("
stu_pwd"
).toString();
StringdbUserName=rs.getString("
stu_name"
if(dbPassword.equals(password)){//输入的密码正确
StringcookSelected=request.getParameter("
if(cookSelected!
=null){//设置Cookie的保存时间
Cookiename=newCookie("
myname"
URLEncoder.encode(userID,"
utf-8"
));
Cookiepass=newCookie("
mypass"
URLEncoder.encode(password,"
StringageString=newString(request.getParameter("
).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("
dbUserName);