【JavaWeb】建立一个简单的servlet,前台后台实现jdbc链接[用户密码检查]

1.前台界面:

2.检查结果打印到屏幕:

3.简单的逻辑

1.前台form表单

2.servlet

3.DAO层

具体代码逻辑:

1.前台:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>表格颜色变化</title>
    <style>
        .div1{
            position: fixed;
            width: 100%;
            height: 100%;
        }
        .form1{
            position: absolute;
            top: 30%;
            left: 0;
            right: 0;
            margin: 0 auto;
            border: 1px solid grey ;
            width: 500px;
            padding: 5px;
        }
        table, th, td {
            border: 1px solid black;
        }
    </style>
</head>
<body>
<div class="div1">
    <form action="/WebTest1_war_exploded/userCheck" class="form1" method="post">
        <table id="myTable" align="center">
            <tr>
                <th>总体信息</th>
                <th>输入列表</th>
            </tr>
            <tr>
                <td>用户名</td>
                <td><input type="text" placeholder="请输入用户名" name="userName"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="text" placeholder="请输入密码" name="passWord"></td>
            </tr>
            <tr>
                <td></td>
                <td>&nbsp&nbsp&nbsp&nbsp&nbsp<input type="submit">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="reset"></td>
            </tr>
        </table>
    </form>
</div>



<script>
    const table = document.getElementById("myTable");
    const rows = table.getElementsByTagName("tr");
    for (let i = 1; i < rows.length; i++) {
        rows[i].addEventListener("mouseover", function() {
            this.style.backgroundColor = "blue";
        });
        rows[i].addEventListener("mouseout", function() {
            this.style.backgroundColor = "";
        });
    }
</script>

</body>
</html>

2.web.xml映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>UserCheck</servlet-name>
        <servlet-class>UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserCheck</servlet-name>
        <url-pattern>/userCheck</url-pattern>
    </servlet-mapping>
</web-app>

3.后台:

UserServlet.java



import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;


/**
 * @author djh
 * @create 2023-05-01  14:53
 */
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入UserServlet doPost方法");
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");

        Connection connection = UserDAO.jdbcConnection(req);
        boolean b = UserDAO.checkUser(connection, userName, passWord);
        if (b){
            System.out.println("用户存在");
        }else {
            System.out.println("用户不存在");
        }
        UserDAO.closeConn(connection);


    }
}

DAO层:

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author djh
 * @create 2023-05-01  15:42
 */
public class UserDAO {
    /**
     * 链接数据库
     * @return
     */
    public static Connection jdbcConnection(HttpServletRequest req){
        Properties properties = null;
        Connection connection = null;
        try {
            properties = new Properties();
            ServletContext servletContext = req.getServletContext();
            InputStream resourceAsStream = servletContext.getResourceAsStream("\\WEB-INF\\jdbc.properties");
            properties.load(resourceAsStream);
            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            System.out.println("数据连接失败");
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 检查是否存在
     * @param connection
     * @param username
     * @param password
     * @return
     */
    public static boolean checkUser(Connection connection,String username,String password){
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        PreparedStatement preparedStatement;
        ResultSet resultSet;
        boolean flag = false;
        try {

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                flag = true;
            }
            try {
                resultSet.close();
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return flag;

    }

    /**
     * 关闭链接
     * @param connection
     */
    public static void closeConn(Connection connection){
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}

4.配置文件 jdbc.properties

url=jdbc:mysql://localhost:3306/book
user=root
password=
driver=com.mysql.jdbc.Driver

注意点:jdbc.properties的路径问题,mysql的jar包,当你在servlet使用:

        Properties properties = new Properties();
        properties.load(new FileInputStream("jdbc.properties"));

会提示找不到路径的错误,因为在javaweb中可以使用以下方式代替:

//1.方法一 
InputStream fis =UserDAO.class.getClassLoader().getResourceAsStream(“WEB-INF\jdbc.properties”)

//2.方法二(要求UserDAO和jdbc.properties在同一目录下) 
InputStream fis =UserDAO.class.getResourceAsStream(“jdbc.properties”)

//3.方法三,对于Web工程也可以这样。 
//先获取ServletContext,然后 

InputStream in=context.getResourceAsStream(“/WEB-INF/classes/jdbc.properties”);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值