jsp实现简单图片验证码功能
本文实例为大家分享了jsp实现简单图片验证码的具体代码,供大家参考,具体内容如下
一、实现的功能分析
(1)在登陆页面加验证码的功能,起到一定的安全性。在输入正确的验证码,用户名和密码的情况下,才可以实现登录。
(2)实现查询数据库的功能。在登陆后的页面中,显示用户名和密码,并且设置有一个超链接,实现查询数据库的功能。
(3)代码核心是:随机生成验证码,并且显示在页面上。同时要和输入框中的输入验证码进行校验。
(4)主页面使用img标签的src属性引入验证页面的jsp文件。
(5)验证码的实现页面使用bufferedimage类的方法产生图片。
(6)使用graphics类的各种方法实现验证码的构成。
二、代码实现
(1)登录页面:index.jsp文件。
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta charset="utf-8"> <title>登录页面</title> </head> <body> <form action="loginservlet" method="post"> 用户名:<input name="username" type="text" value=""/><br/><br/> 密码:<input name="password" type="password" value=""/><br/><br/> 验证码: <input type="text" name="checkcode" height="20px " value=""/> <img src="codeservlet"/>${error_code}<br/> <input type="submit" value="提交"> </form> </body> </html>
(2)登录后的页面:user.jsp文件。
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ page import = "com.entity.author"%> <!doctype html> <html> <head> <meta charset="utf-8"> <title>显示登录用户的用户名和密码页面</title> </head> <body> <% //内置对象 request.setcharacterencoding("utf-8"); //获取交互层放入session中的obj author obj = (author)session.getattribute("authorinfo"); if(obj != null){ out.print("<p>用户名:"+obj.getname()+"</p>"); out.print("<p>密码:"+obj.getid()+"</p>"); } else{ response.sendredirect("index.jsp"); } %> <br/> <a href="authorservlet">用户信息查询 </a> </body> </html>
(3)实现数据查询页面:ueslist.jsp文件。
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!doctype html> <html> <head> <meta charset="utf-8"> <title>查询信息显示页面</title> </head> <body> <table border="1"> <tr> <td>编号</td> <td>名称</td> <td>价格</td> <td>数量</td> <td>日期</td> <td>风格</td> </tr> <c:foreach items="${authorlist}" var="author"> <tr> <td>${author.id}</td> <td>${author.name }</td> <td>${author.price }</td> <td>${author.num }</td> <td>${author.dates}</td> <td>${author.style}</td> </tr> </c:foreach> </table> </body> </html>
(4)定义一个author类,用于接收数据库中的元素。
package com.entity; //用于获取数据库中的元素对象 public class author { private int id; private string name; private int price ; private int num; private string dates; private string style; public int getid() { return id; } public void setid(int id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public int getprice() { return price; } public void setprice(int price) { this.price = price; } public int getnum() { return num; } public void setnum(int num) { this.num = num; } public string getdates() { return dates; } public void setdates(string dates) { this.dates = dates; } public string getstyle() { return style; } public void setstyle(string style) { this.style = style; } }
(5)登录页面的交互层:loginservlet.java文件。用于登录检验和验证码匹配。
//交互层(客户端和服务器的交互) package com.servlet; import java.io.ioexception; import java.sql.sqlexception; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import com.dao.authordao; import com.entity.author; /** * servlet implementation class loginservlet */ @webservlet("/loginservlet") public class loginservlet extends httpservlet { private static final long serialversionuid = 1l; /** * @see httpservlet#httpservlet() */ public loginservlet() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub //内置对象request,response request.setcharacterencoding("utf-8"); httpsession session = request.getsession(); //获取用户输入验证码 string checkcode = request.getparameter("checkcode"); //获取session中的验证码,也就是codeservlet中生成的四个字符 string sessioncode = (string)session.getattribute("scode"); //验证码正确 if(checkcode.equals(sessioncode)) { //获取表单数据 string username = request.getparameter("username"); int password = integer.valueof(request.getparameter("password")); //判断用户信息是否正确,查询数据库获取用户信息 authordao ad = new authordao(); author obj = ad.check(username, password); //判断 if(obj != null) { //重新放入用户信息 // httpsession session = request.getsession(); session.setattribute("authorinfo", obj); //设置session的有效期为10秒 session.setmaxinactiveinterval(10); //页面转发 response.sendredirect("user.jsp"); } else { //页面重定向到登录页面 response.sendredirect("index.jsp"); } } else { //验证码不正确 request.setattribute("error_code", "验证码不匹配"); request.getrequestdispatcher("index.jsp").forward(request, response); } } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } }
(6)数据库查询的交互层:authorservlet.java文件。
package com.servlet; import java.io.ioexception; import java.util.list; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import com.dao.authordao; import com.entity.author; /** * servlet implementation class authorservlet */ @webservlet("/authorservlet") public class authorservlet extends httpservlet { private static final long serialversionuid = 1l; /** * @see httpservlet#httpservlet() */ public authorservlet() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub //设置编码方式 request.setcharacterencoding("utf-8"); //查询用户列表 authordao ad = new authordao(); //将dao层中的结果放入list中 list<author> list = ad.queryauthorlist(); request.setattribute("authorlist", list); //请求转发的方式将查询结果放入request中,再将超链接直接访问authorservlet就将信息显示出来了。 request.getrequestdispatcher("uselist.jsp").forward(request, response); } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } }
(7)定义一个authordao类实现查询数据库和检验登录的用户名和密码。
//用于检验登录页面所填入信息是否正确 package com.dao; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; import java.util.arraylist; import java.util.list; import com.entity.author; public class authordao { public author check(string username ,int password) { author obj = null ; try { dbconnection db = new dbconnection(); //获取数据库连接 connection conn = db.getconn(); //设置要执行的数据库语句 string sql = "select *from furnitures where name = ? and id = ?"; preparedstatement ps = conn.preparestatement(sql); //设置用户名和密码放入sql语句 ps.setstring(1, username); ps.setint(2, password); //执行sql查询语句 , 并将执行结果放入结果集中 resultset rs = ps.executequery(); //用户名和密码都正确 if(rs.next()) { //新创建一个obj 将查询结果放入 obj = new author(); obj.setid(rs.getint(1)); obj.setname(rs.getstring(2)); obj.setprice(rs.getint(3)); obj.setnum(rs.getint(4)); obj.setdates(rs.getstring(5)); obj.setstyle(rs.getstring(6)); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } return obj; } public list<author> queryauthorlist(){ author obj = null; //定义一个list集合,用于存放查询结果 list<author> list = new arraylist<author>() ; try { dbconnection db = new dbconnection(); //获取数据库连接 connection conn = db.getconn(); //设置数据库要查询的语句 string sql = "select *from furnitures "; preparedstatement ps = conn.preparestatement(sql); //执行数据库查询语句,并将查询结果放入结果集 resultset rs = ps.executequery(); //利用循环将obj放入list集合中 while(rs.next()) { obj = new author(); obj.setid(rs.getint(1)); obj.setname(rs.getnstring(2)); obj.setprice(rs.getint(3)); obj.setnum(rs.getint(4)); obj.setdates(rs.getstring(5)); obj.setstyle(rs.getstring(6)); //将obj加入到list list.add(obj); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } return list; } }
(8)定义一个验证码生成codeservlet类,用于生成验证码。
package com.servlet; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.ioexception; import java.util.random; import javax.imageio.imageio; import javax.servlet.servletexception; import javax.servlet.servletoutputstream; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; @webservlet("/codeservlet") public class codeservlet extends httpservlet{ //定义验证码的源码 private static final string str ="abcdefghijklmnopqrstuvwxyaabcdefghijklmnopqrstuvwxyz1234567890"; //定义随机数 private random random = new random(); //随机生成四个字符 public string getstr() { string s = ""; int len = str.length(); for(int i=0;i<4;i++) { s+=str.charat(random.nextint(len)); } return s; } //随机颜色 public color getcolor() { int red = random.nextint(256); int green = random.nextint(256); int blue = random.nextint(256); color color = new color(red,green,blue); return color; } @override protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { // todo auto-generated method stub //生成验证码图片 //画板 bufferedimage image = new bufferedimage(70,20,bufferedimage.type_int_rgb ); //画笔 graphics pen = image.getgraphics(); //矩形 pen.fillrect(0, 0, 70, 20); //字体 pen.setfont(new font("微软雅黑",font.bold,20)); //获取4个字符 string code = getstr(); //绘制图片 for(int i=0;i<code.length();i++) { pen.setcolor(getcolor()); pen.drawstring(string.valueof(code.charat(i)), i*15+5, 20);; } //response对象绘制图片到页面,servle输出流进行图片的输出 servletoutputstream sos = resp.getoutputstream(); imageio.write(image, "png", sos); sos.flush(); sos.close(); //验证码放入session httpsession session = req.getsession(); session.setattribute("scode", code); } @override protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { // todo auto-generated method stub dopost(req, resp); } }
(9)创建dbconnectoin.java类用户获取数据库连接。(我用的是mysql)
//获取数据库连接 package com.dao; import java.sql.connection; import java.sql.drivermanager; import java.sql.sqlexception; public class dbconnection { private static string username="填入自己的数据库名"; private static string password="填入自己的数据库密码"; private static string driver = "com.mysql.jdbc.driver"; private static string url="jdbc:mysql://localhost:3306/已经创建数据库名"; private connection conn; static { try { //加载驱动,捕获异常 class.forname(driver); } catch (classnotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } } public dbconnection () throws sqlexception { //连接数据库 conn = drivermanager.getconnection(url,username,password); } //用于获取conn public connection getconn() { return conn; } public void setconn(connection conn) { this.conn = conn; } }
三、页面
(1)登录页面
(2)数据查询页面
(3)查询结果显示页面
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。