欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSP实现登录功能之添加验证码

程序员文章站 2023-11-24 20:44:58
jsp登陆验证,网页登陆验证带验证码校验,登录功能之添加验证码 part_1:专门用于生成一个验证码图片的类:verificationcode.java pac...

jsp登陆验证,网页登陆验证带验证码校验,登录功能之添加验证码

part_1:专门用于生成一个验证码图片的类:verificationcode.java

package cn.mike.javase.test; 
import java.awt.color; 
import java.awt.font; 
import java.awt.graphics2d; 
import java.awt.image.bufferedimage; 
import java.io.file; 
import java.io.filenotfoundexception; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.io.outputstream; 
import java.util.random; 
import javax.imageio.imageio; 
import org.junit.test; 
/** 
 * @author : administrator 
 * @function : 这是用来测试随机生成验证码图片的类; 
 */ 
public class verificationcode { 
  /** 
   * 单元测试,试一下能不能自动生成验证码图片 
   */ 
  // 这个函数是单元测试时使用的,这里private一下外面就调用不到了; 
  /* @test */ 
  /* public */private void test_fun() { 
    verificationcode vc = new verificationcode(); 
    bufferedimage image = vc.getimage(); 
    try { 
      // 生成验证码图片,并保存到指定的路径 
      verificationcode.output(image, new fileoutputstream(new file( 
          ".\\image\\vcode_2.jpg"))); 
    } catch (filenotfoundexception e) { 
      e.printstacktrace(); 
    } 
    // 将随机生成的文本内容输出到控制台,用于校验 
    system.out.println(vc.gettext()); 
  } 
  private int w = 70;// 宽 
  private int h = 35;// 高 
  private string text;// 文本内容(验证码字符串) 
  private random r = new random(); 
  private string[] fontnames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_gb2312" }; 
  // 随机字符集合中不包括0和o,o,1和l,因为这些不易区分 
  private string codes = "23456789abcdefghijkmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyxz"; 
  // 验证码图片的背景色:白色 
  private color bgcolor = new color(255, 255, 255); 
  /** 
   * 返回一个验证码图片buffer对象:bufferedimage 
   */ 
  public bufferedimage getimage() { 
    bufferedimage image = createimage(); 
    // 获取绘图环境(画笔工具) 
    graphics2d g2 = (graphics2d) image.getgraphics(); 
    // sb : 用来保存验证码字符串文本内容 
    stringbuilder sb = new stringbuilder(); 
    for (int i = 0; i < 4; ++i) {// 随机生成4个字符 
      string s = randomchar() + ""; 
      sb.append(s); 
      float x = i * 1.0f * w / 4; 
      g2.setfont(randomfont()); 
      g2.setcolor(randomcolor()); 
      g2.drawstring(s, x, h - 5); 
    } 
    this.text = sb.tostring();// 记录验证码文本内容 
    drawline(image);// 画干扰线 
    return image; 
  } 
  /** 
   * @return 获取验证码文本内容 
   */ 
  public string gettext() { 
    return text; 
  } 
  /** 
   * @param image 
   * @param out 
   *      将文本写到指定的输出流。比如本测试中fileoutputstream指定的保存路径 
   */ 
  public static void output(bufferedimage image, outputstream out) { 
    try { 
      imageio.write(image, "jpeg", out); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
  } 
  private void drawline(bufferedimage image) { 
    graphics2d g2 = (graphics2d) image.getgraphics(); 
    for (int i = 0; i < 3; ++i) {// 画3条干扰线 
      int x1 = r.nextint(w); 
      int y1 = r.nextint(h); 
      int x2 = r.nextint(w); 
      int y2 = r.nextint(h); 
      g2.setcolor(color.blue); 
      g2.drawline(x1, y1, x2, y2); 
    } 
  } 
  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); 
    int size = r.nextint(5) + 24; 
    return new font(fontname, style, size); 
  } 
  private char randomchar() { 
    int index = r.nextint(codes.length()); 
    return codes.charat(index); 
  } 
  private 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; 
  } 
}

part_2:登录界面:login.jsp

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> 
<% 
  string path = request.getcontextpath(); 
  string basepath = request.getscheme() + "://" 
      + request.getservername() + ":" + request.getserverport() 
      + path + "/"; 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
  <head> 
    <base href="<%=basepath%>"> 
    <title>my jsp 'login.jsp' starting page</title> 
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="expires" content="0"> 
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="this is my page"> 
    <!-- 
  <link rel="stylesheet" type="text/css" href="styles.css"> 
  --> 
    <script type="text/javascript"> 
  function _change_verity_code() { 
    var imgelem = document.getelementbyid("img_src"); 
    //添加一个请求参数a是因为,通常浏览器都有缓存,点击换一张的时候没反应,所以加一个请求参数,获取当前请求时间,可以精确到毫秒,所以每次请求的参数都不同,所以浏览器有缓存也不妨碍; 
    imgelem.src = "/servletdemoproject/servlet/getverificationcodeservlet?a=" 
        + new date().gettime(); 
  } 
</script> 
  </head> 
  <% 
    string fdbkmsg = (string) request.getattribute("fdbkmsg"); 
    if (null == fdbkmsg) { 
      fdbkmsg = ""; 
    } 
  %> 
  <% 
    boolean logedin = (boolean) session.getattribute("logedin"); 
    if (null == logedin) { 
      logedin = false; 
    } else if (logedin) { 
      //如果在本次会话已经登陆,直接重定向到success-page-1 
      response 
          .sendredirect("/servletdemoproject/login-demo/success-page-1.jsp"); 
    } 
  %> 
  <% 
    string username = ""; 
    cookie[] cookies = request.getcookies(); 
    if ((null != cookies) && (cookies.length > 0)) { 
      for (cookie c : cookies) { 
        if ("admin".equals(c.getvalue())) { 
          username = "admin"; 
          break; 
        } 
      } 
    }//end if-condition 
  %> 
  <body> 
    <br> 
    <div align="center"> 
      请登录: 
      <br> 
      <form action="/servletdemoproject/servlet/loginverificationservlet" 
        method="post"> 
        <div> 
          用户名: 
          <input type="text" name="username" value="<%=username%>" /> 
          <br> 
        </div> 
        <div> 
          密  码: 
          <input type="password" name="password" /> 
          <br> 
        </div> 
        <div> 
          验证码: 
          <input type="text" name="code_text" size="3" /> 
          <img src="/servletdemoproject/servlet/getverificationcodeservlet" 
            id="img_src" /> 
          <a href="javascript:_change_verity_code()">换一张</a> 
          <br> 
        </div> 
        <div> 
          <font color='red'><%=fdbkmsg%></font> 
          <br> 
        </div> 
        <div> 
          <input type="submit" value="提交" /> 
          <br> 
        </div> 
      </form> 
    </div> 
  </body> 
</html> 

part_3:处理登录校验的servlet :loginverificationservlet.java

package cn.mike.servlet.test_1212; 
import java.awt.image.bufferedimage; 
import java.io.ioexception; 
import javax.servlet.servletexception; 
import javax.servlet.http.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import cn.mike.javase.test.verificationcode; 
public class getverificationcodeservlet extends httpservlet { 
  private static final long serialversionuid = -3520994675366100452l; 
  public void doget(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    // 1.新建一个verificationcode类; 
    verificationcode vc = new verificationcode(); 
    // 2.从verificationcode类中获取bufferedimage对象; 
    bufferedimage bufimage = vc.getimage(); 
    // 3.同时获取验证码中的文本内容,并放到session域中, 用于校验; 
    string code_text = vc.gettext(); 
    request.getsession().setattribute("code_text", code_text); 
    // 4.将生成的图片输出到客户端浏览器 
    verificationcode.output(bufimage, response.getoutputstream()); 
  }// end method-doget 
  public void dopost(httpservletrequest request, httpservletresponse response) 
      throws servletexception, ioexception { 
    // do same as get-method : 
    doget(request, response); 
  }// end method-dopost 
} 

part_4:成功登陆后的提示界面1:success-page-1.jsp

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> 
<% 
  string path = request.getcontextpath(); 
  string basepath = request.getscheme() + "://" 
      + request.getservername() + ":" + request.getserverport() 
      + path + "/"; 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
  <head> 
    <base href="<%=basepath%>"> 
    <title>my jsp 'success-page-1.jsp' starting page</title> 
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="expires" content="0"> 
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="this is my page"> 
    <!-- 
  <link rel="stylesheet" type="text/css" href="styles.css"> 
  --> 
  </head> 
  <% 
    string username = (string) session.getattribute("username"); 
    if (null == username) { 
      //如果username为空值,说明不是通过正常渠道来的,转发到login页面; 
      request.setattribute("fdbkmsg", "别想走后门进来,赶紧登录!"); 
      request.getrequestdispatcher("/login-demo/login.jsp").forward( 
          request, response); 
    } 
  %> 
  <body> 
    <br> 
    <%=username%>已经成功登陆。 
    <br> 
    <font>您可以选择浏览:</font> 
    <br> 
    <a href="/servletdemoproject/login-demo/success-page-2.jsp">点这儿有精彩.</a> 
    <br> 
    <a href="/servletdemoproject/login-demo/success-page-2.jsp">点这儿更精彩.</a> 
    <br /> 
    <a href="/servletdemoproject/login-demo/success-page-2.jsp">你敢点这儿吗.</a> 
    <br /> 
  </body> 
</html> 

part_5:成功登陆后的提示界面1:success-page-2.jsp

<%@ page language="java" import="java.util.date" pageencoding="utf-8"%> 
<%@ page language="java" import="java.text.simpledateformat"%> 
<% 
  string path = request.getcontextpath(); 
  string basepath = request.getscheme() + "://" 
      + request.getservername() + ":" + request.getserverport() 
      + path + "/"; 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
  <head> 
    <base href="<%=basepath%>"> 
    <title>my jsp 'success-page-2.jsp' starting page</title> 
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="expires" content="0"> 
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="this is my page"> 
    <!-- 
  <link rel="stylesheet" type="text/css" href="styles.css"> 
  --> 
  </head> 
  <% 
    string username = (string) session.getattribute("username"); 
    if (null == username) { 
      request.setattribute("fdbkmsg", "呵呵嗒,这里是你来的地方吗?快登陆!"); 
      //转发到登录界面: 
      request.getrequestdispatcher("/login-demo/login.jsp").forward( 
          request, response); 
    } 
    simpledateformat sdateformat = new simpledateformat("a"); 
    date today = new date(); 
    string am_pm_str = sdateformat.format(today); 
    string am_pm_str_in_chinese = ""; 
    if ("am".equalsignorecase(am_pm_str)) { 
      am_pm_str_in_chinese = "上午"; 
    } else 
      am_pm_str_in_chinese = "下午"; 
    // set null; 
    sdateformat = null; 
    today = null; 
    am_pm_str = null; 
  %> 
  <body> 
    <br /> 
    <font><b><%=username%><%=am_pm_str_in_chinese%>好,能来到页面2真不简单.</b> 
    </font> 
  </body> 
</html> 

以上所述是小编给大家介绍的jsp实现登录功能之添加验证码,希望对大家有所帮助