JavaWeb - user login to achieve V2 and step on the pit point

1 implementation code

Implementation requirements:
Previously, we implemented the user login function. At that time, we asked the user to log in successfully and jump to
success.html page. Now you need to iterate the requirements. After the user logs in successfully, you are required to jump to
success.jsp page, which displays the user name after successful login. The format is: welcome, XXX
sign out. When the user clicks the exit button, clear session and jump back to the login page.

1.1 ideas

  • First, login HTML doesn't need to be greatly changed. Just modify the submission address (action) of the form to "login_result.jsp" (note that there is no /) in the first place of the action).
  • In login_result.jsp, and the corresponding tags are displayed according to the verification results. If the login is successful, an "exit" button will be displayed and jump to another jsp to perform the functions of session invalidation and jump back to the login interface.
  • In invalidate_session.jsp: invalidate the session and jump back to the login interface.

1.2 login.html

Unlike V1, the submitted address is changed from servlet to jsp.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign in</title>
    <script src="js/jquery-1.11.1.js"></script>
    <script src="js/bootstrap.js"></script>
    <link rel="stylesheet" href="css/bootstrap.css" />
    <link rel="stylesheet" href="css/bootstrap-theme.css" />

    <script>
        $(function(){
            $("#myForm").submit(function(){
                var flag = validateUserName() && validatePassword();
                if(!flag){
                    alert("There are fields not completed!");
                    return false;
                }else {
                    return true;
                }
            });
            $("#userName").keyup(function(){
                validateUserName();
            });
            $("#userPass").keyup(function(){
                validatePassword();
            });
        });

        function validateNull(value) {
            return !(value == null || value === "");
        }

        //User name verification rule: it must be more than 6 digits. Only numbers, uppercase letters, lowercase letters and underscores are allowed. It cannot start with an underscore
        function validateUserName() {
            var userName = $("#userName").val();
            var regex = /[A-Za-z0-9]\w+/;
            var msg = $("#userNameMsg");
            if(regex.test(userName)) {
                msg.css("color", "green");
                msg.html("The user name is legal");
                return true;
            } else {
                if(!validateNull(userName)) {
                    msg.html("The input is not empty!");
                } else if(userName.match(/_\w*/)) {
                    msg.html("The first character cannot be an underscore!");
                } else if(userName.length < 2) {
                    msg.html("User name must be at least 2 characters");
                } else {
                    msg.html("Contains illegal characters! Only numbers, letters, underscores are allowed");
                }
                msg.css("color", "red");
                return false;
            }
        }

        //Password verification rules: must be more than 6 digits, including numbers, uppercase letters and lowercase letters
        function validatePassword() {
            var password = $("#userPass").val();
            var regex1 = /[0-9]+[a-z]+[A-Z]+/;
            var regex2 = /[a-z]+[0-9]+[A-Z]+/;
            var regex3 = /[0-9]+[A-Z]+[a-z]+/;
            var regex4 = /[a-z]+[A-Z]+[0-9]+/;
            var regex5 = /[A-Z]+[0-9]+[a-z]+/;
            var regex6 = /[A-Z]+[a-z]+[0-9]+/;

            var msg = $("#passwordMsg");
            if(password.length < 6) {
                msg.html("The length is less than 6 digits!");
                msg.css("color", "red");
                return false;
            }
            if(regex1.test(password) || regex2.test(password) || regex3.test(password) || regex4.test(password) || regex5.test(password) || regex6.test(password)) {
                msg.html("The password is valid");
                msg.css("color", "green");
                return true;
            } else {
                if(!validateNull(password)) {
                    msg.html("The input is empty!");
                } else {
                    msg.html("The password is invalid. It must contain numbers, uppercase and lowercase letters!");
                }
                msg.css("color", "red");
                return false;
            }
        }
    </script>
</head>
<body>
    <div class="container">
        <h2 class="text-center">User login</h2>
        <form id="myForm" role="form" class="form-horizontal" action="login_result.jsp" method="post">
            <div class="form-group">
                <label class="control-label col-sm-1" for="userName">user name:</label>
                <div class="col-sm-5">
                    <input class="form-control" type="text" name="name" id="userName"/>
                </div>
                <div class="col-sm-6">
                    <label id="userNameMsg" class="control-label text-info">Only numbers, uppercase and lowercase letters and underscores are allowed. The first character cannot be an underscore</label>
                </div>

            </div>
            <div class="form-group">
                <label class="control-label col-sm-1" for="userPass">password:</label>
                <div class="col-sm-5">
                    <input type="password" class="form-control" name="pass" id="userPass"/>
                </div>
                <div class="col-sm-6">
                    <label id="passwordMsg" class="control-label text-info text-left">The password must contain at least 6 characters, including upper and lower case letters and numbers</label>
                </div>

            </div>
            <div class="form-group text-center">
                <button type="submit" class="btn btn-info col-sm-3 col-sm-offset-3">Sign in</button>

                <button type="reset" class="btn btn-normal col-sm-3">Reset</button>
            </div>
        </form>
    </div>
</body>
</html>

1.3 login_result.jsp

After the login interface is submitted, you will jump to this page. EL expressions and JSTL tag libraries are used here. The tag library uses the core library c and database sql.

<%@ page import="com.kkb.xzk.validation.DatabaseValidation" %>
<%@ page import="java.sql.SQLException" %><%--
  Created by IntelliJ IDEA.
  User: handi
  Date: 2021/7/23
  Time: 11:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>

<html>
<head>
    <title>Login results</title>
  <script src="js/jquery-1.11.1.js"></script>
  <script src="js/bootstrap.js"></script>
  <link rel="stylesheet" href="css/bootstrap.css" />
  <link rel="stylesheet" href="css/bootstrap-theme.css" />
</head>
<body>
<sql:setDataSource var="userDatabase" driver="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/mydb6?serverTimeZone=UTC" user="root" password="123456"></sql:setDataSource>
<sql:query var="result" dataSource="${userDatabase}" sql="select userpass from user where username=?">
  <sql:param value="${param.name}"></sql:param>
</sql:query>

<c:choose>
  <c:when test="${!(empty result)}">
    <c:forEach var="row" items="${result.rows}">
      <c:if test="${row.userpass == param.pass}">
        <h1>Welcome! ${param.name}</h1>
        <form action="invalidate_session.jsp" method="post">
          <button type="submit" class="btn btn-default">sign out</button>
        </form>
      </c:if>
    </c:forEach>
  </c:when>
  <c:otherwise>
    <h1>Login failed!</h1>"
  </c:otherwise>
</c:choose>
</body>
</html>

1.4 invalidate_session.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%session.invalidate();%>
<%response.sendRedirect("login.html");%>
</body>
</html>

2 points for attention

2.1 session invalidation cannot be performed through jsp in javascript tags

The following is wrong.

<script>
      $(function(){
        $("#exit").click(function(){
          <%session.invalidate();%>
        });
      });
    </script>

This will cause the session to fail directly instead of clicking the button. Because <% session invalidate();%> This sentence is an execution operation, which is equivalent to the direct execution of the browser resolution here.

The correct approach is to wrap the button with the form, click the button and jump to a separate jsp for session invalidation.

2.2 form data reception

It must be noted that the parameter in the braces of the EL expression must be XXX Parameter name set by setattribute(). After the form data is submitted, it is actually saved in the parameters of the request. It is extracted from the ordinary JSP code as follows:

user name:<%=request.getParameter("userName") %>

When using EL expression, the correct operation is to use the hidden object param to obtain.

user name: ${param.userName}

2.3 using JSTL to operate database

Correct practice:

<sql:setDataSource var="userDatabase" driver="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/mydb6?serverTimeZone=UTC" user="root" password="123456"></sql:setDataSource>
<sql:query var="result" dataSource="${userDatabase}" sql="select userpass from user where username=?">
  <sql:param value="${param.name}"></sql:param>
</sql:query>

It should be noted that sql statements cannot be set by splicing, such as:
< SQL: query var = "result" datasource = "${UserDatabase}" SQL = "select userpass from user where username = ${param. Name}" >, which cannot be retrieved.

You should use the sql statement of the pre status channel,? The setting of is implemented through the sql:param tag.

Keywords: Java JSP

Added by gwood_25 on Sat, 15 Jan 2022 12:24:00 +0200