jsp Web Login Verification

  • 2021-11-24 02:32:23
  • OfStack

jsp Login Verification, Web Login Verification with Verification Code Verification, Login Function Added Verification Code

part_1: Class specially used to generate 1 verification code picture: 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 :  This is a class used to test randomly generated verification code pictures;  
 */ 
public class VerificationCode { 
 
  /** 
   *  Unit test, try 1 Can you automatically generate verification code pictures under  
   */ 
  //  This function is used in unit testing, and here private1 You can't call it outside;  
  /* @Test */ 
  /* public */private void test_fun() { 
    VerificationCode vc = new VerificationCode(); 
    BufferedImage image = vc.getImage(); 
    try { 
      //  Generate a verification code picture and save it to the specified path  
      VerificationCode.output(image, new FileOutputStream(new File( 
          ".\\image\\vcode_2.jpg"))); 
    } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
    } 
 
    //  Output the randomly generated text content to the console for verification  
    System.out.println(vc.getText()); 
  } 
 
  private int w = 70;//  Width  
  private int h = 35;//  Gao  
  private String text;//  Text content ( Verification code string ) 
  private Random r = new Random(); 
  private String[] fontNames = { " Song Style ", " Chinese regular script ", " Blackbody ", " Microsoft Yahei ", " Regular script _GB2312" }; 
  //  The random character set does not include 0 And o , O , 1 And l Because these are not easy to distinguish  
  private String codes = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYXZ"; 
  //  Background color of verification code picture: white  
  private Color bgColor = new Color(255, 255, 255); 
 
  /** 
   *  Return 1 Verification code picture buffer Object: BufferedImage 
   */ 
  public BufferedImage getImage() { 
    BufferedImage image = createImage(); 
    //  Get Drawing Environment (Brush Tool)  
    Graphics2D g2 = (Graphics2D) image.getGraphics(); 
    // sb  :   Used to save the text content of the verification code string  
    StringBuilder sb = new StringBuilder(); 
 
    for (int i = 0; i < 4; ++i) {//  Random generation 4 Characters  
      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();//  Record the text content of the verification code  
    drawLine(image);//  Draw interference lines  
    return image; 
 
  } 
 
  /** 
   * @return  Get the text content of the verification code  
   */ 
  public String getText() { 
    return text; 
  } 
 
  /** 
   * @param image 
   * @param out 
   *       Writes text to the specified output stream. For example, in this test FileOutputStream The specified save path  
   */ 
  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) {//  Painting 3 Interference line  
      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 interface: 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"); 
 
    // Add 1 Request parameters a Because, usually browsers have caches, click to change 1 I didn't respond when I was Zhang, so I added 1 Request parameters, get the current request time, can be accurate to milliseconds, so the parameters of each request are different, so the browser has cache does not hinder;  
    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) { 
      // If you have logged in during this session, redirect directly to 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"> 
       Please log in : 
      <br> 
      <form action="/ServletDemoProject/servlet/LoginVerificationServlet" 
        method="post"> 
        <div> 
           User name:  
          <input type="text" name="username" value="<%=username%>" /> 
          <br> 
        </div> 
 
        <div> 
           Dense    Code:  
          <input type="password" name="password" /> 
          <br> 
        </div> 
        <div> 
           Verification code:  
          <input type="text" name="code_text" size="3" /> 
          <img src="/ServletDemoProject/servlet/GetVerificationCodeServlet" 
            id="img_src" /> 
          <a href="javascript:_change_verity_code()"> Change 1 Zhang </a> 
          <br> 
        </div> 
 
        <div> 
          <font color='red'><%=fdbkMsg%></font> 
          <br> 
        </div> 
 
        <div> 
          <input type="submit" value=" Submit " /> 
          <br> 
        </div> 
      </form> 
    </div> 
  </body> 
</html> 

part_3: servlet for login verification: 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. New 1 A VerificationCode Class;  
    VerificationCode vc = new VerificationCode(); 
 
    // 2. From VerificationCode Obtain in the class BufferedImage Object;  
    BufferedImage bufImage = vc.getImage(); 
 
    // 3. At the same time, get the text content in the verification code and put it in session Domain,   Used for verification;  
    String code_text = vc.getText(); 
    request.getSession().setAttribute("code_text", code_text); 
 
    // 4. Output the generated picture to the client browser  
    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: Prompt interface after successful login: 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) { 
      // If username Is null, indicating that it is not from the normal channel and forwarded to Login Page;  
      request.setAttribute("fdbkMsg", " Don't try to come in through the back door, log in quickly! "); 
      request.getRequestDispatcher("/LOGIN-DEMO/Login.jsp").forward( 
          request, response); 
    } 
  %> 
 
  <body> 
    <br> 
    <%=username%> Has successfully landed.  
    <br> 
    <font> You can choose to browse: </font> 
    <br> 
    <a href="/ServletDemoProject/LOGIN-DEMO/success-page-2.jsp"> Click here to have wonderful things .</a> 
    <br> 
    <a href="/ServletDemoProject/LOGIN-DEMO/success-page-2.jsp"> It's more exciting to click here .</a> 
    <br /> 
    <a href="/ServletDemoProject/LOGIN-DEMO/success-page-2.jsp"> Do you dare to light here .</a> 
    <br /> 
  </body> 
</html> 

part_5: Prompt interface after successful login: 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", " Heheda, is this where you come from? Log in! "); 
      // Forward to login interface : 
      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 = " Morning "; 
    } else 
      am_pm_str_in_chinese = " Afternoon "; 
 
    // set null; 
    sDateFormat = null; 
    today = null; 
    am_pm_str = null; 
  %> 
 
  <body> 
    <br /> 
    <font><b><%=username%><%=am_pm_str_in_chinese%> OK, you can come to the page 2 It's not easy .</b> 
    </font> 
  </body> 
</html> 

Related articles: