Maven项目JavaWeb网站开发之登录功能五分钟快速上手项目(IDEA-Java)

 上期已经讲了Maven项目的创建以及基础配置,本期五步骤实现简单的登录功能

前端部分:

步骤一:Web目录下创建index.html登陆界面,元素:账号输入框、密码输入框、登录按钮

<label for="name">账号</label><input type="text" name="name" id="name"><br>
<label for="password">密码</label><input type="password" name="password" id="password">
<button type="button" id="btnLogin" onclick="userLogin()">登录</button>

步骤二: 引入jQuery.js,写一个ajax往后端传数据

<script src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function userLogin(){
    var name = $('#name').val();
    var password = $('#password').val();
    console.log(name,password);
    $.ajax({
        type:'post',
        url:'/userLogin',
        data:{"name":name,"password":password},
        dataType:'text',
        success:function (res){
            if (res === "success"){
                window.alert("登陆成功,即将跳转到用户主页");
                setTimeout(function (){
                    window.location.href='sy_user.html';
                },1500);
            }else{
                window.alert("账号或密码错误,请重新登录!")
            }
        }
    })
}
</script>

 后端部分:

步骤一:在entity实体包下写User类(将数据库表实体化)

public class User {
    private String name;
    private String password;

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

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

}

步骤二:在utils包写数据库连接类DBUtils

public class DBUtils {
//    驱动类链接
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
//    URL地址
    private static final String URL = "jdbc:mysql://localhost:3306/music";
//    数据库用户名
    private static final String USER = "root";
//    数据库密码
    private static final String PASSWORD = "719214";
//  加载驱动,static语句块,在类加载时只执行一次
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
//  数据库连接类
    private Connection conn;
//    编译SQL
    private Statement st;
//    预编译SQL,使用占位符?,?
    private PreparedStatement ps;

//    获取数据库连接对象
//调用Connection的setAutoCommit(false)可以取消自动提交事务
    private void openConnection(){
        try {
            conn = DriverManager.getConnection(URL,USER,PASSWORD);
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //    向数据库发送要执行的SQL语句
    public Statement getStatement(){
        openConnection();
        try {
            st = conn.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return st;
    }

    public PreparedStatement getPreparedStatement(String sql){
        openConnection();
        try {
            ps = conn.prepareStatement(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return ps;
    }

步骤三:在Dao包写UserDAO接口(注意是接口)

public interface UserDAO {
//    用户登录
    User userLogin(String name,String password) throws SQLException;
}

步骤四:在Dao下创建DaoImpl继承包,写UserDAOImpl类

public class UserDAOImpl implements UserDAO {
    @Override
    public User userLogin(String name, String password) throws SQLException {
        DBUtils db = new DBUtils();
        String sql = "select * from user where name=? and password=?";
        PreparedStatement ps = db.getPreparedStatement(sql);
        ps.setString(1,name);
        ps.setString(2,password);
        ResultSet rs = ps.executeQuery();
        User user = new User();
        while (rs.next()){
            user.setName(rs.getString("name"));
            user.setPassword(rs.getString("password"));
            return user;
        }
        return null;
    }
}

步骤五:在servlet包下写userLogin类

@WebServlet("/userLogin")
public class userLogin extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        User user;
        try {
            user = userService.userLogin(name,password);
            if (user!=null){
                HttpSession session = req.getSession();
                session.setAttribute("user",user);
                resp.getWriter().write("success");
            }else{
                resp.getWriter().write("fail");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

上期讲了Maven项目的创建tomcat部署好之后,启动服务器,在数据库中首先输入好测试数据,输入账号和密码点击登录按钮完成跳转即成功实现登录功能,下期讲注册功能,谢谢观看