1、在用户登录界面如何加入验证码,以及实现功能:
首先在myeclipse10中建立web应用程序结构如下:
在WebRoot下面导入Random.jsp文件,其代码如下:
- <%@ page contentType="p_w_picpath/jpeg" import="java.awt.*,java.awt.p_w_picpath.*,java.util.*,javax.p_w_picpathio.*" %>
- <html>
- <body>
- <%!
- Color getRandColor(int fc,int bc){
- Random r=new Random();
- if(fc>255) fc=255;
- if(bc>255) bc=255;
- int red=fc+r.nextInt(bc-fc);
- int green=fc+r.nextInt(bc-fc);
- int blue=fc+r.nextInt(bc-fc);
- return new Color(red,green,blue);
- }
- %>
- <%
- response.setHeader("Pragma","No-cache");
- response.setHeader("Cache-Control","No-cache");
- response.setHeader("Expires","0");
- Random r=new Random();
- int width=60,height=20;
- BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
- Graphics gc=pic.getGraphics();
- gc.setColor(getRandColor(200,250));
- gc.fillRect(0,0,width,height);
- gc.setFont(new Font("Times New Roman",Font.PLAIN,18));
- gc.setColor(getRandColor(160,200));
- for(int i=0;i<200;i++){
- int x1=r.nextInt(width);
- int x2=r.nextInt(height);
- int x3=r.nextInt(15);
- int x4=r.nextInt(15);
- gc.drawLine(x1,x2,x1+x3,x2+x4);
- }
- gc.setColor(getRandColor(120,240));
- for(int j=0;j<100;j++){
- int x=r.nextInt(width);
- int y=r.nextInt(height);
- gc.drawOval(x,y,0,0);
- }
- String rs="";
- String rn="";
- for(int k=0;k<4;k++){
- rn=String.valueOf(r.nextInt(10));
- rs+=rn;
- gc.setColor(new Color(20+r.nextInt(110),r.nextInt(110),20+r.nextInt(110)));
- gc.drawString(rn,13*k+6,16);
- }
- gc.dispose();
- session.setAttribute("random",rs);
- ImageIO.write(pic,"JPEG",response.getOutputStream());
- out.clear();
- out=pageContext.pushBody();
- %>
- </body>
- </html>
然后建立登录文件login.jsp,在其中加入如下代码:
- <input type="text" name="random" />
- <img name="randImage" id="randImage" src="Random.jsp" border="2" />
- <a href="javascript:loadp_w_picpath();"><font size=3>换一张</font></a>
- <%-- 调用js,中的loadp_w_picpath()方法,实现验证码,随即换。 --%>
所调用的js代码如下:
- <script language="javascript">
- function loadp_w_picpath(){
- document.getElementById("randImage").src = "Random.jsp?"+Math.random();
- }
- </script>
这是实现单击--->换一张,验证码自动调换,如下图所示:
其次:在登录的LoginServlet.java中,接收并判断验证码是否正确,相关代码显示如下:
- //检验验证码
- try{
- random=request.getParameter("random");//自己输入的随机验证码
- String ran=(String)session.getAttribute("random");//得到Random.jsp中的随机验证码
- if(!random.equals(ran)){
- String s="<script language='javascript'>alert('验证码输入错误!!');window.location.href='login.jsp'</script>";
- out.print(s);
- return;
- }
- }catch(Exception e){
- System.out.println("LoginServlet.java中,检验验证码抛出异常!");
- e.printStackTrace();
- }
第一个得到的random是自己从文本框中输入的随机验证码,第二个ran是从Random.jsp页面中 得到的,可以从Random.jsp代码看出来
- gc.dispose();
- session.setAttribute("random",rs);
- ImageIO.write(pic,"JPEG",response.getOutputStream());
- out.clear();
- out=pageContext.pushBody();
至此,在写下相关登录验证代码,即可完成相应的验证码登录操作,感觉灰爽,可以试下哦!
转载于:https://blog.51cto.com/makaiyuan/1068866