书签 分享 收藏 举报 版权申诉 / 15

类型JavaWeb用户登录功能的实现教学教材.docx

  • 文档编号:26565661
  • 上传时间:2023-06-20
  • 格式:DOCX
  • 页数:15
  • 大小:53.45KB

JQuery代码:

login.js

$(function(){

$(".loginform_submit").click(function(){

if(checkInput()){

$("form").action("/loginServlet");

}else{

returnfalse;

}

});

$(".validationCode_img").click(function(){

$(".validationCode_img").attr("src","/UserLogin/Sample1/validationCode?

"+Math.random());

});

functioncheckInput(){

//判断用户名

if($("input[name=username]").val()==null||$("input[name=username]").val()==""){

alert("用户名不能为空");

$("input[name=username]").focus();

returnfalse;

}

//判断密码

if($("input[name=password]").val()==null||$("input[name=password]").val()==""){

alert("密码不能为空");

$("input[name=password]").focus();

returnfalse;

}

//判断验证码

if($("input[name=validationCode]").val()==null||$("input[name=validationCode]").val()==""){

alert("验证码不能为空");

$("input[name=validationCode]").focus();

returnfalse;

}

returntrue;

}

});

生成验证码的Servlet:

ValidationCode.java

packagezh.userlogin.sample;

importjavax.imageio.ImageIO;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importjava.awt.*;

importjava.awt.image.BufferedImage;

importjava.io.IOException;

importjava.io.OutputStream;

importjava.util.Random;

/**

*Createdbyzhangon2014/9/13.

*/

publicclassValidationCodeextendsHttpServlet{

@Override

protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{

//获得验证码集合的长度

intcharsLength=codeChars.length();

//下面3条记录是关闭客户端浏览器的缓冲区

//这3条语句都可以关闭浏览器的缓冲区,但是由于浏览器的版本不同,对这3条语句的支持也不同

//因此,为了保险起见,同时使用这3条语句来关闭浏览器的缓冲区

resp.setHeader("ragma","No-cache");

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

resp.setDateHeader("Expires",0);

//设置图形验证码的长和宽

intwidth=90,height=30;

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

Graphicsg=image.getGraphics();//获得用于输出文字的Graphics对象

Randomrandom=newRandom();

g.setColor(getRandomColor(180,250));

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

g.setFont(newFont("TimesNewRoman",Font.ITALIC,height));

g.setColor(getRandomColor(120,180));

//用户保存最后随机生成的验证码

StringBuildervalidationCode=newStringBuilder();

//验证码的随机字体

String[]fontNames={"TimesNewRoman","Bookantiqua","Arial"};

//随机生成3-5个验证码

for(inti=0;i<4;i++){

//随机设置当前验证码的字符的字体

g.setFont(newFont(fontNames[random.nextInt(3)],Font.ITALIC,height));

//随机获得当前验证码的字符

charcodeChar=codeChars.charAt(random.nextInt(charsLength));

validationCode.append(codeChar);

//随机设置当前验证码字符的颜色

g.setColor(getRandomColor(10,100));

//在图形上输出验证码字符,x和y都是随机生成的

g.drawString(String.valueOf(codeChar),16*i+random.nextInt(7),height-random.nextInt(6));

}

//获得HttpSession对象

HttpSessionsession=req.getSession();

//设置session对象5分钟失效

session.setMaxInactiveInterval(5*60);

//将验证码保存在session对象中,key为validation_code

session.setAttribute("validation_code",validationCode.toString());

//关闭Graphics对象

g.dispose();

OutputStreamoutS=resp.getOutputStream();

ImageIO.write(image,"JPEG",outS);

}

@Override

protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{

doGet(req,resp);

}

//图形验证码的字符集,系统将随机从这个字符串中选择一些字符作为验证码

privatestaticStringcodeChars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

//返回一个随机颜色

privatestaticColorgetRandomColor(intminColor,intmaxColor){

Randomrandom=newRandom();

if(minColor>255){

minColor=255;

}

if(maxColor>255){

maxColor=255;

}

//获得r的随机颜色值

intred=minColor+random.nextInt(maxColor-minColor);

//g

intgreen=minColor+random.nextInt(maxColor-minColor);

//b

intblue=minColor+random.nextInt(maxColor-minColor);

returnnewColor(red,green,blue);

}

}

操作数据库的代码:

ManageSQLServer2008.java(本人使用的数据库为SQLServer2008)

packagezh.userlogin.sample.dbmanager;

importjava.beans.Statement;

importjava.sql.*;

publicclassManageSQLServer2008{

//数据库的驱动名

privatefinalStringdbDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";

//数据库的url地址

privatefinalStringurl="jdbc:

sqlserver:

//localhost:

1433;databaseName=zhDemo";

privatefinalStringuserName="sa";

privatefinalStringpassword="123";

privateConnectionconn=null;

publicManageSQLServer2008(){

//加载数据库驱动

try{

Class.forName(dbDriver).newInstance();

//System.out.println("加载驱动成功");

}catch(Exceptione){

e.printStackTrace();

System.err.println("数据库驱动加载失败");

}

//获取数据库链接

try{

conn=DriverManager.getConnection(url,userName,password);

}catch(SQLExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

System.err.println("获取数据库链接失败");

}

}

//执行各种SQL语句的方法

privateResultSetexecSQL(Stringsql,Object...args)throwsSQLException{

//建立PreparedStatement对象

PreparedStatementpStmt=conn.prepareStatement(sql);

//为pStmt对象设置SQL参数值

for(inti=0;i

pStmt.setObject(i+1,args[i]);

}

//执行SQL语句

pStmt.execute();

//返回结果集,如果执行的SQL语句不返回结果集,则返回null

returnpStmt.getResultSet();

}

privatevoidcloseSQLConn(){

//关闭数据库链接

if(conn!

=null){

try{

conn.close();

}catch(SQLExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}

publicStringcheckUser(Stringusername,Stringpassword){

booleanhas_username=false;

booleanpassword_correct=false;

ResultSetrs=null;

try{

rs=execSQL("select*fromzh_users");

}catch(SQLExceptione){

System.err.println("查询数据库出错");

e.printStackTrace();

returnnull;

}

try{

while(rs.next()){

Stringtemp_username=rs.getString("user_name").trim();

Stringtemp_password=rs.getString("password_md5").trim();

if(username.equals(temp_username)){

has_username=true;

if(password.equals(temp_password)){

password_correct=true;

return"hasUserNameAndPasswordCorrect";

}

return"hasUserNameButPasswordInCorrect";

}

}

}catch(SQLExceptione){

System.err.println("操作ResultSet出错");

e.printStackTrace();

}

return"hasNoUserName";

}

}

用于处理用户登录的Servlet:

LoginServlet.java

packagezh.userlogin.sample;

importzh.userlogin.sample.dbmanager.ManageSQLServer2008;

importjavax.servlet.RequestDispatcher;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importjava.io.IOException;

importjava.io.OutputStream;

/**

*Createdbyzhangon2014/9/13.

*/

publicclassLoginServletextendsHttpServlet{

@Override

protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{

OutputStreamout=resp.getOutputStream();

Stringusername=req.getParameter("username");

Stringpassword=req.getParameter("password");

StringvalidationCode=req.getParameter("validationCode");

HttpSessionsession=req.getSession();

Stringvalidation_code=(String)session.getAttribute("validation_code");

if(validationCode.equalsIgnoreCase(validation_code)){

System.out.println("验证码正确");

}else{

System.out.println("验证码错误");

}

ManageSQLServer2008mss=newManageSQLServer2008();

Stringresult=mss.checkUser(username,password);

if(result.equals("hasUserNameAndPasswordCorrect")){

System.out.println("用户名和密码均正确");

}elseif(result.equals("hasUserNameButPasswordInCorrect")){

System.out.println("用户名正确,密码不正确");

}elseif(result.equals("hasNoUserName")){

System.out.println("没有此用户");

}

//转发到result.jsp

RequestDispatcherrd=req.getRequestDispatcher("Login.html");

rd.forward(req,resp);

}

@Override

protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{

doGet(req,resp);

}

}

web.xml文件的配置:

loginServlet

zh.userlogin.sample.LoginServlet

loginServlet

/loginServlet

validationCode

zh.userlogin.sample.ValidationCode

validationCode

举报
举报
版权申诉
版权申诉
word格式文档无特别注明外均可编辑修改;预览文档经过压缩,下载后原文更清晰! 立即下载
配套讲稿:

如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。

特殊限制:

部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。

关 键  词:
JavaWeb 用户 登录 功能 实现 教学 教材
提示  冰豆网所有资源均是用户自行上传分享,仅供网友学习交流,未经上传用户书面授权,请勿作他用。
关于本文
本文标题:JavaWeb用户登录功能的实现教学教材.docx
链接地址:https://www.bdocx.com/doc/26565661.html
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2008-2022 冰点文档网站版权所有

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

收起
展开