jsp网页登陆验证
jsp登陆验证,网页登陆验证带验证码校验,登录功能之添加验证码
part_1:专门用于生成一个验证码图片的类:VerificationCode.java
packagecn.mike.javase.test;
importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics2D;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;
importjavax.imageio.ImageIO;
importorg.junit.Test;
/**
*@author:Administrator
*@function:这是用来测试随机生成验证码图片的类;
*/
publicclassVerificationCode{
/**
*单元测试,试一下能不能自动生成验证码图片
*/
//这个函数是单元测试时使用的,这里private一下外面就调用不到了;
/*@Test*/
/*public*/privatevoidtest_fun(){
VerificationCodevc=newVerificationCode();
BufferedImageimage=vc.getImage();
try{
//生成验证码图片,并保存到指定的路径
VerificationCode.output(image,newFileOutputStream(newFile(
".\\image\\vcode_2.jpg")));
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
//将随机生成的文本内容输出到控制台,用于校验
System.out.println(vc.getText());
}
privateintw=70;//宽
privateinth=35;//高
privateStringtext;//文本内容(验证码字符串)
privateRandomr=newRandom();
privateString[]fontNames={"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312"};
//随机字符集合中不包括0和o,O,1和l,因为这些不易区分
privateStringcodes="23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYXZ";
//验证码图片的背景色:白色
privateColorbgColor=newColor(255,255,255);
/**
*返回一个验证码图片buffer对象:BufferedImage
*/
publicBufferedImagegetImage(){
BufferedImageimage=createImage();
//获取绘图环境(画笔工具)
Graphics2Dg2=(Graphics2D)image.getGraphics();
//sb:用来保存验证码字符串文本内容
StringBuildersb=newStringBuilder();
for(inti=0;i<4;++i){//随机生成4个字符
Strings=randomChar()+"";
sb.append(s);
floatx=i*1.0F*w/4;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s,x,h-5);
}
this.text=sb.toString();//记录验证码文本内容
drawLine(image);//画干扰线
returnimage;
}
/**
*@return获取验证码文本内容
*/
publicStringgetText(){
returntext;
}
/**
*@paramimage
*@paramout
*将文本写到指定的输出流。比如本测试中FileOutputStream指定的保存路径
*/
publicstaticvoidoutput(BufferedImageimage,OutputStreamout){
try{
ImageIO.write(image,"jpeg",out);
}catch(IOExceptione){
e.printStackTrace();
}
}
privatevoiddrawLine(BufferedImageimage){
Graphics2Dg2=(Graphics2D)image.getGraphics();
for(inti=0;i<3;++i){//画3条干扰线
intx1=r.nextInt(w);
inty1=r.nextInt(h);
intx2=r.nextInt(w);
inty2=r.nextInt(h);
g2.setColor(Color.BLUE);
g2.drawLine(x1,y1,x2,y2);
}
}
privateColorrandomColor(){
intred=r.nextInt(150);
intgreen=r.nextInt(150);
intblue=r.nextInt(150);
returnnewColor(red,green,blue);
}
privateFontrandomFont(){
intindex=r.nextInt(fontNames.length);
StringfontName=fontNames[index];
intstyle=r.nextInt(4);
intsize=r.nextInt(5)+24;
returnnewFont(fontName,style,size);
}
privatecharrandomChar(){
intindex=r.nextInt(codes.length());
returncodes.charAt(index);
}
privateBufferedImagecreateImage(){
BufferedImageimage=newBufferedImage(w,h,
BufferedImage.TYPE_INT_RGB);
Graphics2Dg2=(Graphics2D)image.getGraphics();
g2.setColor(this.bgColor);
g2.fillRect(0,0,w,h);
returnimage;
}
}
part_2:登录界面:Login.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'Login.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
<scripttype="text/javascript">
function_change_verity_code(){
varimgElem=document.getElementById("img_src");
//添加一个请求参数a是因为,通常浏览器都有缓存,点击换一张的时候没反应,所以加一个请求参数,获取当前请求时间,可以精确到毫秒,所以每次请求的参数都不同,所以浏览器有缓存也不妨碍;
imgElem.src="/ServletDemoProject/servlet/GetVerificationCodeServlet?a="
+newDate().getTime();
}
</script>
</head>
<%
StringfdbkMsg=(String)request.getAttribute("fdbkMsg");
if(null==fdbkMsg){
fdbkMsg="";
}
%>
<%
BooleanlogedIn=(Boolean)session.getAttribute("logedIn");
if(null==logedIn){
logedIn=false;
}elseif(logedIn){
//如果在本次会话已经登陆,直接重定向到success-page-1
response
.sendRedirect("/ServletDemoProject/LOGIN-DEMO/success-page-1.jsp");
}
%>
<%
Stringusername="";
Cookie[]cookies=request.getCookies();
if((null!=cookies)&&(cookies.length>0)){
for(Cookiec:cookies){
if("admin".equals(c.getValue())){
username="admin";
break;
}
}
}//endif-condition
%>
<body>
<br>
<divalign="center">
请登录:
<br>
<formaction="/ServletDemoProject/servlet/LoginVerificationServlet"
method="post">
<div>
用户名:
<inputtype="text"name="username"value="<%=username%>"/>
<br>
</div>
<div>
密码:
<inputtype="password"name="password"/>
<br>
</div>
<div>
验证码:
<inputtype="text"name="code_text"size="3"/>
<imgsrc="/ServletDemoProject/servlet/GetVerificationCodeServlet"
id="img_src"/>
<ahref="javascript:_change_verity_code()">换一张</a>
<br>
</div>
<div>
<fontcolor='red'><%=fdbkMsg%></font>
<br>
</div>
<div>
<inputtype="submit"value="提交"/>
<br>
</div>
</form>
</div>
</body>
</html>
part_3:处理登录校验的servlet:LoginVerificationServlet.java
packagecn.mike.servlet.test_1212;
importjava.awt.image.BufferedImage;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcn.mike.javase.test.VerificationCode;
publicclassGetVerificationCodeServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=-3520994675366100452L;
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//1.新建一个VerificationCode类;
VerificationCodevc=newVerificationCode();
//2.从VerificationCode类中获取BufferedImage对象;
BufferedImagebufImage=vc.getImage();
//3.同时获取验证码中的文本内容,并放到session域中,用于校验;
Stringcode_text=vc.getText();
request.getSession().setAttribute("code_text",code_text);
//4.将生成的图片输出到客户端浏览器
VerificationCode.output(bufImage,response.getOutputStream());
}//endmethod-doGet
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//dosameasGET-method:
doGet(request,response);
}//endmethod-doPost
}
part_4:成功登陆后的提示界面1:success-page-1.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'success-page-1.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<%
Stringusername=(String)session.getAttribute("username");
if(null==username){
//如果username为空值,说明不是通过正常渠道来的,转发到Login页面;
request.setAttribute("fdbkMsg","别想走后门进来,赶紧登录!");
request.getRequestDispatcher("/LOGIN-DEMO/Login.jsp").forward(
request,response);
}
%>
<body>
<br>
<%=username%>已经成功登陆。
<br>
<font>您可以选择浏览:</font>
<br>
<ahref="/ServletDemoProject/LOGIN-DEMO/success-page-2.jsp">点这儿有精彩.</a>
<br>
<ahref="/ServletDemoProject/LOGIN-DEMO/success-page-2.jsp">点这儿更精彩.</a>
<br/>
<ahref="/ServletDemoProject/LOGIN-DEMO/success-page-2.jsp">你敢点这儿吗.</a>
<br/>
</body>
</html>
part_5:成功登陆后的提示界面1:success-page-2.jsp
<%@pagelanguage="java"import="java.util.Date"pageEncoding="UTF-8"%>
<%@pagelanguage="java"import="java.text.SimpleDateFormat"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'success-page-2.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<%
Stringusername=(String)session.getAttribute("username");
if(null==username){
request.setAttribute("fdbkMsg","呵呵嗒,这里是你来的地方吗?快登陆!");
//转发到登录界面:
request.getRequestDispatcher("/LOGIN-DEMO/Login.jsp").forward(
request,response);
}
SimpleDateFormatsDateFormat=newSimpleDateFormat("a");
Datetoday=newDate();
Stringam_pm_str=sDateFormat.format(today);
Stringam_pm_str_in_chinese="";
if("am".equalsIgnoreCase(am_pm_str)){
am_pm_str_in_chinese="上午";
}else
am_pm_str_in_chinese="下午";
//setnull;
sDateFormat=null;
today=null;
am_pm_str=null;
%>
<body>
<br/>
<font><b><%=username%><%=am_pm_str_in_chinese%>好,能来到页面2真不简单.</b>
</font>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。