jsp实现简单图片验证码功能 |
本文实例为大家分享了jsp实现简单图片验证码的具体代码,供大家参考,具体内容如下 一、实现的功能分析(1)在登陆页面加验证码的功能,起到一定的安全性 。在输入正确的验证码,用户名和密码的情况下,才可以实现登录 。 二、代码实现(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"/><span>${error_code}</span><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)查询结果显示页面 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 。 |