Jsp + java servlet realizes simple user login and registration page (connect to database, login page contains verification code, no login within two weeks, etc.)

Osu rebyzmjz 2020-11-11 11:46:28
jsp java servlet realizes simple

Function is introduced

This project uses jsp and servlet Simple user login . The main logic is :

  • If the user doesn't exist , Register first ( The registration information is synchronized to the database ).
  • After registration , You can enter the login page to login your account .
  • If the account exists , Then jump to the welcome screen correctly , Otherwise, the user will be prompted to input wrong account information .
  • Users need to fill in the verification code when they log on the page. At the same time, they can check whether they are free to log in within two weeks .
  • The user enters the welcome interface , It will show how many times the user has logged in , If it is not the first login, the last login time will be displayed .
  • If the user goes directly to welcome,( No sign in , Open it directly welcome.jsp) Will jump to the login page , Prevent illegal login .

Preparation for preliminary work

1. Installed Tomcat And can be used successfully .
2. Due to the need to connect to the database , This project uses mysql database , Need to introduce
mysql-connector-java-5.1.9.jar package ( It can be downloaded officially or through maven introduce mysql rely on ), We need to pay attention to mysql-connector-java-5.1.9.jar Need to put in C:\Program Files\Java\jdk1.8.0_201\jre\lib\ext Under the path , Otherwise, the database connection will be abnormal .
introduce maven rely on :


Implement login page

Create database

 CREATE TABLE `usert` (
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL

At this point, the database is empty , No data need to be registered to login successfully .

Three page processing

The welcome screen (LoginServlet.jsp)

1. Code

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script type="text/javascript">
<%-- Judge the input account information , The account password cannot be empty and the verification code must be entered --%>
function validate() {


alert(" Account number cannot be empty ");

alert(" The password cannot be empty ");

alert(" Please enter the verification code ");
function refresh() {

<form name="login" action="/LoginCl" method="post">
user name :<input type="text" name="username1"><br>
password :<input type="password" name="passwd"><br>
<input type="checkbox" name="keep" > No landing in two weeks <br>
Verification Code :<input type="text" name="code" size=10>
<%-- Click on the picture to refresh the verification code --%>
<img name="imgValidate" src = "index.jsp" onclick="refresh()" ><br>
<%-- Pay attention to button and submit The difference between --%>
<input type="button" value=" Sign in " onclick="validate()">
String username = null;
String password = null;
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {

if ("username".equals(cookies[i].getName())) {

username = cookies[i].getValue();
} else if ("password".equals(cookies[i].getName())) {

password = cookies[i].getValue();
if (username != null && password != null) {

response.sendRedirect("welcome.jsp?uname=" + username + "&password=" + password);
<form action="register.jsp" method="post">
<input type="submit" value=" register ">

2. The page is as follows :
 Insert picture description here

Verification Code (index.jsp)

( Click the verification code to update the verification code )

<script type="text/javascript">
function refresh() {

<%@ page contentType="charset=UTF-8" language="java"
import ="java.awt.*"
import ="java.awt.image.BufferedImage"
// Create images in memory 
int width=60,height=20;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// Get the brush 
Graphics g=image.getGraphics();
// Set background color 
g.setColor(new Color(200,200,200));
// Take randomly generated captcha (4 Digit number )
Random rnd=new Random();
int randNum=rnd.nextInt(8999)+1000;
String randStr=String.valueOf(randNum);
// Store the verification code in session
// Display the captcha in the image 
g.setFont(new Font("", Font.PLAIN,20));
// Randomly generated 100 A point of interruption , Make the captcha in the image difficult to detect by other programs 
for (int i = 0; i < 100; i++) {

int x=rnd.nextInt(width);
int y=rnd.nextInt(height);
// Output image to page 

 Insert picture description here

Login processing page (LoginCl.java(servlet))

Business logic processing page

package Register;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
public class LoginCl extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

// The solution to Chinese disorder 
// Prevent illegal login obtain session
HttpSession httpSession=request.getSession(true);
// modify session The existence time of is 20s
// Get the account number and password of the user name 
String u=null;
// in the light of jsp Its username by username1
String p=null;
// Get the submitted captcha 
String code = request.getParameter("code");
// obtain session Verification Code 
HttpSession session = request.getSession();
String randStr = (String) session.getAttribute("randStr");
// Only when the account information and verification code are entered correctly can you access 
try {

// start-up mysql Driver 
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
String sql="select * from usert where username=? and password=?";
PreparedStatement preparedStatement = con.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();

response.getWriter().println("<a href=LoginServlet.jsp> I'm sorry : Wrong account or password , Please check the information and re-enter </a>");
else {

// Get 
if(code.equals(randStr)) {

String keep = request.getParameter("keep");
// Check the no login option for two weeks 
if (keep != null) {

// establish cookie
Cookie cookie1 = new Cookie("username", u);
Cookie cookie2 = new Cookie("password", p);
// Set the associated path 
// Set up cookie The death time of Two weeks 
cookie1.setMaxAge(2 * 7 * 24 * 60 * 60);
cookie1.setMaxAge(2 * 7 * 24 * 60 * 60);
// hold cookie Information to the browser 
// Jump to the welcome screen 
response.sendRedirect("welcome.jsp?uname=" + u + " &password=" + p);
} catch (ClassNotFoundException e) {

} catch (SQLException e) {

public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{


If the user does not currently exist , Will output account password error and other information , If the user exists, it will jump to the welcome interface .

The welcome screen (welcome.jsp)

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" import="bean.*"
HttpSession httpSession=request.getSession(true);
String val=(String)httpSession.getAttribute("pass");
// If you open this page, you will jump to the login page , Prevent illegal login 

<jsp:useBean id="mycount" class="bean.Counter" scope="application"/>
<jsp:useBean id="user" class="bean.User" scope="session">
<jsp:setProperty name="user" property="name" param="uname"/>
<jsp:setProperty name="user" property="pd" param="password"/>
<h1> main interface </h1>
<%--welcome name =<%=u%> password =<%=p%><br>--%>
welcome name :<jsp:getProperty name="user" property="name" />
password:<jsp:getProperty name="user" property="pd" /><br>
<%-- This is your first :<%=counter%> Visit this website !<br>--%>
This is your first :<jsp:getProperty name="mycount" property="count"/>
Visit this website !<br>
<a href='LoginServlet.jsp'> Return to login again </a><br>
Cookie[] cookies = request.getCookies();
if(cookies!=null) {

for (int i = 0; i < cookies.length; i++) {

if (cookies[i].getName().equals("lastAccessTime")) {

out.println(" The time of your last visit was :");
Long lastAccessTime = Long.parseLong(cookies[i].getValue());
Date date = new Date(lastAccessTime);
// After the user visits, reset the user's access time , Stored in cookie in , And then send it to the client browser 
Cookie cookie=new Cookie("lastAccessTime",System.currentTimeMillis()+"");
// Set up cookie Valid for 1min
// take cookie Object added to response In the object , So the server is outputting response The content in the object is 
// It will cookie Also input to the client browser 

Implementation of registration page

Information registration (register.jsp)

Created by IntelliJ IDEA.
User: Lenovo
Date: 2020/10/20
Time: 9:44
To change this template use File | Settings | File Templates.
<%@ page language="java" pageEncoding="gb2312" %>
<h1> You are welcome to register </h1>
<script language="JavaScript" type="text/javascript">
function checkPassword() {

if (register.password1.value.length < 6 || register.password1.value.length > 20) {

alert(" Please note that the password length should not exceed 20 At the same time, it is not less than 6 position ");
else {

values = register.password1.value;
var flag = false;
for (var i = 0; i < values.length; i++) {

if ((values.charAt(i) >= 'A' && values.charAt(i) <= 'Z') || (values.charAt(i) >= 'a' && values.charAt(i) <= 'z')) {

if ((values.charAt(i) >= 'A' && values.charAt(i) <= 'Z')) {

for (var k = 0; k < values.length; k++) {

if ((values.charAt(k) >= 'a' && values.charAt(k) <= 'z')) {

flag = true;
else {

for (var k = 0; k < values.length; k++) {

if ((values.charAt(k) >= 'A' && values.charAt(k) <= 'Z')) {

flag = true;
if (flag == false) {

alert(" The password must contain both upper and lower case letters ");
var flag1=false;
for (var k = 0; k < values.length; k++) {



alert(" The password must contain numbers ");
<form name="register" action="registerMessage.jsp" method="post">
Please enter your account number :<input type="text" name="name"><br>
Please input a password ( requirement : Must contain uppercase and lowercase, English and numbers, no illegal characters , Longer than 6 Bit less than 20 position ):<input type="password" name="password1"><br>
Please choose gender :<input name="sex" type="radio" value=" male " checked> male
<input name="sex" type="radio" value=" Woman " > Woman <br>
Please choose your hometown :<select name="home" >
<option value=" Beijing "> Beijing </option>
<option value=" Shanghai "> Shanghai </option>
<option value=" shaanxi "> shaanxi </option>
Please choose your hobby :<input name="fav" type="checkbox" value=" Sing a song "> Sing a song
<input name="fav" type="checkbox" value=" dance "> dance
<input name="fav" type="checkbox" value=" Play a ball "> Play a ball
<input name="fav" type="checkbox" value=" Play a game "> Play a game <br>
<input type="button" value=" register " onclick="checkPassword()">

 Insert picture description here
Click to register and you will jump to the successful registration page , Store the account and password in the database , You can log in directly after .

Registration success page (registerMessage.jsp)

<%@ page language="java" pageEncoding="gb2312" %>
<h2> Information registration successful ! The registration information of the user is as follows :</h2>
String name=request.getParameter("name");
String password=request.getParameter("password1");
String sex = request.getParameter("sex");
String home = request.getParameter("home");
out.println(" account number :"+name);
out.println(" password :"+password);
out.println(" Gender :"+sex);
out.println(" hometown :"+home);
out.println(" Hobby :");
String[] fav = request.getParameterValues("fav");
for (int i = 0; i < fav.length; i++) {

out.print(fav[i]+" ");
try {

Connection con= null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
PreparedStatement preparedStatement = con.prepareStatement("insert into usert values(?,?)");
out.println("<a href=LoginServlet.jsp> Information registration successful , Click here to login </a>");
} catch (SQLException e) {

catch (ClassNotFoundException e) {


 Insert picture description here
( As shown below , Data added successfully )
 Insert picture description here

Function demonstration

This is the end of the project , I'll show you the login scene .
1. Database data
 Insert picture description here
2. Enter information that is not in the database
 Insert picture description here
 Insert picture description here
3. Correct account password
 Insert picture description here
ps: You need to pay attention to fill in the account or password or verification code , Otherwise, an error window will pop up .
 Insert picture description here
 Insert picture description here
 Insert picture description here


This project needs more knowledge points , These include jsp,servlet,mysql,cookie, Javabean etc. . What needs to be learned is web Knowledge is connected . You are welcome to ask questions about the code you don't understand .

本文为[Osu rebyzmjz]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云