Java Web realizes the verification function of login page verification code

Time:2021-4-21

1、 Verification code

Captcha is essentially a picture, and the content of the picture will be generated randomly with the running of the program

The role of verification code: to prevent applications from sending malicious data, to a certain extent, to avoid the attack of malicious programs on the website.
Captcha is essentially a picture, the accurate analysis of the image content is not easy to use the program to achieve.
Captcha drawing: drawing captcha images not only needs to generate the content to be drawn randomly, but also needs to cooperate with a set of API related to drawing in Java.

2、 Effect demonstration

Verification code demo

3、 Give the complete code

(1) Server side code ActionServlet.java

package session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 *Server side merging Servlet
 * 
 * @author QianliangGuo
 */
public class ActionServlet extends HttpServlet {
 @Override
 protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
 //  Set encoding
 request.setCharacterEncoding("utf-8");
 //  Get session
 HttpSession session = request.getSession();
 //Set the session timeout to 10 seconds
// session.setMaxInactiveInterval(10);
 //Get request path
 String uri = request.getRequestURI();
 //  Split path , Keep only logins . Logins in do
 String action = uri.substring(uri.lastIndexOf("/") + 1,uri.lastIndexOf("."));
 //Determine whether the request path is login
 if (action.equals("login")) {
 String uname = request.getParameter("uname");
 String pwd = request.getParameter("pwd");
 //Get the captcha characters submitted by the user
 String vcode = request.getParameter("vcode");
 //Get the latest captcha characters stored in session
 String code = session.getAttribute("code").toString();
 if (code.equals(vcode) &&uname.equals("123") && pwd.equals("123") ) {
 //Bind the logged in user to session
 session.setAttribute("uname", uname);
 //  Redirect to index . jsp
// response.sendRedirect("index.jsp");
 //If cookies are disabled, use URL rewriting
 response.sendRedirect(response.encodeRedirectURL("index.jsp"));
 } else {
 //If login fails, forward to login.jsp
 request.setAttribute ("MSG", "wrong input, please login again!");
 request.getRequestDispatcher("login.jsp").forward(request,response);
 }
 }else if(action.equals("logout")){
 // Disable session
 session.invalidate();
 response.sendRedirect("login.jsp");
 }
 }
}

(2) Draw captcha CodeServlet.java

package session;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 *Draw captcha
 * 
 * @author QianliangGuo
 */
public class CodeServlet extends HttpServlet {
 @Override
 protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
 //Verification code Servlet
 //0. Create a blank picture
 BufferedImage image = new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
 //1. Get the picture brush
 Graphics g = image.getGraphics();
 Random r = new Random();
 //2. Set the brush color
 g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
 //3. Draw the background of the rectangle
 g.fillRect(0, 0, 100, 30);
 //4. Call the custom method to get the alphanumeric string of length 5
 String number = getNumber(5);
 //Get session
 HttpSession session = request.getSession();
 //Set session expiration time to 30 seconds
// session.setMaxInactiveInterval(30);
 // Bind these five random characters to the session
 session.setAttribute("code", number);
 g.setColor(new Color(0,0,0));
 g.setFont(new Font(null,Font.BOLD,24));
 //5. After setting the color font, draw the string
 g.drawString(number, 5, 25);
 //6. Draw 8 interference lines
 for(int i=0;i<8;i++){
 g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255),r.nextInt(255)));
 g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
 }
 response.setContentType("img/jpeg");
 OutputStream ops = response.getOutputStream();
 ImageIO.write(image,"jpeg",ops);
 ops.close();
 
 }
 private String getNumber(int size) {
 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 String number = "";
 Random r = new Random();
 for(int i=0;i<size;i++){
 number+=str.charAt(r.nextInt(str.length()));
 }
 return number;
 }
}

(2) Login page login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<! -- login to the displayed page -- >
<%
 Object msg = request.getAttribute("msg");
 if(msg!=null){
 %>
 <%=msg.toString() %>
 <%} %>
<html>
 <head>
 
 </head>
 
 <body>
 <form action="login.do" method="post">
 User name: < input name = "uname" / ></br>
 Password: < input name = "PWD" type = "password" / ></br>
 Verification Code: < input name = "vcode" / >
 <img src="code" onclick="this.src='code?'+Math.random();"
 Title = "click to replace" / > < br / >
 < input type = submit "value = login / > 
 </form>
 </body>
</html>

(3) The page showing the verification code validateCode.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<! -- page displaying captcha -- >
<html>
 <head>
 < title > verification code
 <! -- move the mouse into the picture and turn it into a hand -- >
 <style type="text/css">
 .s1{
 cursor:pointer;
 }
 </style>
 </head>
 <body>
 <! -- when you click, resend the request to the code, and add a random number to cheat the browser into using a different address -- >
 <img src="code" onclick="this.src='code?'+Math.random();"
 title =" Click Replace "/>
 </body>
</html>

(5)index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<! -- page after successful login -- >
<%
 //Small script: session verification
 Object uname = session.getAttribute("uname");
 if(uname == null){
 // Redirect to login . jsp
 response.sendRedirect("login.jsp");
 return;
 }
 %>
<html>
 <head>
 </head>
 <body>
 <h1>Welcome to: <%= uname.toString () %></h1>
 <a href=" logout.do "Rel =" external nofollow "> Exit</a>
 </body>
</html>

summary

The above is the java web login page verification code verification function introduced by Xiaobian. I hope it can help you. If you have any questions, please leave me a message and Xiaobian will reply you in time. Thank you very much for your support to developer!
If you think this article is helpful to you, please reprint, please indicate the source, thank you!