The verification code of java web login interface is automatically generated. Click to regenerate the verification code and verify the verification code with the input box

Make a light 2022-05-22 12:19:03 阅读数:895

verificationcodejavaweblogin

When entering the login interface , Verification code image is automatically generated , The color of the verification code picture is random , Random letter color , The code just randomly generates lowercase English letters , There are no uppercase letters and numbers

  Click the verification code picture to regenerate the verification code

When the verification code is entered incorrectly , Prompt out

  The login account and password can be verified only after the verification code is entered correctly

Used in medium and large projects , Now the key codes are shown as follows

login.jsp Interface ( Note that... Has been imported at this time jquery It's packed )

<img src="CheckCodeServlet" width="100%" height="30" id="checkCodeImg"/>
<script type="text/javascript">
$("#checkCodeImg").click(function () {
// Reset the value of the property , When you click on the picture
$("#checkCodeImg").attr("src","CheckCodeServlet?m="+Math.random());
});
</script>

CheckCodeServlet class

package com.it.servlets;
import javax.imageio.ImageIO;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// adopt java in awt Draw the verification code picture of the class provided in
// 1. Create a picture
int height=90;// Captcha height
int width=300;// Verification code width
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);// Instantiate an image object
// 2. Draw picture objects , Get the pen that draws the picture from the picture object
Graphics2D pen = image.createGraphics();
//a. Draw the background
pen.setColor(getRandomColor());
pen.fillRect(0,0,width,height);// Draw a solid rectangle
//b. Draw the verification code string
int letterNum=4;// The number of characters on the verification code picture
int space=20;// The space between two letters on the verification code picture
int letterWidth=(width-(letterNum+1)*space)/letterNum;// Calculate the width occupied by each letter
// for Cycle every cycle , Draw a letter ( In lowercase ascii code :97-122)
Random random = new Random();
String code ="";
for (int i=0;i<letterNum;i++){
// Randomly generate a lowercase letter
int ascii = random.nextInt(26) + 97;//97-122
byte[] bytes={(byte) ascii};
String letter=new String(bytes);
code = code + letter;// In order to save the verification code characters to session
// Draw letters
pen.setColor(getRandomColor());
pen.setFont(new Font("Gulim",Font.BOLD,70));
pen.drawString(letter,space+(letterWidth+space)*i,height-space);// Write the letter on the canvas
}
HttpSession session = req.getSession();
session.setAttribute("code",code);
// Add picture interference , Prevent the machine from automatically recognizing
// After the picture is drawn , Pass the picture through response The output stream responds to the client
ImageIO.write(image,"png",resp.getOutputStream());
}
private Color getRandomColor() {
Random random = new Random();
int r=random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
Color color = new Color(r, g, b);
return color;
}
}

ManagerLoginServlet class

String checkCode = req.getParameter("checkCode");
// Check the captcha first , Only when the verification code is correct , Just check the login account and password
// First of all get session, Get more session Medium code The value of the property , Compare with the value of the input box
if (req.getSession().getAttribute("code").equals(checkCode)){
// When the verification code is correct , Perform login name and login password verification
}else {
// Verification code error
req.setAttribute("tips","<label style='color:red'> Login failed , Verification code error !</label>");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}

Here is the code in the complete class

login.jsp Interface ( Note that... Has been imported at this time jquery It's packed )

<%--
Created by IntelliJ IDEA.
User: lijianglin
Date: 2022/5/19
Time: 17:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="assets/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="assets/css/ace.min.css" />
<link rel="stylesheet" href="assets/css/ace-rtl.min.css" />
<link rel="stylesheet" href="assets/css/ace-skins.min.css" />
<link rel="stylesheet" href="css/style.css"/>
<script src="assets/js/ace-extra.min.js"></script>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="assets/layer/layer.js" type="text/javascript"></script>
<title> Sign in </title>
</head>
<body class="login-layout Reg_log_style" style="background: url(images/login_bg.png);">
<div class="logintop">
<span> Welcome to the background management interface platform </span>
<ul>
<li><a href="#"> Back to the home page </a></li>
<li><a href="#"> help </a></li>
<li><a href="#"> About </a></li>
</ul>
</div>
<div class="loginbody">
<div class="login-container">
<div class="center"></div>
<div class="space-6"></div>
<div class="position-relative">
<div id="login-box" class="login-box widget-box no-border visible" style="margin-top: 50px;">
<div class="widget-body" >
<div class="widget-main" >
<h4 class="header blue lighter bigger">
<i class="icon-coffee green"></i>
Administrator login
</h4>
<div class="login_icon"><img src="images/login.png" /></div>
<form class="" id="form1" action="ManagerLoginServlet" method="post">
<fieldset>
<ul>
<li class="frame_style form_error">
<label class="user_icon"></label>
<input name="loginName" title=" Login name " type="text" id="username"/><i> user name </i>
</li>
<li class="frame_style form_error">
<label class="password_icon"></label>
<input name="loginPwd" title=" The login password " type="password" id="userpwd"/><i> password </i>
</li>
<li class="frame_style form_error">
<label class="Codes_icon"></label>
<input name="checkCode" title=" Verification Code " type="text" id="Codes_text"/><i> Verification Code </i>
<div class="Codes_region">
<img src="CheckCodeServlet" width="100%" height="30" id="checkCodeImg"/>
<script type="text/javascript">
$("#checkCodeImg").click(function () {
// Reset the value of the property , When you click on the picture
$("#checkCodeImg").attr("src","CheckCodeServlet?m="+Math.random());
});
</script>
</div>
</li>
</ul>
<div class="space"></div>
<div class="clearfix">
<label class="inline">
<input type="checkbox" class="ace">
<span class="lbl"> Save password </span>
</label>
<button type="submit" class="width-35 pull-right btn btn-sm btn-primary" id="login_btn">
<i class="icon-key"></i>
Sign in
</button>
</div>
<div class="space-4"></div>
</fieldset>
</form>
<div class="social-or-login center">
<span class="bigger-110"> notice </span>
</div>
<div class="social-login center">
<%-- from ManagerLoginServlet Class , Get attribute value--%>
Tips ${tips}
</div>
</div><!-- /widget-main -->
<div class="toolbar clearfix"></div>
</div><!-- /widget-body -->
</div><!-- /login-box -->
</div><!-- /position-relative -->
</div>
</div>
<div class="loginbm"> copyright 2021</div><strong></strong>
</body>
</html>
<script>
$('#form1').on('submit', function(){
var num=0;
var str="";
$("input[type$='text'],input[type$='password']").each(function(n){
if($(this).val()=="")
{
layer.alert(str+=""+$(this).attr("title")+" Can't be empty !\r\n",{
title: ' Prompt box ',
icon:0,
});
num++;
return false;
}
});
if(num>0){ return false;}
else{
// The administrator has entered the password , Login name , Verification Code
return true;
}
});
$(document).ready(function(){
$("input[type='text'],input[type='password']").blur(function(){
var $el = $(this);
var $parent = $el.parent();
$parent.attr('class','frame_style').removeClass(' form_error');
if($el.val()==''){
$parent.attr('class','frame_style').addClass(' form_error');
}
});
$("input[type='text'],input[type='password']").focus(function(){
var $el = $(this);
var $parent = $el.parent();
$parent.attr('class','frame_style').removeClass(' form_errors');
if($el.val()==''){
$parent.attr('class','frame_style').addClass(' form_errors');
} else{
$parent.attr('class','frame_style').removeClass(' form_errors');
}
});
})
</script>

CheckCodeServlet class

package com.it.servlets;
import javax.imageio.ImageIO;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// adopt java in awt Draw the verification code picture of the class provided in
// 1. Create a picture
int height=90;// Captcha height
int width=300;// Verification code width
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);// Instantiate an image object
// 2. Draw picture objects , Get the pen that draws the picture from the picture object
Graphics2D pen = image.createGraphics();
//a. Draw the background
pen.setColor(getRandomColor());
pen.fillRect(0,0,width,height);// Draw a solid rectangle
//b. Draw the verification code string
int letterNum=4;// The number of characters on the verification code picture
int space=20;// The space between two letters on the verification code picture
int letterWidth=(width-(letterNum+1)*space)/letterNum;// Calculate the width occupied by each letter
// for Cycle every cycle , Draw a letter ( In lowercase ascii code :97-122)
Random random = new Random();
String code ="";
for (int i=0;i<letterNum;i++){
// Randomly generate a lowercase letter
int ascii = random.nextInt(26) + 97;//97-122
byte[] bytes={(byte) ascii};
String letter=new String(bytes);
code = code + letter;// In order to save the verification code characters to session
// Draw letters
pen.setColor(getRandomColor());
pen.setFont(new Font("Gulim",Font.BOLD,70));
pen.drawString(letter,space+(letterWidth+space)*i,height-space);// Write the letter on the canvas
}
HttpSession session = req.getSession();
session.setAttribute("code",code);
// Add picture interference , Prevent the machine from automatically recognizing
// After the picture is drawn , Pass the picture through response The output stream responds to the client
ImageIO.write(image,"png",resp.getOutputStream());
}
private Color getRandomColor() {
Random random = new Random();
int r=random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
Color color = new Color(r, g, b);
return color;
}
}

ManagerLoginServlet class

package com.it.servlets;
import com.it.entity.Manager;
import com.it.service.ManagerService;
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 java.io.IOException;
import java.sql.SQLException;
// For administrator login authentication servlet
@WebServlet("/ManagerLoginServlet")
public class ManagerLoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// doGet Written in doPost Method , Yes, all methods are doPost Method , In this way, whether it comes from get still post Can successfully call the method
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. Receiving account number 、 password 、 Verification Code
req.setCharacterEncoding("utf-8");
// Get the input from the input box , The parameter is the name of the input box .
String loginName = req.getParameter("loginName");
String loginPwd = req.getParameter("loginPwd");
String checkCode = req.getParameter("checkCode");
// Check the captcha first , Only when the verification code is correct , Just check the login account and password
// First of all get session, Get more session Medium code The value of the property , Compare with the value of the input box
if (req.getSession().getAttribute("code").equals(checkCode)){
// When the verification code is correct , Perform login name and login password verification
// 2. call ManagerService check
ManagerService managerService = new ManagerService();
try {
Manager manager = managerService.checkManagerLogin(loginName, loginPwd);
// 3. Judge the verification results
if (manager==null){
// Login failed , Jump to the login interface and give an error prompt
req.setAttribute("tips","<label style='color:red'> Login failed , Wrong password or account number !</label>");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}else {
// Login successful , Jump to index.jsp Interface
resp.sendRedirect("index.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
}
}else {
// Verification code error
req.setAttribute("tips","<label style='color:red'> Login failed , Verification code error !</label>");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
}

copyright:author[Make a light],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/142/202205211820122905.html