First day of Java Web comprehensive case (information display after registration, verification code, email verification, login, exit and successful login)

1, Building development environment -- tourism projects based on the separation of front and back ends

Technology stack needed for the project

Backend: servlet, bianutils, Jackson, JavaMail, JDBC template, Druid + MySQL
 Front end: bootstrap + jquery

1. Create web project, java directory and resources directory

2. Import the dependency package needed by the project in pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.bianyiit</groupId>
  <artifactId>maven_tourism</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>maven_tourism Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>

    <!--json Transform dependent-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

    <!--jedis rely on-->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.2</version>
    </dependency>

    <!--beanUtils-->
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
      <scope>compile</scope>
    </dependency>

    <!--javaMail-->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>javax.mail-api</artifactId>
      <version>1.5.6</version>
    </dependency>
    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.5.3</version>
    </dependency>
    <!--jedis-->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.0</version>
    </dependency>

    <!--jdbcTemplate rely on-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <!--druid Connection pool dependency-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>

    <!--Database driven dependency-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>


    <!--web Dependent dependence-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>


    <!--junit rely on-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>day12_redis_role</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <!-- Designated port -->
          <port>8080</port>
          <!-- Request path -->
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

3. Import the front-end resources of the project under webapp -- various html pages / img/css/jquery/bootstrap

4. Create database and import six tables

5. Import two configuration files in resources


6. Import five tool classes under util package

package com.bianyiit.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;

/*
	1. Declare static data source member variables
	2. Create connection pool object
	3. Define the public method of getting data source
	4. Define the method to get the connection object
	5. Define how to close resources
 */
public class JDBCUtils {
	// 1. Declare static data source member variables
	private static DataSource ds;

	// 2. Create connection pool object
	static {
		// Load data from configuration file
		InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
		Properties pp = new Properties();
		try {
			pp.load(is);
			// Create a connection pool, using the parameters in the configuration file
			ds = DruidDataSourceFactory.createDataSource(pp);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 3. Define the public method to get data source
	public static DataSource getDataSource() {
		return ds;
	}

	// 4. Define the method to get the connection object
	public static Connection getConnection() throws SQLException {
		return ds.getConnection();
	}

	// 5. Define how to close resources
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {}
		}

		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {}
		}
	}

	// 6. Heavy load closing method
	public static void close(Connection conn, Statement stmt) {
		close(conn, stmt, null);
	}
}
package com.bianyiit.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Jedis Tool class
 */
public final class JedisUtil {
    private static JedisPool jedisPool;

    static {
        //Read profile
        InputStream is = JedisPool.class.getClassLoader().getResourceAsStream("jedis.properties");
        //Create Properties object
        Properties pro = new Properties();
        //Associated file
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Get data and set it to JedisPoolConfig
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));

        //Initialize JedisPool
        jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));


    }

    /**
     * Get connection method
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * Close Jedis
     */
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
package com.bianyiit.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Emailing tools
 */
public final class MailUtils {
    private static final String USER = "zhangsan@163.com"; // Sender's name, same as email address
    private static final String PASSWORD = "xxxxx"; // If it is qq mailbox, the authorization code or login password of the client can be used

    /**
     *
     * @param to Recipient mailbox
     * @param text Mail text
     * @param title Title
     */
    /* Send mail with validation information */
    public static boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.163.com");

            // Sender's account
            props.put("mail.user", USER);
            //Sender's password
            props.put("mail.password", PASSWORD);

            // Build authorization information for SMTP authentication
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // User name, password
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // Create a mail session using environment properties and authorization information
            Session mailSession = Session.getInstance(props, authenticator);
            // Create mail message
            MimeMessage message = new MimeMessage(mailSession);
            // Set sender
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // Set up recipients
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // Set message title
            message.setSubject(title);

            // Set the content body of the message
            message.setContent(text, "text/html;charset=UTF-8");
            // Send mail
            Transport.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception { // For testing purposes
        MailUtils.sendMail("zhangsan@xx.com","Hello, this is an official email from Bian Yi.","Test mail");
        System.out.println("Send successfully");
    }
}
package com.bianyiit.util;

import java.security.MessageDigest;

/**
 * Write an MD5 algorithm. The running result is the same as the md5() function of MySQL
 * Convert clear text password to MD5 password
 * 123456->e10adc3949ba59abbe56e057f20f883e
 */
public final class Md5Util {
	private Md5Util(){}
	/**
	 * Convert clear text password to MD5 password 
	 */
	public static String encodeByMd5(String password) throws Exception{
		//The MessageDigest class in Java encapsulates MD5 and SHA algorithms. Today we only need MD5 algorithm
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		//Call MD5 algorithm, that is, return 16 values of byte type
		byte[] byteArray = md5.digest(password.getBytes());
		//Note: MessageDigest can only convert String to byte [], and the next work will be done by our programmers
		return byteArrayToHexString(byteArray);
	}
	/**
	 * Convert byte [] to hexadecimal string 
	 */
	private static String byteArrayToHexString(byte[] byteArray) {
		StringBuffer sb = new StringBuffer();
		//ergodic
		for(byte b : byteArray){//The 16 time
			//Take out each byte type and convert it
			String hex = byteToHexString(b);
			//Put the converted value into StringBuffer
			sb.append(hex);
		}
		return sb.toString();
	}
	/**
	 * Convert byte to hexadecimal string 
	 */
	private static String byteToHexString(byte b) {//-31 to e1, 10 to 0a,...
		//Assign byte type to int type
		int n = b;
		//If n is a negative number
		if(n < 0){
			//Positive number
			//-The hexadecimal number of 31 is equivalent to the hexadecimal number of 225 
			n = 256 + n;
		}
		//Quotient (14), subscript of array
		int d1 = n / 16;
		//Remainder (1), subscript of array
		int d2 = n % 16;
		//Value by subscript
		return hex[d1] + hex[d2];
	}
	private static String[] hex = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	/**
	 * test
	 */
	public static void main(String[] args) throws Exception{
		String password = "123456";
		String passwordMD5 = Md5Util.encodeByMd5(password);
		System.out.println(password);
		System.out.println(passwordMD5);
	}
}
package com.bianyiit.util;

import java.util.UUID;

/**
 * Generate UUID random string utility class
 */
public final class UuidUtil {
	private UuidUtil(){}
	public static String getUuid(){
		return UUID.randomUUID().toString().replace("-","");
	}
	/**
	 * test
	 */
	public static void main(String[] args) {
		System.out.println(UuidUtil.getUuid());
		System.out.println(UuidUtil.getUuid());
		System.out.println(UuidUtil.getUuid());
		System.out.println(UuidUtil.getUuid());
	}
}

7. Create two entity classes under domain

package com.bianyiit.domain;

import java.io.Serializable;

/**
 * User entity class
 */
public class User implements Serializable {
    private int uid;//User id
    private String username;//User name
    private String password;//Password
    private String name;//Real name
    private String birthday;//Date of birth
    private String sex;//Male or female
    private String telephone;//Cell-phone number
    private String email;//mailbox
    private String status;//Active, Y for active, N for inactive
    private String code;//Activation code (unique required)

    /**
     * Nonparametric construction method
     */
    public User() {
    }

    /**
     * Parametric method
     * @param uid
     * @param username
     * @param password
     * @param name
     * @param birthday
     * @param sex
     * @param telephone
     * @param email
     * @param status
     * @param code
     */
    public User(int uid, String username, String password, String name, String birthday, String sex, String telephone, String email, String status, String code) {
        this.uid = uid;
        this.username = username;
        this.password = password;
        this.name = name;
        this.birthday = birthday;
        this.sex = sex;
        this.telephone = telephone;
        this.email = email;
        this.status = status;
        this.code = code;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getEmail() {
        return email;
    }

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

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", birthday='" + birthday + '\'' +
                ", sex='" + sex + '\'' +
                ", telephone='" + telephone + '\'' +
                ", email='" + email + '\'' +
                ", status='" + status + '\'' +
                ", code='" + code + '\'' +
                '}';
    }
}
package com.bianyiit.domain;

import java.io.Serializable;
import java.util.Objects;

/**
 * Used to encapsulate back-end return front-end data objects
 */
public class ResultInfo implements Serializable {
    private boolean flag;//The back-end return result is normal to true, and if an exception occurs, false is returned
    private Object data;//Back end returns result data object
    private String errorMsg;//Unexpected error message

    //Nonparametric construction method
    public ResultInfo() {
    }
    public ResultInfo(boolean flag) {
        this.flag = flag;
    }
    /**
     * Parametric construction method
     * @param flag
     * @param errorMsg
     */
    public ResultInfo(boolean flag, String errorMsg) {
        this.flag = flag;
        this.errorMsg = errorMsg;
    }
    /**
     * Parametric construction method
     * @param flag
     * @param data
     * @param errorMsg
     */
    public ResultInfo(boolean flag, Object data, String errorMsg) {
        this.flag = flag;
        this.data = data;
        this.errorMsg = errorMsg;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

2, Analysis of registration function and coding

1. First open index.html to view the portal page of the whole website

2. Open register.html to verify the user name and password

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>register</title>
        <link rel="stylesheet" type="text/css" href="css/common.css">
        <link rel="stylesheet" href="css/register.css">
		<!--Import jquery-->
		<script src="js/jquery-3.3.1.js"></script>
		<script>
            function checkPassword () {
                var password = $("#password").val();

                var  flag = /^\w{3,20}$/.test(password);
                if (!flag){
                    $("#password").css("border","1px solid red");

                }else {
                    $("#password").css("border","");
                }
                return flag;
            }
            function checkUsername () {
                var username = $("#username").val();

                var  flag = /^\w{3,20}$/.test(username);
                if (!flag){
                    $("#username").css("border","1px solid red");

                }else {
                    $("#username").css("border","");
                }
                return flag;
            }
			$(function () {
                /*
				*  Verify user name
				*  	Length 3-20 characters (letters or numbers)
				* */
				$("#username").blur(checkUsername);
                /*
               *  Check password
               *  	Length 3-20 characters (letters or numbers)
               * */
                $("#password").blur(checkPassword);

                $("#registerForm").submit(function () {
					var usernameFlag = checkUsername();
                    var passwordFlag = checkPassword();
                    if (usernameFlag && passwordFlag){
                        //Submit form data to the server through ajax
							// Reason: the basic structure of the project is the separation of the front and back ends. The front-end pages are all html pages, and the data in the request cannot be obtained through the el expression in the html page
							// All servers cannot keep the data in the request and pass it to the page, but the ajax request can accept the data returned by the server
                        $.post("/registServlet",$("#registerForm").serialize(),function (data) {
                            /*
								1. If the server registers successfully, jump to the page

								2. Otherwise, display the error message
                        	*/

                            if(data.flag){
                                location.href = "register_ok.html"
							}else {
                                $("#errorMsg").html(data.errorMsg)
							}
                        },"json");

					}
                    return false;
                });
            })
		</script>


    </head>
	<body>
	<!--Introduction of the head-->
	<div id="header"></div>
        <!-- head end -->
    	<div class="rg_layout">
    		<div class="rg_form clearfix">
    			<div class="rg_form_left">
    				<p>New user registration</p>
    				<p>USER REGISTER</p>
    			</div>
    			<div class="rg_form_center">
					<div id="errorMsg" style="color:red;text-align: center"></div>
					<!--Registration form-->
    				<form id="registerForm" action="/registServlet">
						<!--Identifier of the submitted processing request-->
						<input type="hidden" name="action" value="register">
    					<table style="margin-top: 25px;">
    						<tr>
    							<td class="td_left">
    								<label for="username">User name</label>
    							</td>
    							<td class="td_right">
    								<input type="text" id="username" name="username" placeholder="Please enter your account number">
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="password">Password</label>
    							</td>
    							<td class="td_right">
    								<input type="password" id="password" name="password" placeholder="Please input a password">
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="email">Email</label>
    							</td>
    							<td class="td_right">
    								<input type="text" id="email" name="email" placeholder="Please input Email">
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="name">Full name</label>
    							</td>
    							<td class="td_right">
    								<input type="text" id="name" name="name" placeholder="Please enter your real name">
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="telephone">Cell-phone number</label>
    							</td>
    							<td class="td_right">
    								<input type="text" id="telephone" name="telephone" placeholder="Please enter your mobile number">
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="sex">Gender</label>
    							</td>
    							<td class="td_right gender">
    								<input type="radio" id="sex" name="sex" value="male" checked> male
    								<input type="radio" name="sex" value="female"> female
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="birthday">Date of birth</label>
    							</td>
    							<td class="td_right">
    								<input type="date" id="birthday" name="birthday" placeholder="year/month/day">
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left">
    								<label for="check">Verification Code</label>
    							</td>
    							<td class="td_right check">
    								<input type="text" id="check" name="check" class="check">
    								<img src="checkCode" height="32px" alt="" onclick="changeCheckCode(this)">
									<script type="text/javascript">
										//Picture click event
										function changeCheckCode(img) {
											img.src="/checkCode?"+new Date().getTime();
                                        }
									</script>
    							</td>
    						</tr>
    						<tr>
    							<td class="td_left"> 
    							</td>
    							<td class="td_right check"> 
    								<input type="submit" class="submit" value="register">
									<span id="msg" style="color: red;"></span>
    							</td>
    						</tr>
    					</table>
    				</form>
    			</div>
    			<div class="rg_form_right">
    				<p>
    					//Already have an account?
    					<a href="#"> log in now</a>
    				</p>
    			</div>
    		</div>
    	</div>
        <!--Leading tail-->
    	<div id="footer"></div>
		<!--Import layout js,Share header and footer-->
		<script type="text/javascript" src="js/include.js"></script>
    	
    </body>
</html>

1. Click the registration button to enter the registration interface

2. Timing I of front end verification: input box loses focus

2. Timing 2 of front end verification: before submitting the form

4. Demonstration of the effect of incorrect user name and correct password (not involving the processing of the server, simple front-end verification)

5. Demonstration of the effect of correct user name and wrong password (not involving the processing of server, simple front-end verification)

3. Create a new filter package under the web to solve the Chinese scrambling of the browser's incoming request s

package com.bianyiit.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }
}

3. Create a servlet package under the web, and a RegistServlet under the package

package com.bianyiit.web.servlet;

import com.bianyiit.domain.ResultInfo;
import com.bianyiit.domain.User;
import com.bianyiit.services.UserService;
import com.bianyiit.services.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

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;

@WebServlet("/registServlet")
public class RegistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        ResultInfo resultInfo = new ResultInfo();

        String check = request.getParameter("check");
        String checkcode_server = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        request.getSession().removeAttribute("CHECKCODE_SERVER");

        ObjectMapper objectMapper = new ObjectMapper();
        if(checkcode_server==null||!check.equalsIgnoreCase(checkcode_server)){
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("Incorrect verification code");
            objectMapper.writeValue(response.getWriter(),resultInfo);
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println(user);
        UserService userService = new UserServiceImpl();
        int update = 0;
        try {
            update = userService.regist(user);
        } catch (Exception e) {
            e.printStackTrace();
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("login has failed");
            objectMapper.writeValue(response.getWriter(),resultInfo);
            return;
        }
        if(update>0){
            //response.sendRedirect(request.getContextPath()+"/register.html");
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("login was successful");
            objectMapper.writeValue(response.getWriter(),resultInfo);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Business process

4. Interface oriented programming can improve the maintainability and expansibility of the program

package com.bianyiit.services;

import com.bianyiit.domain.User;

public interface UserService {
    int regist(User user);
}
package com.bianyiit.services;

import com.bianyiit.dao.UserDao;
import com.bianyiit.dao.UserDaoImpl;
import com.bianyiit.domain.User;
import com.bianyiit.util.JedisUtil;
import com.bianyiit.util.MailUtils;
import com.bianyiit.util.UuidUtil;
import redis.clients.jedis.Jedis;

public class UserServiceImpl implements UserService {
    UserDao userDao=new UserDaoImpl();
    @Override
    public int regist(User user) {
        //1. Save user to database
        int add = userDao.add(user);
        return add;
    }
}
package com.bianyiit.dao;

import com.bianyiit.domain.User;

public interface UserDao {
    int add(User user);
}
package com.bianyiit.dao;

import com.bianyiit.domain.User;
import com.bianyiit.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDaoImpl implements UserDao{
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public int add(User user) {
        String sql="insert into tab_user values (null,?,?,?,?,?,?,?,?,?)";
        int update = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getName(),
                user.getBirthday(),
                user.getSex(),
                user.getTelephone(),
                user.getEmail(),
                user.getStatus(),
                user.getCode());
        return update;
    }
}

Page effect display


3, Analysis and coding of verification code function

1. Find the register page

2. Create a new CheckCodeServlet in the servlet

package com.bianyiit.web.servlet;

import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Verification Code
 */
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		//Server tells browser not to cache
		response.setHeader("pragma","no-cache");
		response.setHeader("cache-control","no-cache");
		response.setHeader("expires","0");
		
		//Create a picture with a length of 80 and a width of 30 in memory. The default black background
		//Parameter 1: length
		//Parameter 2: width
		//Parameter 3: color
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		//Get brush
		Graphics g = image.getGraphics();
		//Set brush color to gray
		g.setColor(Color.GRAY);
		//Fill picture
		g.fillRect(0,0, width,height);
		
		//Generate 4 random verification codes, 12Ey
		String checkCode = getCheckCode();
		//Put the verification code into HttpSession
		request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
		
		//Set the brush color to yellow
		g.setColor(Color.YELLOW);
		//Set font size
		g.setFont(new Font("Blackbody",Font.BOLD,24));
		//Write verification code to picture
		g.drawString(checkCode,15,25);
		
		//Output pictures in memory to browser
		//Parameter 1: picture object
		//Parameter 2: image format, such as PNG,JPG,GIF
		//Parameter 3: where to output the picture
		ImageIO.write(image,"PNG",response.getOutputStream());
	}
	/**
	 * Generate 4-bit random string 
	 */
	private String getCheckCode() {
		String base = "0123456789ABCDEFGabcdefg";
		int size = base.length();
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i=1;i<=4;i++){
			//Generate a random value from 0 to size-1
			int index = r.nextInt(size);
			//Get the character with index as the subscript in the base string
			char c = base.charAt(index);
			//Put c in StringBuffer
			sb.append(c);
		}
		return sb.toString();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request,response);
	}
}

Verification code effect demonstration:

4, Analysis and coding of mailbox verification function

1. Go back to the UserServiceImpl used for registration. When we save the user information to the database, we send the activation mailbox to the real mailbox

package com.bianyiit.services;

import com.bianyiit.dao.UserDao;
import com.bianyiit.dao.UserDaoImpl;
import com.bianyiit.domain.User;
import com.bianyiit.util.JedisUtil;
import com.bianyiit.util.MailUtils;
import com.bianyiit.util.UuidUtil;
import redis.clients.jedis.Jedis;

public class UserServiceImpl implements UserService {
    UserDao userDao=new UserDaoImpl();
    @Override
    public int regist(User user) {
        //1. Save user to database
        int add = userDao.add(user);
        //2. Send activation email
        String uuid = UuidUtil.getUuid();
        Jedis jedis = JedisUtil.getJedis();
        //Two hour verification code is valid
        jedis.setex(uuid,5*60,user.getUsername());
        jedis.close();

        String mailContent="<a href='http://Localhost: 8080 / activeservlet? Activecode = + UUID + "'> please click here to activate your user < / a >";
        MailUtils.sendMail(user.getEmail(),mailContent,"User activation message");
        return add;
    }

    @Override
    public boolean active(String activeCode) {

        Jedis jedis = JedisUtil.getJedis();
        String username = jedis.get(activeCode);
        if(username==null||username.length()==0){
            return false;
        }else {
            int active = userDao.active(username);
            if(active>0){
                return true;
            }else{
                return false;
            }
        }
    }
}

2. Use a MailUtil tool class to complete the encapsulation of the sending mailbox

package com.bianyiit.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Emailing tools
 */
public final class MailUtils {
    private static final String USER = "zhangsan@qq.com"; // Sender's name, same as email address
    private static final String PASSWORD = "1f5ewf1a5f1ae5fa"; // If it is qq mailbox, the authorization code or login password of the client can be used

    /**
     *
     * @param to Recipient mailbox
     * @param text Mail text
     * @param title Title
     */
    /* Send mail with validation information */
    public static boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");

            // Sender's account
            props.put("mail.user", USER);
            //Sender's password
            props.put("mail.password", PASSWORD);

            // Build authorization information for SMTP authentication
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // User name, password
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // Create a mail session using environment properties and authorization information
            Session mailSession = Session.getInstance(props, authenticator);
            // Create mail message
            MimeMessage message = new MimeMessage(mailSession);
            // Set sender
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // Set up recipients
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // Set message title
            message.setSubject(title);

            // Set the content body of the message
            message.setContent(text, "text/html;charset=UTF-8");
            // Send mail
            Transport.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception { // For testing purposes
        MailUtils.sendMail("zenglinkui@163.com","Hello, this is an official email from Bian Yi.","Test mail");
        System.out.println("Send successfully");
    }
}

3. Open SMTP and POP3 protocols in QQ mailbox

4. After opening successfully, send an email to the user through the following code



5. After entering the mailbox and clicking, jump to ActiveServlet

package com.bianyiit.web.servlet;

import com.bianyiit.services.UserService;
import com.bianyiit.services.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;

@WebServlet("/activeServlet")
public class ActiveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String activeCode = request.getParameter("activeCode");
        System.out.println(activeCode);
        UserService userService=new UserServiceImpl();
        boolean isactive = userService.active(activeCode);
        if(isactive){
            //Activation succeeded, jump to home page
            response.sendRedirect(request.getContextPath()+"/active_ok.html");
        }else {
            response.sendRedirect(request.getContextPath()+"/active_fail.html");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}


Effect demonstration after successful activation

5, Analysis of login function and coding

1. Create a new login.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bianyi holiday net-Sign in</title>
    <link rel="stylesheet" type="text/css" href="css/common.css">
    <link rel="stylesheet" type="text/css" href="css/login.css">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
      <!--Import angularJS file-->
    <!--<script src="js/angular.min.js"></script>-->
	<!--Import jquery-->
	<script src="js/jquery-3.3.1.js"></script>

	<script>

		$(function () {
            //1. Bind click event to login button
			$("#btn_sub").click(function () {
                //2. Send ajax request and submit form data
				$.post("/loginServlet",$("#loginForm").serialize(),function (data) {
					//data : {flag:false,errorMsg:''}
					if(data.flag){
					    //Login successfully
						location.href="index.html";
					}else{
					    //Login failed
						$("#errorMsg").html(data.errorMsg);
					}
                });
            });
        });


		//3. Handling response results



	</script>
</head>

<body>
<!--Introduction of the head-->
<div id="header"></div>
    <!-- head end -->
    <section id="login_wrap">
        <div class="fullscreen-bg" style="background: url(images/login_bg.png);height: 532px;">
        	
        </div>
        <div class="login-box">
        	<div class="title">

        		<span>Welcome to our holiday account</span>
        	</div>
        	<div class="login_inner">
				
				<!--Login error message-->
        		<div id="errorMsg" class="alert alert-danger" ></div>
				<form id="loginForm" action="" method="post" accept-charset="utf-8">
        			<input type="hidden" name="action" value="login"/>
					<input name="username" type="text" placeholder="Please enter your account number" autocomplete="off">
        			<input name="password" type="text" placeholder="Please input a password" autocomplete="off">
        			<div class="verify">
					<input name="check" type="text" placeholder="Please enter the verification code" autocomplete="off">
					<span><img src="checkCode" alt="" onclick="changeCheckCode(this)"></span>
					<script type="text/javascript">
						//Picture click event
						function changeCheckCode(img) {
							img.src="checkCode?"+new Date().getTime();
						}
					</script>
			</div>
			<div class="submit_btn">
        				<button type="button"  id="btn_sub">Sign in</button>
        				<div class="auto_login">
        					<input type="checkbox" name="" class="checkbox">
        					<span>automatic logon</span>
        				</div>        				
        			</div>        			       		
        		</form>
        		<div class="reg">No account?<a href="javascript:;">Immediate registration</a></div>
        	</div>
        </div>
    </section>
    <!--Leading tail-->
    <div id="footer"></div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery-1.11.0.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <!--Import layout js,Share header and footer-->
    <script type="text/javascript" src="js/include.js"></script>
</body>

</html>

2. Create a new LoginServlet

package com.bianyiit.web.servlet;

import com.bianyiit.domain.ResultInfo;
import com.bianyiit.domain.User;
import com.bianyiit.services.UserService;
import com.bianyiit.services.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

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("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        ResultInfo info = new ResultInfo();
        ObjectMapper objectMapper = new ObjectMapper();

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

        String checkCode= (String)request.getSession().getAttribute("CHECKCODE_SERVER");
        request.getSession().removeAttribute(checkCode);
        if(checkCode==null||!checkCode.equalsIgnoreCase(check)){
            info.setFlag(false);
            info.setErrorMsg("Verification code error");
            objectMapper.writeValue(response.getWriter(),info);
            return;
        }
        UserService userService=new UserServiceImpl();
        User user = userService.login(username);

        if(user==null){
            info.setFlag(false);
            info.setErrorMsg("Login user does not exist");
        }else {
            if(password==null||!password.equals(user.getPassword())){
                info.setFlag(false);
                info.setErrorMsg("Incorrect password");
            }else if(user.getStatus()==null){
                info.setFlag(false);
                info.setErrorMsg("User not activated");
            }else{
                info.setFlag(true);
                request.getSession().setAttribute("loginUser",user);
            }
        }
        objectMapper.writeValue(response.getWriter(),info);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

3. Business logic processing

4. After successful login, encapsulate the user information into the session

5. After successful login, return a data data through ajax and set info.flag to true

6. At this time, we find a piece of code in header.html to obtain the user name in the session where the user exists

7.FindLoginUserServlet

package com.bianyiit.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

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("/findLoginUserServlet")
public class FindLoginUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object loginUser = request.getSession().getAttribute("loginUser");
        response.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(response.getWriter(),loginUser);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

8. Effect demonstration of login

6, Analysis of exit function and coding

1. Request ExitServlet to clear the value of Session

2.ExitServlet

package com.bianyiit.web.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("/exitServlet")
public class ExitServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect("index.html");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

3. Effect demonstration after clicking exit

Published 73 original articles, won praise 11, visited 2276
Private letter follow

Tags: Java Jedis Maven JQuery

Posted on Mon, 13 Jan 2020 10:48:46 -0500 by treybraid