signed

QiShunwang

“诚信为本、客户至上”

JDBC项目更新第二版_4.26课堂

2021/4/26 23:02:11   来源:

1.JDBCUtils

package cn.edu.xit.Utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtils {
	// 得到连接对象
	public static Connection getConnection() throws SQLException,ClassNotFoundException{
		// 加载驱动
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost/127.0.0.1:3306/student";
		String username = "root";
		String password = "swj93980";
		Connection con = DriverManager.getConnection(url,username,password);
		System.out.println("success1");
		return con;
	}
	public static void main(String[] args){
		JDBCUtils j = new JDBCUtils(); // j得到con
		if(j != null){
			System.out.println("success");
		}
	}
}

2.User

package cn.edu.xit.domain;

public class User {
	private int id;
	private String username;
	private String password;
	private String jobs;
	private String phone;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	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 String getJobs() {
		return jobs;
	}
	public void setJobs(String jobs) {
		this.jobs = jobs;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
}

3.UserDao

package cn.edu.xit.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.edu.xit.Utils.JDBCUtils;
import cn.edu.xit.domain.User;

public class UserDao {
	// 通过用户名和密码查找用户
	public User findUserByUsernameandPwd(String username,String password){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			// 获得数据连接
			conn = JDBCUtils.getConnection();
			// 发生SQL语句
			String sql = "select * form user where username = ? and password = ?";
			// 获得Statement对象
			stmt = conn.prepareStatement(sql);
			// 第一个问号为username
			stmt.setString(1, username);
			stmt.setString(2, password);
			rs = stmt.executeQuery();
			// 处理结果集
			if(rs.next()){
				// 如果不为空
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setJobs(rs.getString("jobs"));
				user.setPhone(rs.getString("phone"));
				return user;
			}
			// 如果没有就返回空对象
			return null;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				rs.close();
				stmt.close();
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		return null;
	}
	public List<User> findAll(){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		ArrayList<User> list = new ArrayList<User>();
		try{
			// 获得数据的连接
			conn = JDBCUtils.getConnection();
			// 获得statement对象
			stmt = conn.createStatement();
			// 发送SQL语句
			String sql = "select * from user";
			// 执行
			rs = stmt.executeQuery(sql);
			//处理结果集
			while(rs.next()){
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setJobs(rs.getString("jobs"));
				user.setPhone(rs.getString("phone"));
				list.add(user);
			}
			return list;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				rs.close();
				stmt.close();
				conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return null;
	}
}

4.LoginServlet

package cn.edu.xit.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 cn.edu.xit.dao.UserDao;
import cn.edu.xit.domain.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8"); // 对post提交有效
		response.setContentType("text/html;charset=utf-8");
		String username = request.getParameter("username"); // 从login.jsp中得到username
		String password = request.getParameter("password");
		UserDao userdao = new UserDao();
		try{
			User user = userdao.findUserByUsernameandPwd(username, password);
			if(user != null){
				// 把user对象保存到session对象,
				request.getSession().setAttribute("user", user);
				response.sendRedirect("FindUserServlet");
			}
			else{
				response.sendRedirect("login.jsp");
			}
		}catch(Exception e){
			e.printStackTrace();
			response.sendRedirect("login.jsp");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

5.FindUserServlet

package cn.edu.xit.servlet;

import java.io.IOException;
import java.util.List;

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 cn.edu.xit.dao.UserDao;
import cn.edu.xit.domain.User;

/**
 * Servlet implementation class FindUserServlet
 */
@WebServlet("/FindUserServlet")
public class FindUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		UserDao userdao = new UserDao();
		List<User> users = null;
		try{
			users = userdao.findAll();
		}catch(Exception e){
			e.printStackTrace();
		}
		request.setAttribute("user", users);
		request.getRequestDispatcher("list.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

6.login

<%@ 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>Insert title here</title>
</head>
<body>
<h1>用户登录</h1>
<form action = "LoginServlet" method = "post">
   username:<input type = "text" name = "username"><br/><br/>
   password:<input type = "password" name = "password"><br/><br/>
   <input type = "submit" value = "login">
</form>
</body>
</html>

7.list

<%@page import="cn.edu.xit.domain.User"%>
<%@page import="java.util.List"%>
<%@ 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>Insert title here</title>
</head>
<body>

<!-- 显示用户的所有信息页面 -->
<table border = "1px">
<tr>
<th>学号</th>
<th>姓名</th>
<th>密码</th>
<th>工作</th>
<th>电话</th>
<th>操作</th>
</tr>
<%
List<User> users = (List<User>)request.getAttribute("user");
for(User user:users){
  %>
  <tr>
  <td><%=user.getId() %></td>
  <td><%=user.getUsername() %></td>
  <td><%=user.getPassword() %></td>
  <td><%=user.getJobs() %></td>
  <td><%=user.getPhone() %></td>
  <td><a href = "DeleteServelt?id=<%=user.getId()%>" onclick = "return confirm('确定删除')"></a></td>
  </tr>
<%
}
%>
</table>
</body>
</html>