JavaWeb作业

自己建立JavaWeb项目,连接MySQL数据库。

1.做一登陆界面,能够查询数据库验证用户名和密码;

2.登录成功后,显示用户表里所有用户数据。

注:数据库和表以及数据自己建立。

1.下载jar包

       1、下载地址:MySQL :: Download MySQL Connector/J (Archived Versions)下载5.0版本的jar包

 

          2、其次还有一个jar包是在tomcat中找的在lib包下的servlet。

 

 2.导入jar包

     1、将下载好的jar包导入该项目的WebContent\WEB-INF\lib下

 

 2、将两个jar包添加到运行环境中。

 

 3.代码

      1、在src下新建dao包,然后新建UserDao.java内容如下

     

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import entity.User;
import util.DBUtil;

public class UserDao {
    
    //数据库连接对象
    public User login(String username,String password) {
       User u=null;
       Connection connection =null;
       PreparedStatement pstmt=null;
       ResultSet resultSet=null;

      //赋值
      try {
         connection=DBUtil.getCon();
          //静态sql语句
         String sql = "select * from user where username=? and password=?";//在表里搜索内容
         pstmt = (PreparedStatement) connection.prepareStatement(sql);
         pstmt.setString(1, username);
         pstmt.setString(2, password);
         resultSet = pstmt.executeQuery();
         if(resultSet.next()){
            u=new User();
            u.setName(resultSet.getString("username"));
            u.setPassword(resultSet.getString("password"));
            System.out.println("登录成功!");
         }else{
            System.out.println("用户名或者密码错误!");
         }
      } catch (SQLException e) {
        e.printStackTrace();
      }finally {
         // DBUtil.close(pstmt, connection);
      }
      return u;

    }

    public boolean addUser(User user) {
        Connection connection = null;
        PreparedStatement psmt = null;
        try {
             connection = DBUtil.getCon();

             String sql  ="insert into user(username,password)";
             psmt = (PreparedStatement) connection.prepareStatement(sql);

             //运用实体对象进行参数赋值
             
             psmt.setString(1, user.getName());
             psmt.setString(2,user.getPassword());
             psmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }finally {
            //DBUtil.close(psmt, connection);
        }
        return true;
    }
    
}

    2、新建entity包下新建User.java类

package entity;

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;
    }

}

     3、新建servlet包,下新建LoginServlet.java

package servlet;

import java.io.IOException;
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 dao.UserDao;
import entity.User;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

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

        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String account = request.getParameter("username");
        String psd = request.getParameter("password");

        HttpSession sessionzxl = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserDao userDAO = new UserDao();
        User user = userDAO.login(username, password);
        if (user != null) {
            sessionzxl.setAttribute("user", user);
            request.getRequestDispatcher("success.jsp").forward(request, response);
            ;
        } else {
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

}

       4、新建util包,新建DBUtil.java

package util;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class DBUtil {
    public static final String driver = "com.mysql.jdbc.Driver";
    public static final String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useOldAliasMetadataBehavior=true";
    public static final String username = "root";
    public static final String password = "1234";
    public static Connection con = null;

    static {
        try {
            Class.forName(driver);// 得到DriverManager,在下面建立连接时使用
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getCon() {

        if (con == null) {
            try {
                con = (Connection) DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;
    }

    // 关闭的方法
    public static void close(Statement statement, Connection conn) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

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

    public static void main(String args[]) {
        new DBUtil().getCon();
    }

}

4.html代码

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录界面</title>
<style type="text/css">
</style>

</head>
<body>
    <div style="text-align: center; margin-top: 120px">
        <form action="LoginServlet" method="post">
            <table style="margin-left: 40%">
                <h1 width="200" scrolldelay="250">用户登录</h1>
                <tr>
                    <td>登录名:</td>
                    <td><input name="username" type="text" size="21"></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input name="password" type="password" size="21"></td>
                </tr>
            </table>
            <input type="submit" value="登录"> <input type="reset"
                value="重置">
        </form>
        <br>
    </div>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆失败界面</title>
</head>
<body>
    登陆失败!
    <br/>    
    <a href="login.jsp">请重新登录</a>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import = "java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="entity.User"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录成功界面</title>
</head>
<body>
    <%
    User user = (User) session.getAttribute("user");
    %>
    "登陆成功!";
    <br> 用户名:<%=user.getName()%>
    <br> 密码:<%=user.getPassword()%>
    <br>
    <h3>所有用户信息</h3>
<table border="1">
    <tr>
        <th>用户名</th>
        <th>密码</th>
    </tr>
<%
    //加载、注册数据库驱动程序
    Class.forName("com.mysql.jdbc.Driver");
    
    //数据库连接字符串
    String url = "jdbc:mysql://localhost:3306/test";
    //用户名
    String username = "root";
    //密码
    String password = "1234";
    //数据库连接
    Connection conn = DriverManager.getConnection(url, username, password);
        
    //构造sql语句
    String sql = "select * from user";
    //获取数据库操作对象(PreparedStatement对象)
    PreparedStatement pstmt = conn.prepareStatement(sql);
    
    ResultSet rs = pstmt.executeQuery();
    
    //循环前准备变量
    String uname = null;
    String upassword = null;
    while(rs.next()){
        uname = rs.getString("username");
        upassword = rs.getString("password");
        %>
    <tr>
        <td><%= uname %></td>
        <th><%= upassword%></th>
    </tr>
    
    
<% 
    }
    //释放对象
    if(pstmt != null){
        pstmt.close();
    }
    if(conn != null){
        pstmt.close();
    }
    if(rs != null){
        rs.close();
    }
%>
</table>

</body>
</html>

其中碰到的问题,注意数据库的名字是不是正确的,数据库的密码是不是对的

 

 一定要保持一致

 

 

 

 运行结果

 

 

 

 

 

posted @ 2022-05-07 21:46  冷漠的孩子  阅读(141)  评论(0)    收藏  举报