Case---User Information List Display Module

Table of contents

1. Demand

2. Design

2.1 Technical selection

2.2 Database Design

3. Create a project, import html and jsp pages, configuration files, jar packages

3.1 Importing html and jsp pages

3.1.1 css, fonts, js related files

3.1.2html page

3.1.3 Configuration file

3.1.4jar package

4. Function query

4.1 Functional query analysis

4.2 Code Implementation

5. User login

5.1 User Login Analysis

5.2 Code Implementation

6. Add features

6.1 Analysis

6.2 Code Implementation

1. Demand

User information addition, deletion, modification and query operations

2. Design

2.1 Technical selection

Servlet+JSP+MySQL+JDBCTempleat+Duird+BeanUtilS+tomcat

2.2 Database Design

create database day17; -- create database
use day17;                -- use database
create table user(   -- create table
    id int primary key auto_increment,
    name varchar(20) not null,
    gender varchar(5),
    age int,
    address varchar(32),
    qq    varchar(20),
    email varchar(50)
)

3. Create a project, import html and jsp pages, configuration files, jar packages

3.1 Importing html and jsp pages

Import the following packages next time

3.1.1 css, fonts, js related files

 

 

You can find the corresponding file through the BooStrap official website, or the file format you like.

3.1.2html page

add.html

<!-- HTML5 Documentation-->
<!DOCTYPE html>
<!-- language of the page -->
<html lang="zh-CN">
<head>
    <!-- specified character set -->
    <meta charset="utf-8">
    <!-- use Edge Rendering in the latest browsers -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: The web page can be automatically adapted according to the set width, and a container is virtualized inside the browser. The width of the container is the same as the width of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio, which is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 3 above meta Label*must*on top, anything else is*must*Follow it! -->
    <title>Add user</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <center><h3>add contact page</h3></center>
    <form action="" method="post">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Please type in your name">
        </div>

        <div class="form-group">
            <label>gender:</label>
            <input type="radio" name="sex" value="male" checked="checked"/>male
            <input type="radio" name="sex" value="Female"/>Female
        </div>

        <div class="form-group">
            <label for="age">age:</label>
            <input type="text" class="form-control" id="age" name="age" placeholder="Please enter age">
        </div>

        <div class="form-group">
            <label for="address">Nationality:</label>
            <select name="address" class="form-control" id="jiguan">
                <option value="Guangdong">Guangdong</option>
                <option value="Guangxi">Guangxi</option>
                <option value="Hunan">Hunan</option>
            </select>
        </div>

        <div class="form-group">
            <label for="qq">QQ: </label>
            <input type="text" class="form-control" name="qq" placeholder="please enter QQ Number"/>
        </div>

        <div class="form-group">
            <label for="email">Email: </label>
            <input type="text" class="form-control" name="email" placeholder="Please input the email address"/>
        </div>

        <div class="form-group" style="text-align: center">
            <input class="btn btn-primary" type="submit" value="submit" />
            <input class="btn btn-default" type="reset" value="reset" />
            <input class="btn btn-default" type="button" value="return" />
        </div>
    </form>
</div>
</body>
</html>

 index.html

<!DOCTYPE html> 
<html lang="zh-CN">
  <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>front page</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
    </script>
  </head>
  <body>
  <div align="center">
  	<a
	  href="list.html" style="text-decoration:none;font-size:33px">Query all user information
	</a>
  </div>
  </body>
</html>

 list.html

<!DOCTYPE html>
<!-- language of the page -->
<html lang="zh-CN">
<head>
    <!-- specified character set -->
    <meta charset="utf-8">
    <!-- use Edge Rendering in the latest browsers -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: The web page can be automatically adapted according to the set width, and a container is virtualized inside the browser. The width of the container is the same as the width of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio, which is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 3 above meta Label*must*on top, anything else is*must*Follow it! -->
    <title>User Information Management System</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
    <style type="text/css">
        td, th {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <h3 style="text-align: center">User information list</h3>
    <table border="1" class="table table-bordered table-hover">
        <tr class="success">
            <th>Numbering</th>
            <th>Name</th>
            <th>gender</th>
            <th>age</th>
            <th>Hometown</th>
            <th>QQ</th>
            <th>Mail</th>
            <th>operate</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Zhang San</td>
            <td>male</td>
            <td>20</td>
            <td>Guangdong</td>
            <td>44444222</td>
            <td>zs@qq.com</td>
            <td><a class="btn btn-default btn-sm" href="update.html">Revise</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
        </tr>
        <tr>
            <td>2</td>
            <td>Zhang San</td>
            <td>male</td>
            <td>20</td>
            <td>Guangdong</td>
            <td>44444222</td>
            <td>zs@qq.com</td>
            <td><a class="btn btn-default btn-sm" href="update.html">Revise</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
        </tr>
        <tr>
            <td>3</td>
            <td>Zhang San</td>
            <td>male</td>
            <td>20</td>
            <td>Guangdong</td>
            <td>44444222</td>
            <td>zs@qq.com</td>
            <td><a class="btn btn-default btn-sm" href="update.html">Revise</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
        </tr>
        <tr>
            <td>4</td>
            <td>Zhang San</td>
            <td>male</td>
            <td>20</td>
            <td>Guangdong</td>
            <td>44444222</td>
            <td>zs@qq.com</td>
            <td><a class="btn btn-default btn-sm" href="update.html">Revise</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
        </tr>
        <tr>
            <td>5</td>
            <td>Zhang San</td>
            <td>male</td>
            <td>20</td>
            <td>Guangdong</td>
            <td>44444222</td>
            <td>zs@qq.com</td>
            <td><a class="btn btn-default btn-sm" href="update.html">Revise</a>&nbsp;<a class="btn btn-default btn-sm" href="">delete</a></td>
        </tr>
        <tr>
            <td colspan="8" align="center"><a class="btn btn-primary" href="add.html">Add contacts</a></td>
        </tr>
    </table>
</div>
</body>
</html>

 login.html

<!DOCTYPE html> 
<html lang="zh-CN">
  <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>Admin login</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
    </script>
  </head>
  <body>
  	<div class="container" style="width: 400px;">
  		<h3 style="text-align: center;">Admin login</h3>
        <form action="login" method="post">
	      <div class="form-group">
	        <label for="user">username:</label>
	        <input type="text" name="user" class="form-control" id="user" placeholder="please enter user name"/>
	      </div>
	      
	      <div class="form-group">
	        <label for="password">password:</label>
	        <input type="password" name="password" class="form-control" id="password" placeholder="Please enter password"/>
	      </div>
	      
	      <div class="form-inline">
	        <label for="vcode">Verification code:</label>
	        <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="please enter verification code" style="width: 120px;"/>
	        <a href="javascript:refreshCode()"><img src="vcode" title="Can't see clearly click refresh" id="vcode"/></a>
	      </div>
	      <hr/>
	      <div class="form-group" style="text-align: center;">
	        <input class="btn btn btn-primary" type="submit" value="Log in">
	       </div>
	  	</form>
		
		<!-- error message box -->
	  	<div class="alert alert-warning alert-dismissible" role="alert">
		  <button type="button" class="close" data-dismiss="alert" >
		  	<span>&times;</span></button>
		   <strong>Login failed!</strong>
		</div>
  	</div>
  </body>
</html>

update.html

<!DOCTYPE html>
<!-- language of the page -->
<html lang="zh-CN">
    <head>
    	<base href="<%=basePath%>"/>
        <!-- specified character set -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>modify user</title>

        <link href="css/bootstrap.min.css" rel="stylesheet">
        <script src="js/jquery-2.1.0.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
        
    </head>
    <body>
        <div class="container" style="width: 400px;">
        <h3 style="text-align: center;">Edit contacts</h3>
        <form action="" method="post">
          <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" id="name" name="name"  readonly="readonly" placeholder="Please type in your name" />
          </div>

          <div class="form-group">
            <label>gender:</label>
              <input type="radio" name="sex" value="male"  />male
                <input type="radio" name="sex" value="Female"  />Female
          </div>

          <div class="form-group">
            <label for="age">age:</label>
            <input type="text" class="form-control" id="age"  name="age" placeholder="Please enter age" />
          </div>

          <div class="form-group">
            <label for="address">Nationality:</label>
             <select name="address" class="form-control" >
                <option value="Guangdong">Guangdong</option>
                <option value="Guangxi">Guangxi</option>
                <option value="Hunan">Hunan</option>
            </select>
          </div>

          <div class="form-group">
            <label for="qq">QQ: </label>
            <input type="text" class="form-control" name="qq" placeholder="please enter QQ Number"/>
          </div>

          <div class="form-group">
            <label for="email">Email: </label>
            <input type="text" class="form-control" name="email" placeholder="Please input the email address"/>
          </div>

             <div class="form-group" style="text-align: center">
                <input class="btn btn-primary" type="submit" value="submit" />
                <input class="btn btn-default" type="reset" value="reset" />
                <input class="btn btn-default" type="button" value="return"/>
             </div>
        </form>
        </div>
    </body>
</html>

3.1.3 Configuration file

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day17
username=root
password=root
# Initialize the number of connections
initialSize=5
# Maximum number of connections
maxActive=10
# maximum waiting time
maxWait=3000

 JDBCUtils.java

package cn.itcast.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC Tool class using Durid connection pool
 */
public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1. Load the configuration file
            Properties pro = new Properties();
            //Use ClassLoader to load configuration file and get byte input stream
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2. Initialize the connection pool object
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Get the connection pool object
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * Get the connection Connection object
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

3.1.4jar package

4. Function query

4.1 Functional query analysis

When the user clicks "Query all user information" on the index.jsp page, the page jumps to the list.jsp page and displays the query information.

4.2 Code Implementation

User.java

package cn.itcast.domain;

public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String address;
    private String qq;
    private String email;

    private String username;
    private String password;

    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 int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getEmail() {
        return email;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", qq='" + qq + '\'' +
                ", email='" + email + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html lang="zh-CN">
<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>front page</title>

  <!-- 1. import CSS the global style of -->
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
  <script src="js/jquery-2.1.0.min.js"></script>
  <!-- 3. import bootstrap of js document -->
  <script src="js/bootstrap.min.js"></script>
  <script type="text/javascript">
  </script>
</head>
<body>


  <div >${user.name},Welcome</div>
  <div align="center">
    <a
            href="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">Query all user information
    </a>
  </div>






</body>
</html>

userListServlet.java

package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.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.util.List;

@WebServlet("/userListServlet")
public class UserListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Call UserService to complete the query
        UserService service = new UserServiceImpl();
        List<User> users = service.findAll();
        //2. Store the list in the request field
        request.setAttribute("users",users);
        //3. Forward to list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

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

Build a session 👉Call the lower-level method (servicefindAll()) 👉Set the return value List<User> users to share in the request domain 👉Use the principle of forwarding to send the List<User> users information to the list.jsp page

UserService.java

package cn.itcast.service;

import cn.itcast.domain.PageBean;
import cn.itcast.domain.User;

import java.util.List;
import java.util.Map;

/**
 * User management business interface
 */
public interface UserService {

    /**
     * Query all user information
     * @return
     */
    public List<User> findAll();

    /**
     * login method
     * @param user
     * @return
     */
    User login(User user);

    /**
     * saveUser
     * @param user
     */
    void addUser(User user);

    /**
     * Delete User by id
     * @param id
     */
    void deleteUser(String id);

    /**
     * query by id
     * @param id
     * @return
     */
    User findUserById(String id);

    /**
     * Modify user information
     * @param user
     */
    void updateUser(User user);

    /**
     * Delete users in bulk
     * @param ids
     */
    void delSelectedUser(String[] ids);

    /**
     * Paging condition query
     * @param currentPage
     * @param rows
     * @param condition
     * @return
     */
    PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition);
}

 UserServicelmpl.java

package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();

    @Override
    public List<User> findAll() {
        //Call Dao to complete the query
        return dao.findAll();
    }

    @Override
    public User login(User user) {
        return dao.findUserByUsernameAndPassword(user.getUsername(),user.getPassword());
    }

    @Override
    public void addUser(User user) {
        dao.add(user);
    }

    @Override
    public void deleteUser(String id) {
        dao.delete(Integer.parseInt(id));
    }

    @Override
    public User findUserById(String id) {
        return dao.findById(Integer.parseInt(id));
    }

    @Override
    public void updateUser(User user) {
        dao.update(user);
    }

    @Override
    public void delSelectedUser(String[] ids) {
        if(ids != null && ids.length > 0){
            //1. Traverse the array
            for (String id : ids) {
                //2. Call dao to delete
                dao.delete(Integer.parseInt(id));
            }
        }

    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {

        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);

        if(currentPage <=0) {
            currentPage = 1;
        }
        //1. Create an empty PageBean object
        PageBean<User> pb = new PageBean<User>();
        //2. Set parameters
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);

        //3. Call dao to query the total number of records
        int totalCount = dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);
        //4. Call dao to query the List collection
        //The index of the record at which the calculation starts
        int start = (currentPage - 1) * rows;
        List<User> list = dao.findByPage(start,rows,condition);
        pb.setList(list);

        //5. Calculate the total page number
        int totalPage = (totalCount % rows)  == 0 ? totalCount/rows : (totalCount/rows) + 1;
        pb.setTotalPage(totalPage);


        return pb;
    }
}

UserDao.java

package cn.itcast.dao;

import cn.itcast.domain.User;

import java.util.List;
import java.util.Map;

/**
 * User-operated DAO
 */
public interface UserDao {


    public List<User> findAll();

    User findUserByUsernameAndPassword(String username, String password);

    void add(User user);

    void delete(int id);

    User findById(int i);

    void update(User user);

    /**
     * Query the total number of records
     * @return
     * @param condition
     */
    int findTotalCount(Map<String, String[]> condition);

    /**
     * Paging query records per page
     * @param start
     * @param rows
     * @param condition
     * @return
     */
    List<User> findByPage(int start, int rows, Map<String, String[]> condition);
}

UserDaoimpl.java

package cn.itcast.dao.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<User> findAll() {
        //Use JDBC to operate database...
        //1. Define sql
        String sql = "select * from user";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));

        return users;
    }

    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        try {
            String sql = "select * from user where username = ? and password = ?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public void add(User user) {
        //1. Define sql
        String sql = "insert into user values(null,?,?,?,?,?,?,null,null)";
        //2. Execute sql
        template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
    }

    @Override
    public void delete(int id) {
        //1. Define sql
        String sql = "delete from user where id = ?";
        //2. Execute sql
        template.update(sql, id);
    }

    @Override
    public User findById(int id) {
        String sql = "select * from user where id = ?";
        return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
    }

    @Override
    public void update(User user) {
        String sql = "update user set name = ?,gender = ? ,age = ? , address = ? , qq = ?, email = ? where id = ?";
        template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId());
    }

    @Override
    public int findTotalCount(Map<String, String[]> condition) {
        //1. Define the template to initialize sql
        String sql = "select count(*) from user where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //2. Traverse the map
        Set<String> keySet = condition.keySet();
        //A collection of defined parameters
        List<Object> params = new ArrayList<Object>();
        for (String key : keySet) {

            //Exclude pagination condition parameter
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }

            //get value
            String value = condition.get(key)[0];
            //Determine whether value has a value
            if(value != null && !"".equals(value)){
                //valuable
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//? the value of the condition
            }
        }
        System.out.println(sb.toString());
        System.out.println(params);

        return template.queryForObject(sb.toString(),Integer.class,params.toArray());
    }

    @Override
    public List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
        String sql = "select * from user  where 1 = 1 ";

        StringBuilder sb = new StringBuilder(sql);
        //2. Traverse the map
        Set<String> keySet = condition.keySet();
        //A collection of defined parameters
        List<Object> params = new ArrayList<Object>();
        for (String key : keySet) {

            //Exclude pagination condition parameter
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }

            //get value
            String value = condition.get(key)[0];
            //Determine whether value has a value
            if(value != null && !"".equals(value)){
                //valuable
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//? the value of the condition
            }
        }

        //Add pagination query
        sb.append(" limit ?,? ");
        //Add pagination query parameter value
        params.add(start);
        params.add(rows);
        sql = sb.toString();
        System.out.println(sql);
        System.out.println(params);

        return template.query(sql,new BeanPropertyRowMapper<User>(User.class),params.toArray());
    }
}

 Create the UserService interface, define the method, create the UserServicelmpl class to implement the interface, and rewrite the method 👉Tell the lower layer (dao) to call its findAll() method 👉The dao layer creates the UserDao interface, and defines the findAll() method as pubilc List<user> Type 👉UserDaoimpl implements the UserDao interface and rewrites the findAll() method

When findAll() finishes operating the database, it returns a List<User> users, which is forwarded from the dao layer 👉service layer 👉UserListServlet layer to list.jsp

list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<!-- language of the page -->
<html lang="zh-CN">
<head>
    <!-- specified character set -->
    <meta charset="utf-8">
    <!-- use Edge Rendering in the latest browsers -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: The web page can be automatically adapted according to the set width, and a container is virtualized inside the browser. The width of the container is the same as the width of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio, which is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 3 above meta Label*must*on top, anything else is*must*Follow it! -->
    <title>User Information Management System</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
    <style type="text/css">
        td, th {
            text-align: center;
        }
    </style>

    <script>
        function deleteUser(id){
            //User Safety Tips
            if(confirm("Are you sure you want to delete it?")){
                //access path
                location.href="${pageContext.request.contextPath}/delUserServlet?id="+id;
            }
        }

        window.onload = function(){
            //Add click event to delete checked button
            document.getElementById("delSelected").onclick = function(){
                if(confirm("Are you sure you want to delete the selected item?")){

                   var flag = false;
                    //Determine if an item is selected
                    var cbs = document.getElementsByName("uid");
                    for (var i = 0; i < cbs.length; i++) {
                        if(cbs[i].checked){
                            //An item is selected
                            flag = true;
                            break;
                        }
                    }

                    if(flag){//item is selected
                        //form submission
                        document.getElementById("form").submit();
                    }

                }

            }
            //1. Get the first cb
            document.getElementById("firstCb").onclick = function(){
                //2. Get all the cb s in the list below
                var cbs = document.getElementsByName("uid");
                //3. Traverse
                for (var i = 0; i < cbs.length; i++) {
                    //4. Set the checked status of these cbs[i] = firstCb.checked
                    cbs[i].checked = this.checked;

                }

            }


        }


    </script>
</head>
<body>
<div class="container">
    <h3 style="text-align: center">User information list</h3>

    <div style="float: left;">

        <form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
            <div class="form-group">
                <label for="exampleInputName2">Name</label>
                <input type="text" name="name" value="${condition.name[0]}" class="form-control" id="exampleInputName2" >
            </div>
            <div class="form-group">
                <label for="exampleInputName3">Hometown</label>
                <input type="text" name="address" value="${condition.address[0]}" class="form-control" id="exampleInputName3" >
            </div>

            <div class="form-group">
                <label for="exampleInputEmail2">Mail</label>
                <input type="text" name="email" value="${condition.email[0]}" class="form-control" id="exampleInputEmail2"  >
            </div>
            <button type="submit" class="btn btn-default">Inquire</button>
        </form>

    </div>

    <div style="float: right;margin: 5px;">

        <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">Add contacts</a>
        <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">delete selected</a>

    </div>
    <form id="form" action="${pageContext.request.contextPath}/delSelectedServlet" method="post">
        <table border="1" class="table table-bordered table-hover">
        <tr class="success">
            <th><input type="checkbox" id="firstCb"></th>
            <th>Numbering</th>
            <th>Name</th>
            <th>gender</th>
            <th>age</th>
            <th>Hometown</th>
            <th>QQ</th>
            <th>Mail</th>
            <th>operate</th>
        </tr>

        <c:forEach items="${pb.list}" var="user" varStatus="s">
            <tr>
                <td><input type="checkbox" name="uid" value="${user.id}"></td>9
                <td>${s.count}</td>
                <td>${user.name}</td>
                <td>${user.gender}</td>
                <td>${user.age}</td>
                <td>${user.address}</td>
                <td>${user.qq}</td>
                <td>${user.email}</td>
                <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">Revise</a>&nbsp;
                    <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">delete</a></td>
            </tr>

        </c:forEach>


    </table>
    </form>
    <div>
        <nav aria-label="Page navigation">
            <ul class="pagination">
                <c:if test="${pb.currentPage == 1}">
                    <li class="disabled">
                </c:if>

                <c:if test="${pb.currentPage != 1}">
                    <li>
                </c:if>


                    <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage - 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>


                <c:forEach begin="1" end="${pb.totalPage}" var="i" >


                    <c:if test="${pb.currentPage == i}">
                        <li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
                    </c:if>
                    <c:if test="${pb.currentPage != i}">
                        <li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
                    </c:if>

                </c:forEach>


                <li>
                    <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                <span style="font-size: 25px;margin-left: 5px;">
                    common ${pb.totalCount}records, total ${pb.totalPage}Page
                </span>

            </ul>
        </nav>


    </div>


</div>


</body>
</html>

5. User login

5.1 User Login Analysis

 First, let the user input data in login.jsp, and then use session in LoginServlet.java to get the verification code symbol of the server and the verification code in the request field to judge whether the verification code is entered correctly. The user name and password are encapsulated into a user object, and then the login() method in the Service is called, the information object user input by the user is passed as parameters, and the interface and implementation class are created in the service layer, the method is defined, and then the interface and implementation are created in the dao layer. Class, rewrite the method, use the sql statement to operate the database, if the user name and password are correct, the user information object user of the user is returned, otherwise it is null, and the servlet layer is advanced layer by layer to judge the user login (judgment The return value is user or null).

5.2 Code Implementation

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE html>
<html lang="zh-CN">
<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>Admin login</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
        //Toggle verification code
        function refreshCode(){
            //1. Get the verification code image object
            var vcode = document.getElementById("vcode");

            //2. Set its src attribute and add a timestamp
            vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
        }
    </script>
</head>
<body>
<div class="container" style="width: 400px;">
    <h3 style="text-align: center;">Admin login</h3>
    <form action="${pageContext.request.contextPath}/loginServlet" method="post">
        <div class="form-group">
            <label for="user">username:</label>
            <input type="text" name="username" class="form-control" id="user" placeholder="please enter user name"/>
        </div>

        <div class="form-group">
            <label for="password">password:</label>
            <input type="password" name="password" class="form-control" id="password" placeholder="Please enter password"/>
        </div>

        <div class="form-inline">
            <label for="vcode">Verification code:</label>
            <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="please enter verification code" style="width: 120px;"/>
            <a href="javascript:refreshCode();">
                <img src="${pageContext.request.contextPath}/checkCodeServlet" title="Can't see clearly click refresh" id="vcode"/>
            </a>
        </div>
        <hr/>
        <div class="form-group" style="text-align: center;">
            <input class="btn btn btn-primary" type="submit" value="Log in">
        </div>
    </form>

    <!-- error message box -->
    <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" >
            <span>&times;</span>
        </button>
        <strong>${login_msg}</strong>
    </div>
</div>
</body>
</html>

CheckCodeServlet.java

Generation of verification code

package cn.itcast.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("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		//The server tells the browser not to cache
		response.setHeader("pragma","no-cache");
		response.setHeader("cache-control","no-cache");
		response.setHeader("expires","0");
		
		//Create a picture in memory with a length of 80 and a width of 30, with a black background by default
		//Parameter one: long
		//Parameter two: width
		//Parameter three: color
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		//get brushes
		Graphics g = image.getGraphics();
		//Set the brush color to gray
		g.setColor(Color.GRAY);
		//fill image
		g.fillRect(0,0, width,height);
		
		//Generate 4 random verification codes, 12Ey
		String checkCode = getCheckCode();
		//Put the verification code into the HttpSession
		request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
		
		//Set the brush color to yellow
		g.setColor(Color.YELLOW);
		//set font size
		g.setFont(new Font("black body",Font.BOLD,24));
		//Write a verification code to the picture
		g.drawString(checkCode,15,25);
		
		//Output the image in memory to the browser
		//Parameter one: image object
		//Parameter 2: The format of the picture, such as PNG,JPG,GIF
		//Parameter 3: Where to output the image
		ImageIO.write(image,"PNG",response.getOutputStream());
	}
	/**
	 * Generate 4 digit 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 random values ​​from 0 to size-1
			int index = r.nextInt(size);
			//Get the character subscripted by index in the base string
			char c = base.charAt(index);
			//Put c into StringBuffer
			sb.append(c);
		}
		return sb.toString();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request,response);
	}
}



LoginServlet.java

package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Set the encoding
        request.setCharacterEncoding("utf-8");

        //2. Get data
        //2.1 Get the user to fill in the verification code
        String verifycode = request.getParameter("verifycode");

        //3. Verification code verification
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//Make sure the verification code is one-time
        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //Incorrect verification code
            //Tips
            request.setAttribute("login_msg","Verification code error!");
            //Jump to login page
            request.getRequestDispatcher("/login.jsp").forward(request,response);

            return;
        }

        Map<String, String[]> map = request.getParameterMap();
        //4. Encapsulate the User object
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //5. Call the Service query
        UserService service = new UserServiceImpl();
        User loginUser = service.login(user);
        //6. Determine whether the login is successful
        if(loginUser != null){
            //login successful
            //save user to session
            session.setAttribute("user",loginUser);
            //Jump page
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else{
            //Login failed
            //Tips
            request.setAttribute("login_msg","wrong user name or password!");
            //Jump to login page
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }




    }

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

The next service layer and dao layer both query functions on it.

6. Add features

6.1 Analysis

6.2 Code Implementation

add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!-- HTML5 Documentation-->
<!DOCTYPE html>
<!-- language of the page -->
<html lang="zh-CN">
<head>
    <!-- specified character set -->
    <meta charset="utf-8">
    <!-- use Edge Rendering in the latest browsers -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: The web page can be automatically adapted according to the set width, and a container is virtualized inside the browser. The width of the container is the same as the width of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio, which is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 3 above meta Label*must*on top, anything else is*must*Follow it! -->
    <title>Add user</title>

    <!-- 1. import CSS the global style of -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery import, it is recommended to use 1.9 above version -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. import bootstrap of js document -->
    <script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <center><h3>add contact page</h3></center>
    <form action="${pageContext.request.contextPath}/addUserServlet" method="post">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Please type in your name">
        </div>

        <div class="form-group">
            <label>gender:</label>
            <input type="radio" name="gender" value="male" checked="checked"/>male
            <input type="radio" name="gender" value="Female"/>Female
        </div>

        <div class="form-group">
            <label for="age">age:</label>
            <input type="text" class="form-control" id="age" name="age" placeholder="Please enter age">
        </div>

        <div class="form-group">
            <label for="address">Nationality:</label>
            <select name="address" class="form-control" id="address">
                <option value="Shaanxi">Shaanxi</option>
                <option value="Beijing">Beijing</option>
                <option value="Shanghai">Shanghai</option>
            </select>
        </div>

        <div class="form-group">
            <label for="qq">QQ: </label>
            <input type="text" class="form-control" id="qq" name="qq" placeholder="please enter QQ Number"/>
        </div>

        <div class="form-group">
            <label for="email">Email: </label>
            <input type="text" class="form-control" id="email" name="email" placeholder="Please input the email address"/>
        </div>

        <div class="form-group" style="text-align: center">
            <input class="btn btn-primary" type="submit" value="submit" />
            <input class="btn btn-default" type="reset" value="reset" />
            <input class="btn btn-default" type="button" value="return" />
        </div>
    </form>
</div>
</body>
</html>

AddUserServlet.java

package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
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.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Set the encoding
        request.setCharacterEncoding("utf-8");
        //2. Get parameters
        Map<String, String[]> map = request.getParameterMap();
        //3. Encapsulating objects
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4. Call Service to save
        UserService service = new UserServiceImpl();
        service.addUser(user);

        //5. Jump to userListServlet
        response.sendRedirect(request.getContextPath()+"/userListServlet");
    }

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

 

 

Tags: Java MySQL Database

Posted by bhagwat on Tue, 13 Sep 2022 01:56:28 +0930