Book City Project — Stage 1

Exercise task: Use vue.js to implement the following functions:

  1. Display table;
  2. Display four text boxes;
  3. Create a P tag to display what the user is typing in real time in the text box;
  4. Click the Add record button to add records.

Code sample

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test a vue.js</title>
</head>
<body>
<div id="app" style="text-align: center">
    <table style="text-align: center" border="1" cellspacing="0" width="500px">
        <thead>
            <th>Serial number</th>
            <th>The name</th>
            <th>age</th>
            <th>professional</th>
            <th>operation</th>
        </thead>
        <tbody>
            <tr v-for="(user,index) in userList">
                <td>{{user.id}}</td>
                <td>{{user.name}}</td>
                <td>{{user.age}}</td>
                <td>{{user.major}}</td>
                <td><button @click="deleteUser(index)">delete</button></td>
            </tr>
        </tbody>
    </table>
    <form method="post" action="www.baidu.com">No. :<input type="text" v-model="user.id" name="id"><br>Name:<input type="text" v-model="user.name" name="name"><br>Age:<input type="text" v-model="user.age" name="age"><br>Professional:<input type="text" v-model="user.major" name="major"><br>
        <input type="button" @click="addUser" value="Add data">
    </form>
</div>
</body>
<script type="text/javascript" src=".. /js/vue.min.js"></script>
<script type="text/javascript">
    var vue = new Vue({
        el:"#app".data: {user: [].userList:[
                {
                    "id":1."name":"Zhang"."age":18."major":"Java"
                },
                {
                    "id":2."name":"Bill"."age":19."major":"php"
                },
                {
                    "id":3."name":"Fifty"."age":17."major":"object-c"
                },
                {
                    "id":3."name":"Fifty"."age":17."major":"object-c"
                },
                {
                    "id":3."name":"Fifty"."age":17."major":"object-c"}],},methods: {addUser: function(){
                event.preventDefault();
                this.userList.push(this.user);
                this.user = [];
            },
            deleteUser(i){
                this.userList.splice(i,1); }}});</script>
</html>
Copy the code

Bug record

Do not name a function with delete, as delete will invalidate the function.

Hands-on tasks:

  1. Implement login form verification
  2. Registration form verification
<body>
<div id="app">
    <div id="login_header">
        <a href=".. /.. /index.html">
            <img class="logo_img" alt="" src=".. /.. /static/img/logo.gif"/>
        </a>
    </div>

    <div class="login_banner">
        <div id="l_content">
            <span class="login_word"</span> </div> <div id="content">
            <div class="login_form">
                <div class="login_box">
                    <div class="tit"> <h1> Still silicon Valley member </ H1 > </div> <divclass="msg_cont">
                        <b></b>
                        <span class="errorMsg" style="color: red">{{errorMsg}}</span>
                    </div>
                    <div class="form">
                        <form action="login_success.html"<label> User name: </label> <input V-model ="username"
                                    class="itxt"
                                    type="text"
                                    placeholder="Please enter user name"
                                    autocomplete="off"
                                    tabindex="1"
                                    name="username"
                                    id="username"/ > < br / > < br / > < label > user password: < / label > < input v - model ="password"
                                    class="itxt"
                                    type="password"
                                    placeholder="Please enter your password"
                                    autocomplete="off"
                                    tabindex="1"
                                    name="password"
                                    id="password"

                            />
                            <br/>
                            <br/>
                            <input type="submit" value="Login" id="sub_btn" @click="login"/>
                        </form>
                        <div class="tit">
                            <a href="regist.html"> register < / a > < / div > < / div > < / div > < / div > < / div > < / div > < div id ="bottom"Word-wrap: break-word! Important; "> <span style =" max-width: 100%; Copyright &copy;2015
      </span>
    </div>
</div>

</body>
<script type="text/javascript" src=".. /.. /static/script/vue.min.js"></script>
<script type="text/javascript">
    let vue = new Vue({
        el: "#app",
        data: {
            "username": ""."password": ""."errorMsg": ""

        },
        methods: {
            login() {
                if (this.username ! ="") {
                    if (this.password == "") {
                        event.preventDefault();
                        this.errorMsg = "Password cannot be empty.";
                    }else{
                      this.errorMsg = ""; }}else {
                    event.preventDefault();
                    this.errorMsg = "User name cannot be empty"; }}}}); </script>Copy the code

Description:

  1. To use Vue, import vue.js into this file first. [Can not be used without import]
  2. Create a Vue object in JS. [Create entity, bearing EL,data,methods]
  3. Set the mount point. 【 Mistake will fail 】
  4. To determine whether the binding is two-way or one-way, use HTML to match one of the data items with the corresponding data names. 【 Mistake will fail 】
  5. Bind the event driver to the corresponding HTML control, write the corresponding method in methods, and note that the event name should correspond to. 【 Mistake will fail 】

Book City Project — Stage 2

1. Review the JDBC

Java DataBase Connectivity [Java DataBase Connectivity]

Commonly used API

  • DriverManager: DriverManager
  • Connection: indicates the Connection object
  • Statement [PreparedStatement] : operate on a database [execute SQL statements] object
  • ResultSet: processes ResultSet objects

2. Use JDBC and related knowledge

The preparatory work

  • One configuration file: druid.properties
  • Two utility classes
    • BaseDao
    • JdbcUtils
  • Three jars
    • Commons dbutils – 1.6. The jar
    • Druid – 1.1.10. Jar
    • Mysql connector – Java – 5.1.37 – bin. The jar

Matters needing attention

  • To import jar packages for web applications, create a lib package in web-INF and import the required JAR packages in the lib package

JDBC exercise requirements and steps

  • Requirement: Implement student CRUD
  • Create the student table
  • Create Student class
  • Create StudentDao and StudentDaoImpl implementation classes

3. JavaBean

Javabeans: Transfer data between different layers

  • Data beans: The corresponding table structure, data beans, exists in the database
  • Business beans: No corresponding table structure, business beans exist in the database

4. Use the wrapper class advantage in beans

  • Wrapper classes facilitate type conversions
  • The wrapper class facilitates null value judgment
    • For example, int Default value: 0 Integer Default value: null

5. Advantages of interface oriented programming

advantage

  • Improve program extensibility

  • Reduce program maintenance costs

The interface definition

  • Return value: Add, delete, or modify is set to void
  • Parameters: Parameters correspond to placeholders in SQL

6. Three-layer R&D

Why stratification

  • High cohesion, low coupling
  • Reduce program maintenance costs
  • Improving r&d efficiency

Three layers

  • Customer -> Waiter, cook, buyer
  • Presentation layer Business logic layer Data access layer
  • html &servlet service dao

7. The base tag

Why use the base tag for the same page access path

Because in the page there is a lot of a label, the form and the Ajax request requires write access path, the project path in the access path is the same, so if it is not unified writing project path, occurs when the project path to change the page all use project path where need to change the situation.

Syntax rules for the base tag

  • The base tag should be inside the head tag
  • The base tag must precede all other tags that have paths
  • The base tag uses the href attribute to set the base of the path
  • The base tag takes effect as follows: The final access address =base of the base tag href attribute + the path within the specific tag
  • If a path wants to write paths based on the paths in base, it cannot write paths with/At the beginning

Code sample

The original page

 <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>(the home page</title>
    <link rel="stylesheet" href="./static/css/minireset.css" />
    <link rel="stylesheet" href="./static/css/common.css" />
    <link rel="stylesheet" href="./static/css/iconfont.css" />
    <link rel="stylesheet" href="./static/css/index.css" />
    <link rel="stylesheet" href="./static/css/swiper.min.css" />
  </head>
Copy the code

The page after using Base

<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0"/>
    <title>(the home page</title>
    <base href="/bookstore/"/>
    <link rel="stylesheet" href="static/css/minireset.css"/>
    <link rel="stylesheet" href="static/css/common.css"/>
    <link rel="stylesheet" href="static/css/iconfont.css"/>
    <link rel="stylesheet" href="static/css/index.css"/>
    <link rel="stylesheet" href="static/css/swiper.min.css"/>
</head>
Copy the code

Pay attention to

The base label

<base href="/bookstore/"/>/ / project nameCopy the code

replace

8.To fit the task

Implementation steps

  1. Create a dynamic Web project
  2. Copy the static resources from the first edition of Book City into the Web folder
  3. The basic access path for a unified page
  4. Use static data for login verification
  5. Verify that the user name exists when the registration is complete

Code sample

1. Static data login verification

Static data: [Username: zhangsan, password: 123456]

servlet

package com.dyy.servlet;

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;

@WebServlet(name = "LoginServlet",urlPatterns = "/static_check_login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if("zhangsan".equals(username)&&"123456".equals(password)){
            response.sendRedirect(request.getContextPath()+"/pages/user/login_success.html");
        }else{
            response.getWriter().write("Wrong username or password, please try again.");
            Response.sendredirect (request.getContextPath()+"/pages/user/login.html"); * * /}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}Copy the code

The form

<form action="static_check_login" method="post">
              <label>User Name:</label>
              <input
                      v-model="username"
                      class="itxt"
                      type="text"
                      placeholder="Please enter user name"
                      autocomplete="off"
                      tabindex="1"
                      name="username"
                      id="username"

              />
              <br/>
              <br/>
              <label>User password:</label>
              <input
                      v-model="password"
                      class="itxt"
                      type="password"
                      placeholder="Please enter your password"
                      autocomplete="off"
                      tabindex="1"
                      name="password"
                      id="password"

              />
              <br/>
              <br/>
              <input type="submit" value="Login" id="sub_btn" @click="login"/>
            </form>
Copy the code
2. Check whether the user name exists

Static data: [User name: zhangsan]

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Silicon Valley member registration page</title>
    <base href="/pro03/">
    <link type="text/css" rel="stylesheet" href="static/css/style.css"/>
    <link rel="stylesheet" href="static/css/register.css"/>
    <style type="text/css">.login_form { height: 420px; margin-top: 25px; } / *<! ErrorMess control in this class style sheet is hidden by default. Here a custom style override is used to make it visible, but it is not visible until the form is submitted, so you can use the binding style sheet to control whether it works or fails.*/
        .login_banner .register_form form .form-item .vv{
          visibility: visible;
        }
    </style>
</head>
<body>
<div id="app">
    <div id="login_header">
        <a href="index.html">
            <img class="logo_img" alt="" src="static/img/logo.gif"/>
        </a>
    </div>

    <div class="login_banner">
        <div class="register_form">
            <h1>Sign up for silicon Valley membership</h1>
            <form action="static_check_register" method="post">
                <div class="form-item">
                    <div>
                        <label>User Name:</label>
                        <input  name="username" v-model="username" type="text" placeholder="Please enter user name"/>
                    </div>

                    <span class="errMess" :class="{vv:isUnVv}">User name: contains 6 to 12 letters, digits, and underscores (_).</span>
                </div>
                <div class="form-item">
                    <div>
                        <label>User password:</label>
                        <input name="password" v-model="password" type="password" placeholder="Please enter your password"/>
                    </div>
                    <span class="errMess" :class="{vv:isPwdVv}">Password: contains only six characters, including letters and digits.</span>
                </div>
                <div class="form-item">
                    <div>
                        <label>Confirm password:</label>
                        <input name="re_password" v-model="re_password" type="password" placeholder="Please enter your password confirmation."/>
                    </div>
                    <span class="errMess" :class="{vv:isRePwdVv}">The password entered twice is inconsistent</span>
                </div>
                <div class="form-item">
                    <div>
                        <label>Email address:</label>
                        <input name="email" v-model="email" type="text" placeholder="Please enter email address"/>
                    </div>
                    <span class="errMess" :class="{vv:isEmailVv}">Please enter the correct email format</span>
                </div>
                <div class="form-item">
                    <div>
                        <label>Verification code:</label>
                        <div class="verify">
                            <input name="code" type="text" v-model="code" placeholder=""/>
                            <img src="static/img/code.bmp" alt=""/>
                        </div>
                    </div>
                    <span class="errMess" :class="{vv:isCodeVv}">Enter the correct verification code</span>
                </div>
                <button type="submit" class="btn" @click="checkRegist">registered</button>
            </form>
        </div>
    </div>
    <div id="bottom">
      <span>Silicon Valley Book City.Copyright&copy;2015
      </span>
    </div>
</div>
</body>

<script type="text/javascript" src="static/script/vue.min.js"></script>
<script type="text/javascript">
    let vue = new Vue({
        el: "#app".data: {
            username: "".password: "".re_password: "".email: "".code:"".// Dynamically bind stylesheets
            "isUnVv": false.// The user name is valid
            "isPwdVv": false.// Displays the password validity
            "isRePwdVv": false."isEmailVv": false."isCodeVv": false
        },
        methods: {
            checkUserName() {
              this.isUnVv=false;
                let reg = / ^ / a - zA - Z0-9 _ $/ 6, 12 {};
                if(! reg.test(this.username)) {
                    event.preventDefault();
                    this.isUnVv = "true"; }},checkPassword() {
                // Restore default hiding
                this.isPwdVv = false;
                // The password can contain only six characters, including letters and digits.
                var pwdReg = /^[a-zA-Z0-9]{6}$/;
                if(! pwdReg.test(this.password)) {
                    // Prompt the user [display the prompt area]
                    this.isPwdVv = true;
                    // Cancels the default behavior of the controlevent.preventDefault(); }},checkRePassword() {
                this.isRePwdVv = false;
                if (this.password ! =this.re_password) {
                    // The user is prompted that the two passwords are inconsistent
                    this.isRePwdVv = true;
                    // Cancels the default behavior of the controlevent.preventDefault(); }},checkEmail() {
                this.isEmailVv = false;
                [c] mailbox: standard authentication in API.
                var regEmail = [a - / ^ (z0-9 _ \. -] +) @ (/ \ \. Da - z - +) \. ([a-z \.] {2, 6}) $/;
                if(! regEmail.test(this.email)) {
                    // The user is prompted that the input valid format is incorrect
                    this.isEmailVv = true;
                    // Cancels the default behavior of the controlevent.preventDefault(); }},// The verification code is not null
            checkCode() {
                this.isCodeVv = false;
                if (this.code == "") {
                    // Prompts the user that the verification code cannot be empty
                    this.isCodeVv = true;
                    // Cancels the default behavior of the controlevent.preventDefault(); }},checkRegist(){
                this.checkUserName();
                this.checkPassword();
                this.checkRePassword();
                this.checkEmail();
                this.checkCode(); }}});</script>
</html>

Copy the code
package com.dyy.servlet;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.util.Map;import java.util.Set;
/* Static verification registration */
@WebServlet(name = "RegistServlet",urlPatterns = "/static_check_register")
public class RegistServlet extends HttpServlet {   
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");        

response.setContentType("text/html; charset=UTF-8");        
String username = request.getParameter("username");        /* system.out. println(" try to output parameters: "); Map
      
        parameterMap = request.getParameterMap(); Set
       
         p = parameterMap.keySet(); for (String s : p) { String[] strings = parameterMap.get(s); System.out.print(s+":"); for (String string : strings) { System.out.print(string+","); } System.out.println(); } * /
       
      ,>       
if("zhangsan".equals(username)){           
response.getWriter().write("Duplicate user name, please try again.");        
}else{            response.sendRedirect(request.getContextPath()+"/pages/user/regist_success.html");        
}        
System.out.println("End of use of registration function");
}    
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}Copy the code
3. Database connection pool
  1. Import driUD-related JAR packages
  2. Write the properties files
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/bookstore? useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true username=root password=123456 initialSize=10 minIdle=5 maxActive=20 maxWait=5000Copy the code
  1. Write a utility class to get a Connection
package com.dyy.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
    private static DataSource dataSource;
    static {
        try {
            InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties p = new Properties();
            p.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch(Exception e) { e.printStackTrace(); }}/** * get the connection */

    public static Connection getConnection(a)  {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /** * Release resources *@param conn
     * @param stat
     * @param rs
     */
    public static void release(Connection conn, Statement stat, ResultSet rs){
        if(rs! =null) {try {
                rs.close();
            } catch(SQLException e) { e.printStackTrace(); }}if(stat! =null) {try {
                stat.close();
            } catch(SQLException e) { e.printStackTrace(); }}if(conn! =null) {try {
                conn.close();
            } catch(SQLException e) { e.printStackTrace(); }}}}Copy the code
4.Dao
  1. Create poJO classes to receive data returned by the query database
package com.dyy.pojo;

public class User {
    private int id;
    private String username;
    private String password;
    private String email;

    public User(a) {}public User(int id, String username, String password, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail(a) {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\' ' +
                ", password='" + password + '\' ' +
                ", email='" + email + '\' ' +
                '} '; }}Copy the code
  1. Write the BaseDao superclass.
package com.dyy.dao;
import com.dyy.util.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BaseDao<T>{

    private QueryRunner queryRunner = new QueryRunner();
    // Define a variable to receive the type of the generic type
    private Class<T> type;
    // Get T's Class object, get the type of the generics that are inherited by subclasses
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public BaseDao(a) {
// Get the type of the subclass
        Class clazz = this.getClass();
        // Get the type of the parent class
        //getGenericSuperclass() is used to get the type of the parent of the current class
        //ParameterizedType represents a type with generics
        ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
        GetActualTypeArguments Gets the type of the specific generic type
        // This method returns an array of types
        Type[] types = parameterizedType.getActualTypeArguments();
        // Get the type of the specific generic
        this.type = (Class<T>) types[0];
    }
    /** * SQL: insert delete update *@param sql
     * @param params
     * @return* /
    public int update(String sql, Object... params) {
        Connection connection = JDBCUtil.getConnection();
        int count = 0;
        try {
            queryRunner.update(connection,sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.release(connection,null.null);
        }
        return count;
    }
    /** * get a single object *@param sql
     * @param params
     * @return* /
    public T getBean(String sql, Object... params) {
        Connection connection = JDBCUtil.getConnection();
        T t = null;
        try {
            t = queryRunner.query(connection, sql, new BeanHandler<T>(type),
                    params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection,null.null);
        }
        return t;
    }
    /** * get all objects *@param sql
     * @param params
     * @return* /
    public List<T> getBeanList(String sql, Object... params) {
        // Get the connection
        Connection connection = JDBCUtil.getConnection();
        List<T> list = null;
        try {
            list = queryRunner.query(connection, sql, new BeanListHandler<T>(
                    type), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection,null.null);
        }
        return list;
    }

    /** * a generic way to get a single value */
    public Object getSingleValue(String sql, Object... params) {
        // Get the connection
        Connection connection = JDBCUtil.getConnection();
        Object o = null;
        try {
            o = queryRunner.query(connection, sql, new ScalarHandler(), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection,null.null);
        }
        returno; }}Copy the code
  1. Create the UserDao interface
package com.dyy.dao;

import com.dyy.pojo.User;

import java.sql.SQLException;
import java.util.List;

public interface UserDao {
    public List<User> getAllUser(a) throws SQLException;
    /** * Query user information by user name *@param username
     * @return
     * @throws SQLException
     */
    public User selectUserByUserName(String username) throws SQLException;

    /** * Add user information */
    public void insertUser(User user) throws SQLException;

}
Copy the code
  1. Implement the UserDao with the UserDaoImpl class
package com.dyy.dao.impl;

import com.dyy.dao.BaseDao;
import com.dyy.dao.UserDao;
import com.dyy.pojo.User;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl extends BaseDao<User> implements UserDao {
    @Override
    public List<User> getAllUser(a) throws SQLException {
        String sql = "select * from users";
        return getBeanList(sql);
    }

    @Override
    public User selectUserByUserName(String username) throws SQLException {
        String sql = "select * from users where username=?";
        return getBean(sql,username);
    }

    @Override
    public void insertUser(User user) throws SQLException {
        String sql = "insert into users(username,`password`,email) values(? ,? ,?) "; update(sql,user.getUsername(),user.getPassword(),user.getEmail()); }}Copy the code
5. Use MD5 to encrypt the user password.
  1. Write an MD5 utility class MD5Util
package com.dyy.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    /** * Perform MD5 encryption for plaintext strings *@param source
     * @return* /
    public static String encode(String source) {
        /*1. First check whether the inscription string is valid */
        if(source == null || "".equals(source)){
            throw new RuntimeException("The plaintext to be encrypted cannot be empty.");
        }
        /*2. Declare the algorithm name */
        String algorithm = "MD5";
        /*3. Get MessageDigest object */
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        /*4. Get the byte array corresponding to the plaintext string */
        byte[] input = source.getBytes();
        /*5. Perform encryption */
        byte[] output = messageDigest.digest(input);
        Create the BigInteger object */
        int signum = 1;
        BigInteger bigInteger = new BigInteger(signum, output);
        /*7. Convert the value of bigInteger into a string */ in hexadecimal format
        int radix = 16;
        String encoded = bigInteger.toString(radix).toUpperCase();

        returnencoded; }}Copy the code
  1. Create the UserService interface
package com.dyy.service;

import com.dyy.pojo.User;

public interface UserService {
    void doRegister(User userForm);
}
Copy the code
  1. Create the UserServiceImpl implementation class
package com.dyy.service.impl;

import com.dyy.dao.UserDao;
import com.dyy.dao.impl.UserDaoImpl;
import com.dyy.pojo.User;
import com.dyy.service.UserService;
import com.dyy.util.MD5Util;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public void doRegister(User userForm) throws SQLException {
        /* Verify that the user name exists */ before registering
        User existuser = userDao.selectUserByUserName(userForm.getUsername());
        if(existuser! =null) {throw new RuntimeException("The user name already exists, registration failed");
        }
        /* Encrypt the user's password */
        String oldPassword = userForm.getPassword();
        /* Call MD5Util class to encrypt password */
        String encodePassword = MD5Util.encode(oldPassword);
        /* Reassign the encrypted password to the userForm object */
        userForm.setPassword(encodePassword);
        /* Call dao to add data to database, register successfully */userDao.insertUser(userForm); }}Copy the code
  1. Write a BeanUtil utility class that contains a populate method that encapsulates incoming data in an object.

    package com.dyy.util;
    import com.dyy.pojo.User;
    import java.util.Map;
    
    public class BeanUtil {
        /** * This class is used to process the data set passed in by the page into the User object *@param user
         * @param map
         */
        public static void populate(User user, Map<String,String[]> map){
            user.setUsername(map.get("username") [0]);
            user.setPassword(map.get("password") [0]);
            user.setEmail(map.get("email") [0]); }}Copy the code
  2. Modify the RegisterServlet written in phase 1 to handle registration

package com.dyy.servlet;

import com.dyy.pojo.User;
import com.dyy.service.UserService;
import com.dyy.service.impl.UserServiceImpl;
import com.dyy.util.BeanUtil;

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;
import java.util.Map;
import java.util.Set;

/* Static verification registration */
@WebServlet(name = "RegisterServlet",urlPatterns = "/check_register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        /* Use the utility class to process the data, putting the data into the user object */
        BeanUtil.populate(user,parameterMap);
        /* Use the doRegister in Userservice to perform the check user name */
        UserService userService = new UserServiceImpl();
        try {
            userService.doRegister(user);
            /* If no exception occurs, the registration success page is redirected */
            response.sendRedirect(request.getContextPath()+"pages/user/regist_success.html");
        } catch (SQLException e) {
            e.printStackTrace();
            /* Register failed */
            response.getWriter().write("Sorry, registration failed, please try again."); }}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}Copy the code
6. Login function
  1. The UserService interface adds the doLogin() abstract method

    package com.dyy.service;
    
    import com.dyy.pojo.User;
    
    import java.sql.SQLException;
    
    public interface UserService {
        /** * this method is used to verify the registration, check if the user name is duplicate, encrypt the password in the userForm, and insert the data into the user table *@param userForm
         * @throws SQLException
         */
        void doRegister(User userForm) throws SQLException;
    
        /** * This method is used to verify login and check whether the account password is correct *@param user
         * @return
         * @throws SQLException
         */
        User doLogin(User user) throws SQLException;
    }
    Copy the code
  2. The UserServiceImpl class implements the doLogin() method

    package com.dyy.service.impl;
    
    import com.dyy.dao.UserDao;
    import com.dyy.dao.impl.UserDaoImpl;
    import com.dyy.pojo.User;
    import com.dyy.service.UserService;
    import com.dyy.util.MD5Util;
    
    import java.sql.SQLException;
    
    public class UserServiceImpl implements UserService {
        private UserDao userDao = new UserDaoImpl();
    
        @Override
        public void doRegister(User userForm) throws SQLException {
            /* Verify that the user name exists */ before registering
            User existUser = userDao.selectUserByUserName(userForm.getUsername());
            if(existUser ! =null) {
                throw new RuntimeException("The user name already exists, registration failed");
            }
            /* Encrypt the user's password */
            String oldPassword = userForm.getPassword();
            /* Call MD5Util class to encrypt password */
            String encodePassword = MD5Util.encode(oldPassword);
            /* Reassign the encrypted password to the userForm object */
            userForm.setPassword(encodePassword);
            /* Call dao to add data to database, register successfully */
            userDao.insertUser(userForm);
    
        }
    
        * if there is any, the password will be encrypted and compared with the line of data. If the password is wrong, it will also return a failure. * If the account password is correct, then return all the information of the user. * *@param user
         * @returnReturn account information *@throws SQLException
         */
        @Override
        public User doLogin(User user) throws SQLException {
            User realUser = userDao.selectUserByUserName(user.getUsername());
            if (realUser == null) {
                throw new RuntimeException("Wrong account number");
            }
            String encodePassword = MD5Util.encode(user.getPassword());
            if(realUser.getPassword().equals(encodePassword)){
                return realUser;
            }else{
                throw new RuntimeException("Password error"); }}}Copy the code
  3. Modify the doPost() method in LoginServlet

    package com.dyy.servlet;
    
    import com.dyy.pojo.User;
    import com.dyy.service.UserService;
    import com.dyy.service.impl.UserServiceImpl;
    
    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;
    
    /* Static verification login */
    @WebServlet(name = "LoginServlet",urlPatterns = "/check_login")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
    
            String username = request.getParameter("username");
            String password = request.getParameter("password");
    
            UserService userService = new UserServiceImpl();
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
    
            try {
                userService.doLogin(user);
                response.sendRedirect(request.getContextPath()+"/pages/user/login_success.html");
            } catch (SQLException e) {
                e.printStackTrace();
                response.getWriter().write("Wrong account or password, please try again ~"); }}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}Copy the code

    Note:

    The urlPatterns of the LoginServlet and RegisterServlet have been changed, so the form’s actions have changed as well.

Bug record

Problem 1: Sevlet cannot receive form information.

Description: Request.getparametermap (); request.getParameterMap(); request.getParameterMap(); It’s also empty.

Solution: This is because if the control does not specify a name value, it will not pass in.

Problem 2: The database encoding is incorrect.

Use SHOW VARIABLES LIKE ‘character%’; To view database encoding information. Find the database encoding is utf-8, only one table does not support Chinese, that the table is created before the database changes character set, with the default database the same code set Latin.

Solution: It is convenient to drop the table to create a new table with the same structure. If the database encoding is incorrect, change the database encoding first and then rebuild the table.

Problem 3: The properties file cannot be read.

Description: when reading the file using the InputStream = JDBCUtil. In the class. The getClassLoader () getResourceAsStream (” druid. Properties “); , my properties file and the utility class are under the same package util. When I use the test class, I find a null pointer exception.

Solution: Migrate druid.properties to the SRC directory. A more formal way to write this is to create the Resources directory, mark it as the resource root directory resources root, and then move the properties file into the Resources directory. As shown in the figure:

Final form:

Question 4: occurrence javax.mail. Servlet. ServletException: servlet exception, shows that the root cause is the Java lang. NoClassDefFoundError: org/apache/commons/dbutils/ResultSetHandler

Commons-dbutils packages are missing, but the directory contains two dbutils packages.

Solution: Try to re-import the JAR and remove one version of the dbutils package. Successfully resolved.

To be continued