[MVC+JDBC] 用戶登錄系統


用戶登錄系統

1. 搭建環境

在這裏插入圖片描述
在這裏插入圖片描述

2. 準備數據

CREATE DATABASE mvc;

USE mvc;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
	`id` DOUBLE ,
	`username` VARCHAR (96),
	`password` VARCHAR (96)
);

LOCK TABLES `user` WRITE;

INSERT INTO `user` (`id`, `username`, `password`) VALUES('1','admin','123');
INSERT INTO `user` (`id`, `username`, `password`) VALUES('2','reggie','abc');

UNLOCK TABLES;

在這裏插入圖片描述

3. 後端代碼

a. UserDao & UserDaoImpl

package com.regino.dao;

import com.regino.domian.User;

import java.util.List;

public interface UserDao {

    // Login
    public abstract User login(String username, String password);

    // Create
    public abstract boolean add(User user);

    // Retrieve all
    public abstract List<User> findAll();

    // Retrieve
    public abstract User findById(String id);

    // Update
    public abstract boolean update(User newUser);

    // Delete
    public abstract boolean delete(String id);
}
package com.regino.dao;

import com.regino.domian.User;
import com.regino.utils.JdbcUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private Connection connection = null;
    private PreparedStatement preparedStatement = null;
    private Statement statement = null;
    private ResultSet resultSet = null;

    @Override
    public User login(String username, String password) {
        User user = null;
        try {
            // 從連接池獲取連接
            connection = JdbcUtils.getConnection();
            String sql = "select * from user where username = ? and password = ?";
            // 獲取 SQL 預編譯執行對象
            preparedStatement = connection.prepareStatement(sql);
            // 設置實際參數
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            // 執行 SQL 並返回結果
            resultSet = preparedStatement.executeQuery();
            // 處理結果
            if (resultSet.next()) {
                // 獲取 id、用戶名、密碼
                int id = resultSet.getInt("id");
                username = resultSet.getString("username");
                password = resultSet.getString("password");
                user = new User(id, username, password);
            }
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            JdbcUtils.close(resultSet, preparedStatement, connection);
        }
        return null;
    }

    @Override
    public boolean add(User user) {
        boolean isAdded = false;
        try {
            // 從連接池獲取連接
            connection = JdbcUtils.getConnection();
            String sql = "insert into user values(?, ?, ?)";
            // 獲取 SQL 預編譯執行對象
            preparedStatement = connection.prepareStatement(sql);
            // 設置實際參數
            preparedStatement.setInt(1, user.getId());
            preparedStatement.setString(2, user.getUsername());
            preparedStatement.setString(3, user.getPassword());
            // 執行 SQL 並返回結果
            int i = preparedStatement.executeUpdate();
            // 處理結果
            if (i > 0) {
                isAdded = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            JdbcUtils.close(resultSet, preparedStatement, connection);
        }
        return isAdded;
    }

    @Override
    public List<User> findAll() {
        List<User> list = new ArrayList<User>();
        User user = null;
        try {
            // 從連接池獲取連接
            connection = JdbcUtils.getConnection();
            String sql = "select * from user";
            // 獲取 SQL 執行對象(不需要 Statement 的子接口 PreparedStatement 來提升性能和安全性)
            statement = connection.createStatement();
            // 執行 SQL 並返回結果
            resultSet = statement.executeQuery(sql);
            // 處理結果
            while (resultSet.next()) {
                // 獲取數據
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                user = new User(id, username, password);
                list.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            JdbcUtils.close(resultSet, statement, connection);
        }
        return list;
    }

    @Override
    public User findById(String id) {
        User user = null;
        try {
            // 從連接池獲取連接
            connection = JdbcUtils.getConnection();
            String sql = "select * from user where id = ?";
            // 獲取 SQL 預編譯執行對象
            preparedStatement = connection.prepareStatement(sql);
            // 設置實際參數
            preparedStatement.setString(1, id);
            // 執行 SQL 並返回結果
            resultSet = preparedStatement.executeQuery();
            // 處理結果
            if (resultSet.next()) {
                // 獲取數據
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                user = new User(Integer.valueOf(id), username, password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            JdbcUtils.close(resultSet, preparedStatement, connection);
        }
        return user;
    }

    @Override
    public boolean update(User user) {
        boolean isUpdated = false;
        try {
            // 從連接池獲取連接
            connection = JdbcUtils.getConnection();
            String sql = "update user set username = ?, password = ? where id = ?";
            // 獲取 SQL 預編譯執行對象
            preparedStatement = connection.prepareStatement(sql);
            // 設置實際參數
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setInt(3, user.getId());
            // 執行 SQL 並返回結果
            int i = preparedStatement.executeUpdate();
            // 處理結果
            if (i > 0) {
                isUpdated = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            JdbcUtils.close(resultSet, preparedStatement, connection);
        }
        return isUpdated;
    }

    @Override
    public boolean delete(String id) {
        boolean isDeleted = false;
        try {
            // 從連接池獲取連接
            connection = JdbcUtils.getConnection();
            String sql = "delete from user where id = ?";
            // 獲取 SQL 預編譯執行對象
            preparedStatement = connection.prepareStatement(sql);
            // 設置實際參數
            preparedStatement.setString(1, id);
            // 執行 SQL 並返回結果
            int i = preparedStatement.executeUpdate();
            // 處理結果
            if (i > 0) {
                isDeleted = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 釋放資源
            JdbcUtils.close(resultSet, preparedStatement, connection);
        }
        return isDeleted;
    }
}
  • 在調用 preparedStatement 與 statement 的 executeQuery() 和 executeUpdate() 方法時,statement 需要傳遞 SQL 語句作爲參數,而 preparedStatement 不需要,因爲 prepareStatement 在創建時就已經獲得了 SQL 語句(connection.prepareStatement(sql);),而 statement 則沒有(connection.createStatement();)。

b. 實體類

package com.regino.domian;

import java.io.Serializable;

public class User implements Serializable {

    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

	// 省略set/get/toString ...

c. UserService & UserServiceImpl

package com.regino.service;

import com.regino.domian.User;

import java.util.List;

public interface UserService {

    // Login
    public abstract User login(String username, String password);

    // Create
    public abstract boolean add(User user);

    // Retrieve all
    public abstract List<User> findAll();

    // Retrieve
    public abstract User findById(String id);

    // Update
    public abstract boolean update(User newUser);

    // Delete
    public abstract boolean delete(String id);
}
package com.regino.service;

import com.regino.dao.UserDaoImpl;
import com.regino.domian.User;

import java.util.List;

public class UserServiceImpl implements UserService {

    private UserDaoImpl userDaoImpl = new UserDaoImpl();

    @Override
    public User login(String username, String password) {
        return userDaoImpl.login(username, password);
    }

    @Override
    public boolean add(User user) {
        return userDaoImpl.add(user);
    }

    @Override
    public List<User> findAll() {
        return userDaoImpl.findAll();
    }

    @Override
    public User findById(String id) {
        return userDaoImpl.findById(id);
    }

    @Override
    public boolean update(User newUser) {
        return userDaoImpl.update(newUser);
    }

    @Override
    public boolean delete(String id) {
        return userDaoImpl.delete(id);
    }
}

d. JdbcUtils

package com.regino.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

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

public class JdbcUtils {

	private static DataSource dataSource = null;

	// 初始化連接池 Druid 對象,一個項目只有一個 static{}
	static {
		try {
			// 通過類加載器讀取src目錄下配置文件,獲取io流
			InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
			// 創建Properties對象
			Properties properties = new Properties();
			properties.load(is);
			// Druid連接池工廠對象,初始化連接池
			dataSource = DruidDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 提供獲取連接池對象靜態方法
	public static DataSource getDataSource() {
		return dataSource;
	}

	// 提供連接對象的靜態方法
	public static Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}

	// 提供釋放資源的靜態方法(歸還 Connection)
	public static void close(ResultSet resultSet, Statement statement, Connection connection) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

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

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

	// 重載關閉方法
	public static void close(Statement statement, Connection connection) {
		close(null, statement, connection);
	}
}

e. CharacterEncondingFilter

package com.regino.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//該字符串過濾器要解決全局亂碼問題
/*
亂碼的分類:
     1. 請求亂碼(即HTML頁面提交表單數據---Servlet通過getParameter()方法獲取參數的時候是否亂碼)
            get請求:沒有
            post請求:有亂碼
     2. 響應亂碼
            response.getWrite().write("好人"); //向瀏覽器輸出數據亂碼
            不管任何請求方式都會亂碼的。
 */
//配置過濾路徑
@WebFilter("/*")
public class CharacterEncondingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 強制類型轉換 (目的是爲了使用 HttpServletRequest 的 getMethod 方法)
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 解決 Response 響應亂碼問題
        response.setContentType("text/html;charset=utf-8");

        //3. 獲取客戶請求方式,如果是 post 請求方式我們需要解決獲取請求參數亂碼問題
        String method = request.getMethod();
        if("post".equalsIgnoreCase(method)){
            request.setCharacterEncoding("utf-8");
        }

        //解決完畢亂碼之後記得要放行
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }
}

f. CheckServlet

package com.regino.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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CheckServlet", urlPatterns = "/checkServlet")
public class CheckServlet extends HttpServlet {

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

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        int width = 120;
        int height = 40;
        //首先創建一個畫布
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //創建當前畫布的畫筆
        Graphics gh = bufferedImage.getGraphics();

        //設置背景色顏色
        gh.setColor(Color.white);
        //繪畫 背景
        gh.fillRect(0, 0, width, height);

        //設置邊框的顏色
        gh.setColor(Color.red);
        //繪畫邊框
        gh.drawRect(0, 0, width - 1, height - 1);

        //定義一個random
        Random rd = new Random();
        //在畫布上繪畫驗證碼的內容
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //定義一個變量保存驗證碼
        String checkStr = "";
        for (int i = 1; i < 5; i++) {

            //設置字體
            Font font = new Font("宋體", Font.PLAIN, 28);
            gh.setFont(font);
            //設置字體的顏色
            gh.setColor(new Color(rd.nextInt(255), rd.nextInt(255), rd.nextInt(255)));
            //獲取需要繪畫的文字
            String s = str.charAt(rd.nextInt(str.length())) + "";
            //將字體畫到畫布上去
            gh.drawString(s, 10 + (i - 1) * 30, 30);
            checkStr += s;
        }

        //繪畫障礙物
        for (int i = 1; i < 10; i++) {
            //設置線條的顏色
            gh.setColor(new Color(rd.nextInt(255), rd.nextInt(255), rd.nextInt(255)));
            //繪畫線條
            gh.drawLine(rd.nextInt(width), rd.nextInt(height), rd.nextInt(width), rd.nextInt(height));
        }
        //將圖片保存到session中
        HttpSession session = request.getSession();
        session.setAttribute("checkImg", checkStr);
        //將圖片輸出到前端
        /*
         * 第一個參數:需要輸出的畫布
         * 第二個參數:格式
         * 第三個參數:輸出流
         */
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }
}

g. UserServlet

package com.regino.web.servlet;

import com.regino.domian.User;
import com.regino.service.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.List;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private UserServiceImpl userServiceImpl = new UserServiceImpl();

    // 請求入口
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 判斷請求 action
        String action = request.getParameter("action");

        if (action.equals("login")) {
            this.login(request, response);
        } else if (action.equals("add")) {
            this.add(request, response);
        } else if (action.equals("list")) {
            this.findAll(request, response);
        } else if (action.equals("findById")) {
            this.findById(request, response);
        } else if (action.equals("update")) {
            this.update(request, response);
        } else if (action.equals("delete")) {
            this.delete(request, response);
        }
    }

    // Login
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 獲取請求參數
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkStr = request.getParameter("checkStr");
        String checkStrServer = (String) request.getSession().getAttribute("checkImg");
        if (checkStr.equalsIgnoreCase(checkStrServer)) {
            // 調用 service
            User user = userServiceImpl.login(username, password);
            if (user == null) {
                // 登陸失敗
                request.setAttribute("msg", "用戶名或密碼錯誤!");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                // 登陸成功
                request.getSession().setAttribute("loginUser", user);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        } else {
            request.setAttribute("msg", "驗證碼錯誤!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    // Create
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            // 接收請求參數 map
            Map<String, String[]> parameterMap = request.getParameterMap();
            // 快速封裝 User 實體
            User newUser = new User();
            BeanUtils.populate(newUser, parameterMap);  //如果該實體類沒有action數據的時候,beanUtils不會給user封裝的。
            // 調用 service 添加 User
            boolean isAdded = userServiceImpl.add(newUser);
            if (isAdded) {
                System.out.println("刪除成功");
            } else {
                System.out.println("刪除失敗");
            }
            // 重定向到 Retrieve all
            response.sendRedirect(request.getContextPath() + "/user?action=list");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    // Retrieve all
    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 調用 service 查詢
        List<User> list = userServiceImpl.findAll();
        // 將 List 存儲到 Request 域
        request.setAttribute("list", list);
        // 轉發到 list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }

    // Retrieve
    protected void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 接收請求參數 id
        String id = request.getParameter("id");
        // 調用 service,根據 id 查詢
        User user = userServiceImpl.findById(id);
        // 將 user 存儲到 request 域
        request.setAttribute("user", user);
        // 轉發到 update.jsp
        request.getRequestDispatcher("/update.jsp").forward(request, response);
    }

    // Update
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            // 接收請求參數
            Map<String, String[]> parameterMap = request.getParameterMap();
            // 快速封裝到 User 實體
            User newUser = new User();
            BeanUtils.populate(newUser, parameterMap);
            // 調用 service 更新
            boolean isUpdated = userServiceImpl.update(newUser);
            if (isUpdated) {
                System.out.println("更新成功");
            } else {
                System.out.println("更新失敗");
            }
            // 重定向到 Retrieve all
            response.sendRedirect(request.getContextPath() + "/user?action=list");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    // Delete
    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 接收請求參數 ID
        String id = request.getParameter("id");
        // 調用 service 刪除
        boolean isDeleted = userServiceImpl.delete(id);
        if (isDeleted) {
            System.out.println("刪除成功");
        } else {
            System.out.println("刪除失敗");
        }
        // 重定向到 Retrieve all(再請求轉發至 list.jsp)
        response.sendRedirect(request.getContextPath() + "/user?action=list");
    }
}

4. 前端代碼

a. 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="en">
<head>
    <style type="text/css">
        ol li {
            list-style: none;
        }

        .list-inline {
            text-align: center;
        }
    </style>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<div class="container-fluid">
    <div class="col-md-3" style="padding-top:20px">
        <ol class="list-inline">
            <c:choose>
                <c:when test="${loginUser!=null}">
                    <li>歡迎,${loginUser.username}</li>
                    <a href="${pageContext.request.contextPath}/user?action=list" style="text-decoration:none;font-size:33px">用戶列表</a>
                </c:when>
                <c:otherwise>
                    <%--"./login.jsp" 也可以--%>
                    <li><a href="login.jsp" style="text-decoration:none;font-size:33px">用戶登陸</a></li>
                </c:otherwise>
            </c:choose>
        </ol>
    </div>
</div>
</body>
</html>

b. login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>會員登錄</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
    <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script src="js/bootstrap.min.js" type="text/javascript"></script>
    <!-- 引入自定義css文件 style.css -->
    <link rel="stylesheet" href="css/style.css" type="text/css"/>

    <style>
        body {
            margin-top: 20px;
            margin: 0 auto;
        }

        .carousel-inner .item img {
            width: 100%;
            height: 300px;
        }

        .container .row div {
            /* position:relative;
                         float:left; */

        }

        font {
            color: #666;
            font-size: 22px;
            font-weight: normal;
            padding-right: 17px;
        }
    </style>
</head>
<body>

<!-- 引入header.jsp -->


<div class="container"
     style="width: 100%; height: 460px; background: #FF2C4C url('images/login.gif') no-repeat;">
    <div class="row">
        <div class="col-md-7">
            <!--<img src="./image/login.jpg" width="500" height="330" alt="會員登錄" title="會員登錄">-->
        </div>

        <div class="col-md-5">
            <div
                    style="width: 440px; border: 1px solid #E7E7E7; padding: 20px 0 20px 30px; border-radius: 5px; margin-top: 60px; background: #fff;">
                <font>會員登錄</font>USER LOGIN
                <div style="color: red;">${msg}</div>
                <%--由於 get 方式提交參數是需要拼接在 url 地址上的,那麼是表單的 url 後面本身就已經有參數就會被覆蓋。
                 post 方式不會在 url 地址上重新去拼接參數,所以 action 沒有被覆蓋。--%>
                <form class="form-horizontal" action="${pageContext.request.contextPath}/user" method="post">
                    <div class="form-group">
                        <input type="hidden" name="action" value="login"/>
                        <label for="username" class="col-sm-2 control-label">用戶名</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="username" name="username"
                                   placeholder="請輸入用戶名">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword" class="col-sm-2 control-label">密碼</label>
                        <div class="col-sm-6">
                            <input type="password" class="form-control" id="inputPassword" name="password"
                                   placeholder="請輸入密碼">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword2" class="col-sm-2 control-label">驗證碼</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="inputPassword2" name="checkStr"
                                   placeholder="請輸入驗證碼">
                        </div>
                        <div class="col-sm-3">
                            <img src="${pageContext.request.contextPath}/checkServlet"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <div class="checkbox">
                                <label> <input type="checkbox"> 自動登錄
                                </label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label>
                                <input type="checkbox"> 記住用戶名
                            </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <input type="submit" width="100" value="登錄" name="submit"
                                   style="background: url('./images/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;">
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 引入footer.jsp -->

</body>
</html>

c. list.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">
    <!-- 使用Edge最新的瀏覽器的渲染方式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport視口:網頁可以根據設置的寬度自動進行適配,在瀏覽器的內部虛擬一個容器,容器的寬度與設備的寬度相同。
    width: 默認寬度與設備的寬度相同
    initial-scale: 初始的縮放比,爲1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <title>用戶信息管理系統</title>

    <!-- 1. 導入CSS的全局樣式 -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery導入,建議使用1.9以上的版本 -->
    <script src="js/jquery-1.11.3.min.js"></script>
    <!-- 3. 導入bootstrap的js文件 -->
    <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">用戶信息列表</h3>
    <table border="1" class="table table-bordered table-hover">
        <tr class="success">
            <th>編號</th>
            <th>用戶名</th>
            <th>密碼</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${list}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.password}</td>
                <td>
                    <a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/user?action=findById&id=${user.id}">修改</a>
                    &nbsp;<a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/user?action=delete&id=${user.id}">刪除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <h5 style="text-align: center"><a class="btn btn-default btn-sm" href="./add.jsp">添加</a></h5>
</div>
</body>
</html>

d. update.jsp

<%@ page language="java" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>修改用戶</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">
    <div class="container">
        <h3 style="text-align: center;">修改用戶</h3>
        <form action="${pageContext.request.contextPath}/user?action=update" method="post">
            <div class="form-group">
                <label for="id">編號:</label>
                <input type="text" class="form-control" id="id" readonly="readonly" name="id" value="${user.id}">
            </div>

            <div class="form-group">
                <label for="username">用戶名:</label>
                <input type="text" class="form-control" id="username" name="username" placeholder="請輸入用戶名"/>
            </div>

            <div class="form-group">
                <label for="password">密碼:</label>
                <input type="text" class="form-control" id="password" name="password" placeholder="請輸入密碼"/>
            </div>

            <div class="form-group" style="text-align: center">
                <input class="btn btn-primary" type="submit" value="提交"/>
                <input class="btn btn-default" type="reset" value="重置"/>
                <input class="btn btn-default" type="button" value="返回"/>
            </div>
        </form>
    </div>
</div>
</body>
</html>

e. add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 網頁使用的語言 -->
<html lang="zh-CN">
<head>
    <!-- 指定字符集 -->
    <meta charset="utf-8">
    <!-- 使用Edge最新的瀏覽器的渲染方式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport視口:網頁可以根據設置的寬度自動進行適配,在瀏覽器的內部虛擬一個容器,容器的寬度與設備的寬度相同。
    width: 默認寬度與設備的寬度相同
    initial-scale: 初始的縮放比,爲1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <title>添加用戶</title>

    <!-- 1. 導入CSS的全局樣式 -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery導入,建議使用1.9以上的版本 -->
    <script src="js/jquery-2.1.0.min.js"></script>
    <!-- 3. 導入bootstrap的js文件 -->
    <script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <center><h3>添加聯繫人頁面</h3></center>
    <form action="${pageContext.request.contextPath}/user?action=add" method="post">
        <div class="form-group">
            <label for="username">編號:</label>
            <input type="text" class="form-control" id="id" name="id" placeholder="請輸入編號">
        </div>

        <div class="form-group">
            <label for="username">用戶名:</label>
            <input type="text" class="form-control" id="username" name="username" placeholder="請輸入用戶名">
        </div>

        <div class="form-group">
            <label for="password">密碼:</label>
            <input type="text" class="form-control" id="password" name="password" placeholder="請輸入密碼">
        </div>

        <div class="form-group" style="text-align: center">
            <input class="btn btn-primary" type="submit" value="提交" />
            <input class="btn btn-default" type="reset" value="重置" />
            <input class="btn btn-default" type="button" value="返回" />
        </div>
    </form>
</div>
</body>
</html>

5. 配置文件

a. druid.properties

# 數據庫基本四項
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mvc
username=root
password=root

# 初始化個數
initialSize=5
# 最大連接個數
maxActive=10
# 等待時間,毫秒
maxWait=3000

b. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
           version="3.0">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

6. 測試

a. 登錄演示

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

b. 用戶列表

在這裏插入圖片描述

c. 修改用戶

在這裏插入圖片描述
在這裏插入圖片描述

d. 添加用戶

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

e. 刪除用戶

在這裏插入圖片描述
在這裏插入圖片描述


原文鏈接:https://qwert.blog.csdn.net/article/details/106108118

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章