编程知识 cdmana.com

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

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 :


 <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

Implement login page

Create database

 CREATE TABLE `usert` (
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk

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" %>
<html>
<head>
    <title>LoginServlet</title>
</head>
<body>
<script type="text/javascript">
<%-- Judge the input account information , The account password cannot be empty and the verification code must be entered --%>
    function validate() {
   
   
        if(login.username1.value===""){
   
   
            alert(" Account number cannot be empty ");
            return;
        }
        if(login.passwd.value===""){
   
   
            alert(" The password cannot be empty ");
            return;
        }
        if(login.code.value===""){
   
   
            alert(" Please enter the verification code ");
            return;
        }
        login.submit();
    }
    function refresh() {
   
   
        login.imgValidate.src="index.jsp?id="+Math.random();
    }
</script>
<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>
  <form action="register.jsp" method="post">
    <input  type="submit" value=" register ">
</form>
</body>
</html>

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() {
   
   
     src="index.jsp?id="+Math.random();
    }
</script>
<%@ page contentType="charset=UTF-8" language="java"
        import ="java.awt.*"
         import ="java.awt.image.BufferedImage"
          import="java.util.*"
         import="javax.imageio.ImageIO"
         pageEncoding="gb2312"%>
<%
response.setHeader("Cache-Control","no-cache");
// 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));
  g.fillRect(0,0,width,height);
  // 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
  session.setAttribute("randStr",randStr);
  // Display the captcha in the image 
  g.setColor(Color.black);
  g.setFont(new Font("", Font.PLAIN,20));
  g.drawString(randStr,10,17);
  // 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);
        g.drawOval(x,y,1,1);
    }
    // Output image to page 
    ImageIO.write(image,"JPEG",response.getOutputStream());
    out.clear();
    out=pageContext.pushBody();

%>

 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.*;

@WebServlet("/LoginCl")
public  class LoginCl extends HttpServlet {
   
   
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
   
   
        // The solution to Chinese disorder 
        response.setContentType("text/html;charset=gb2312");
// Prevent illegal login      obtain session
        HttpSession httpSession=request.getSession(true);
        // modify session The existence time of is 20s
        httpSession.setMaxInactiveInterval(20);
        httpSession.setAttribute("pass","ok");
        // Get the account number and password of the user name 
        String u=null;
        // in the light of jsp  Its username by username1
        u=request.getParameter("username1");
        String p=null;
        p=request.getParameter("passwd");
        // Get the submitted captcha 
        String code = request.getParameter("code");
        // obtain session Verification Code 
        HttpSession session = request.getSession();
        String randStr = (String) session.getAttribute("randStr");
        response.setCharacterEncoding("gb2312");
      // Only when the account information and verification code are entered correctly can you access 
        try {
   
   
            // start-up mysql Driver 
            Class.forName("com.mysql.jdbc.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);
            preparedStatement.setString(1,u);
            preparedStatement.setString(2,p);
            ResultSet rs = preparedStatement.executeQuery();
            if(!rs.next()){
   
   
               response.getWriter().println("<a href=LoginServlet.jsp> I'm sorry : Wrong account or password , Please check the information and re-enter </a>");
                return;
            }
            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 
                        cookie1.setPath(request.getContextPath());
                        cookie2.setPath(request.getContextPath());
                        // 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 
                        response.addCookie(cookie1);
                        response.addCookie(cookie2);
                    }
                    // Jump to the welcome screen 
                    response.sendRedirect("welcome.jsp?uname=" + u + " &password=" + p);
                }
                rs.close();
                preparedStatement.close();
             }
        } catch (ClassNotFoundException e) {
   
   
            e.printStackTrace();
        } catch (SQLException e) {
   
   
            e.printStackTrace();
        }
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
   
   
        this.doGet(request,response);
    }
}

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.*"
%>
<html>
<head>
    <title>welcome</title>
</head>
<body>
<%
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
 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 
    if(val==null){
   
   
        response.sendRedirect("LoginServlet.jsp");
    }  
%>
<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"/>
</jsp:useBean>
<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);
                out.println(date.toLocaleString());
            }
        }
    }
    // 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
    cookie.setMaxAge(60);
    // 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 
    response.addCookie(cookie);
%>
</body>
</html>

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" %>
<html>
<head>
    <title>register</title>
</head>
<body>
    <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 ");
                return;
            }

            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;
                                    break;
                                }
                            }
                        }
                        else {
   
   
                            for (var k = 0; k < values.length; k++) {
   
   
                                if ((values.charAt(k) >= 'A' && values.charAt(k) <= 'Z')) {
   
   
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                    }
                    if (flag == false) {
   
   
                        alert(" The password must contain both upper and lower case letters ");
                        return;
                    }
                var flag1=false;
                for (var k = 0; k < values.length; k++) {
   
   
                    if((values.charAt(k)>='0'&&values.charAt(k)<='9')){
   
   
                        flag1=true;
                    }
                }
                if(flag1==false){
   
   
                    alert(" The password must contain numbers ");
                    return;
                }
            }
            register.submit();
        }
    </script>
<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>
     </select>
    <br>
     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()">
</form>
</body>
</html>

 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" %>
<html>
<head>
    <title>message</title>
</head>
<body>
<h2> Information registration successful ! The registration information of the user is as follows :</h2>
<%
    request.setCharacterEncoding("gb2312");
    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 {
   
   
        Class.forName("com.mysql.jdbc.Driver");
    Connection con= null;
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
        PreparedStatement preparedStatement = con.prepareStatement("insert into usert values(?,?)");
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,password);
        preparedStatement.executeUpdate();

        out.println("<a href=LoginServlet.jsp> Information registration successful , Click here to login </a>");
    } catch (SQLException e) {
   
   
        e.printStackTrace();
    }
    catch (ClassNotFoundException e) {
   
   
        e.printStackTrace();
    }
%>
</body>
</html>

 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 .
eg:
 Insert picture description here
 Insert picture description here
 Insert picture description here











summary

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]所创,转载请带上原文链接,感谢

Scroll to Top