当前位置: 首页 > article >正文

java web配置servlet实现图像验证码

老规矩,话不多说直接上代码

第一步:首先配置一个产生验证码的类


public class VerifyCode {private int w = 70;private int h = 35;private Random r = new Random();// {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}private String[] fontNames  = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};// 可选字符private String codes  = "0123456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";// 背景色private Color bgColor  = new Color(255, 255, 255);// 验证码上的文本private String text ;// 生成随机的颜色private Color randomColor () {int red = r.nextInt(150);int green = r.nextInt(150);int blue = r.nextInt(150);return new Color(red, green, blue);}// 生成随机的字体private Font randomFont () {int index = r.nextInt(fontNames.length);String fontName = fontNames[index];//生成随机的字体名称int style = r.nextInt(4);//生成随机的样式, 0(无样式), 1(粗体), 2(斜体), 3(粗体+斜体)int size = r.nextInt(5) + 24; //生成随机字号, 24 ~ 28return new Font(fontName, style, size);}// 画干扰线private void drawLine (BufferedImage image) {int num  = 3;//一共画3条Graphics2D g2 = (Graphics2D)image.getGraphics();for(int i = 0; i < num; i++) {//生成两个点的坐标,即4个值int x1 = r.nextInt(w);int y1 = r.nextInt(h);int x2 = r.nextInt(w);int y2 = r.nextInt(h);g2.setStroke(new BasicStroke(1.5F));g2.setColor(Color.BLUE); //干扰线是蓝色g2.drawLine(x1, y1, x2, y2);//画线}}// 随机生成一个字符private char randomChar () {int index = r.nextInt(codes.length());return codes.charAt(index);}// 创建BufferedImageprivate BufferedImage createImage () {BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);Graphics2D g2 = (Graphics2D)image.getGraphics();g2.setColor(this.bgColor);g2.fillRect(0, 0, w, h);return image;}// 调用这个方法得到验证码public BufferedImage getImage () {BufferedImage image = createImage();//创建图片缓冲区Graphics2D g2 = (Graphics2D)image.getGraphics();//得到绘制环境StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本// 向图片中画4个字符for(int i = 0; i < 4; i++)  {//循环四次,每次生成一个字符String s = randomChar() + "";//随机生成一个字母sb.append(s); //把字母添加到sb中float x = i * 1.0F * w / 4; //设置当前字符的x轴坐标g2.setFont(randomFont()); //设置随机字体g2.setColor(randomColor()); //设置随机颜色g2.drawString(s, x, h-5); //画图}this.text = sb.toString(); //把生成的字符串赋给了this.textdrawLine(image); //添加干扰线return image;}// 返回验证码图片上的文本public String getText () {return text;}// 保存图片到指定的输出流public static void output (BufferedImage image, OutputStream out)throws IOException {ImageIO.write(image, "JPEG", out);}
}

注释写的很清楚了,自己看。

第二步:在项目中配置好servlet


配置servlet有两种方式,网上挺多的介绍挺全的,感兴趣的话自己百度,由于我用的是springboot框架,用注解的方式配置servlet挺方便的,于是我采取这种方式来进行配置:

第一个servlet:用于相应网页的请求,向网页输出咱们写的验证码

@WebServlet(name = "VerifyCodeServlet", value = "/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//创建对象VerifyCode vc = new VerifyCode();//获取图片对象BufferedImage bi = vc.getImage();//获得图片的文本内容String text = vc.getText();// 将系统生成的文本内容保存到session中request.getSession().setAttribute("text", text);//向浏览器输出图片vc.output(bi, response.getOutputStream());}
}

他对应jsp中的这样一句话:

验证码:<input type="text" name="image"><img src="/VerifyCodeServlet">

第二个servlet:用于处理登录请求的逻辑处理

@WebServlet(name = "LoginServlet3", value = "/LoginServlet3")
public class LoginServlet3 extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/*System.out.println("af");*/// 编码request.setCharacterEncoding("utf-8");// 获取请求参数/*拿到页面传过来的手动输入的验证码, 该验证码要和生成图片上的文本验证码比较, 如果相同, 验证码输入成功!*/String imageText = request.getParameter("image");// 图片的验证码String text = (String) request.getSession().getAttribute("text");System.out.println(text+"    "+imageText);if (!text.equalsIgnoreCase(imageText)) {//equalsIgnoreCase意思是不考虑大小写request.setAttribute("imageMess", "验证码输入错误!");//getRequestDispatcher这个方法将请求从一个 Servlet or JSP目标资源 上 转发到服务器上的另一个资源(servlet、JSP 文件或 HTML 文件,这些资源必须是当前Web上下文中的),让其它的资源去生成响应数据。//例如用户请求的是目标资源A,A接受到请求后,转发到B,真正产生响应数据是被转发的资源B,而A只是起个引导转发作用。浏览器的地址栏不会变,依然是A的URL。//    这个方法可以允许被请求的目标资源做一些准备工作后,再让转发的资源去响应请求。//request.getRequestDispatcher(url)的url可以是相对路径也可以是绝对路径。//request.getRequestDispatcher(url)之所以可以使用相对路劲,是因为在getRequestDispatcher(url)方法中封装了// ServletContext.getRealPath()以获得相应的项目根路径,再通过字符串相加,从而可以获得一个完整的路径request.getRequestDispatcher("/admin/views/login3.jsp").forward(request, response);return;}// 获取用户名和密码String username = request.getParameter("username");String password = request.getParameter("password");if ("haha".equals(username) && "123".equals(password)) {// 将用户信息保存到session中request.getSession().setAttribute("username", username);// 使用cookie实现回写用户名Cookie cookie = new Cookie("username", username);cookie.setMaxAge(60 * 60);// 通过响应头发送cookieresponse.addCookie(cookie);// 重定向登录成功界面response.sendRedirect(request.getContextPath() + "/admin/views/success3.jsp");//也可以直接写controller里的mapping//sendRedirect只能用response调用,可以用相对路径(直接用),也可以用相对路径(需加应用路径)//response.sendRedirect("third?name=jay");//   或//   response.sendRedirect(request.getContextPath()+"/third?name=jay");} else {request.setAttribute("error", "用户名或密码错误!");request.getRequestDispatcher("/admin/views/login3.jsp").forward(request, response);}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}

注释写的超级详细了,我不想再多说。

写好了servlet,别忘了在启动文件里加一个注解来扫包:也可以不写basePackages,这样的话扫整个项目。

@ServletComponentScan(basePackages = "com.example.learnsecurity.learnsecurity.Servlet")   //启动器启动时,扫描本目录以及子目录带有的webservlet注解的

第三步:jsp代码如下


login3.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>登录界面</title>
</head>
<body>
<%// 获取浏览器发送过来的cookie, 获取用户信息Cookie[] cookies = request.getCookies();String username = "";if (cookies != null) {for (Cookie cookie : cookies) {if ("username".equals(cookie.getName())) {username = cookie.getValue();}}}
%>
<font color="red">${requestScope.message}</font>
<form action="/LoginServlet3" method="post">用户名:<input type="text" name="username" value="<%= username%>"><font color="red">${requestScope.error}</font><br>密码:<input type="password" name="password"><br>验证码:<input type="text" name="image"><img src="/VerifyCodeServlet"><input type="button" value="看不清? 换一张." id="btn"><font color="red">${requestScope.imageMess}</font><br><input type="submit" value="登录">
</form>
<script type="text/javascript">document.getElementById("btn").onclick = function () {// 获取img元素// 为了让浏览器发送请求到servlet, 所以一定要改变srcdocument.getElementsByTagName("img")[0].src ="/VerifyCodeServlet?time=" + new Date().getTime();};
</script></body>
</html>

seccess3.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>成功登录</title>
</head>
<body>
<%// 获取用户信息String username = (String) session.getAttribute("username");if (username == null) {// 保存错误信息到request中, 然后转发到login3.jsp中, 提醒登录request.setAttribute("message", "请登录!");// 转发到登录页面request.getRequestDispatcher("/login3.jsp").forward(request, response);}
%>
<h2>欢迎登录:${sessionScope.username}!!!</h2>
</body>
</html>

第四步:运行过程说明: 


首先,地址栏输入localhost:+port+/login3,经过controller跳转到了login3.jsp页面

至于为什么会显示出二维码,上面讲到了,这是login3.jsp中下面这句话的功劳:

验证码:<input type="text" name="image"><img src="/VerifyCodeServlet">

 那点击看不清?换一张是怎么换的?是login3.jsp里的js在作用:

<script type="text/javascript">document.getElementById("btn").onclick = function () {// 获取img元素// 为了让浏览器发送请求到servlet, 所以一定要改变srcdocument.getElementsByTagName("img")[0].src ="/VerifyCodeServlet?time=" + new Date().getTime();};
</script>

 然后当我们输入在第二个servlet里写死的用户名和密码后,点击提交,就会被过滤器拦截,然后转发请求到LoginServlet3,在这里有我们对于登录的逻辑处理工作。

不想说了,注释写的很清楚了,自己看看收获更大。

 

http://www.lryc.cn/news/2416371.html

相关文章:

  • artDialog的使用笔记
  • 冰河木马简易使用 ——病毒木马 003
  • 饼状图(PieChart)与柱形图(BarChart)的使用
  • 【视频编解码】H264入门
  • 你们大学还用Protel 99 SE、51单片机吗?
  • ORA-12514: TNS: 监听程序当前无法识别连接描述符中请求的服务【解决思路】
  • 【小呆的力学笔记】弹塑性力学的初步认知三:广义胡克定律
  • linux mrtg 命令,linux服务器之流量监控(MRTG)
  • 【修复版】免费微信小游戏源码h5赛马php网页开源可二次开发,附安装教程
  • css单线边框_css border-collapse设置表格单线边框和双线边框
  • Linux AVG ANTIVIRUS FREE使用介绍
  • CPE上的STUN和TR069功能详解和实验
  • Divx编解码器的研究与设计
  • 系统结构期末复习(四)指令级并行
  • deleteRow() 连续删除多行
  • js发送邮件
  • 怎么查看文件的MD5码
  • 一、 QTP的前世今生
  • 基于VirtualBox虚拟机安装Ubuntu图文教程
  • jersey 入门示例_Jersey Web Service Hello World Java示例
  • 12款国内外企业协作工具推荐
  • SEO数据监控技巧都有哪些?
  • 如何优化网页加载速度?
  • 如何利用Python监控你女/男朋友每天都在浏览什么网站?
  • 表白,整人,无门槛,娱乐代码
  • Mac+virtualbox安装win7
  • NRF24L01 无线模块
  • CSS min-height 属性
  • STM32F103实验定时器
  • javascript——JS 实现下拉菜单