四层架构
创建项目![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c1e7d588b9b9c26abf4b011c054dc7b6.png)
将JDBCUtil工具类导入到,util包中。工具类代码如下:
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 操作数据库的工具类
* @author 樊**
*
*/
public class JDBCUtil {
private static final String DB_USER_NAME = "root";//数据库的用户名
private static final String DB_PASSWORD ="root";//数据库密码
private static final String DB_NAME = "user_management";//数据库名称
private static final String IP = "127.0.0.1";//127.0.0.1安装mysql数据库的服务器的ip地址
private static final String URL="jdbc:mysql://"+IP+":3306/"+DB_NAME;//mysql连接地址
//private static final String URL = "jdbc:mysql://"+IP+":3306/"+DB_NAME+"?serverTimezone=UTC";//mysql连接地址
private static Connection conn;//创建连接对象
private static Statement stmt;//执行sql语句的对象,执行命令的对象
private static ResultSet rs;//保存select之后查询结果的数据的对象
/**
* 获得连接对象
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private static Connection getCon() throws ClassNotFoundException, SQLException{
//加载mysql驱动
//Class.forName("com.mysql.cj.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver");
if(conn == null || conn.isClosed()){//防止多次赋值
conn = DriverManager.getConnection(URL, DB_USER_NAME, DB_PASSWORD);
}
return conn;
}
/**
* 获得Statement对象,用于执行sql语句
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private static Statement openStmt() throws ClassNotFoundException, SQLException{
stmt = getCon().createStatement();
return stmt;
}
/**
* 执行数据库的增(insert)、删(delete)、改(update)的操作
* @param sql
* @return
*/
public static int executeSQL(String sql){
int i = 0;
try {
i = openStmt().executeUpdate(sql);//执行sql语句
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭数据库相关对象
close();
}
return i;
}
/**
* 执行数据库查询(select)的操作
* @param sql
* @return
*/
public static ResultSet search(String sql){
try {
rs = openStmt().executeQuery(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
/**
* 关闭数据库的方法
*/
public static void close(){
try {
if(rs != null){
rs.close();//关闭ResultSet,顺序很重要不要错
}
if(stmt != null){
stmt.close();//关闭Statement
}
if(conn != null){
conn.close();//关闭Connection对象
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
然后开始部署自己的jar包,粘贴后自动部署,不需要bulidpath
开始创建html页面(显示登录名和密码)
更改编码集全部为UTF-8,要不然全是乱码。然后开始编写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>Insert title here</title>
</head>
<body>
<form action="UserController" method="get">
<h2>用户登录</h2>
用户名:<input name="username" type="text" size="12"><br/>
密码:<input name="pwd" type="password" size="12"><br/>
<input type="submit" value="登录">
<input type="reset" value="重置">
</form>
</body>
</html>
然后开始部署服务器:找到servers–右键
然后开始在浏览器中访问:http://127.0.0.1:8080/user_manager/login.jsp
但是此时登录无效果,因此我们下面要做的是,前端界面连接数据库,访问数据库中的内容,来验证登录。
就会生成密密麻麻的代码,但是我们只动doGet()方法里面的代码。
整体代码如下:
package controller;
import java.io.IOException;
import java.io.PrintWriter;
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 service.UserService;
/**
* Servlet implementation class UserController
*/
@WebServlet("/UserController")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UserController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
// System.out.println("成功的跳转到后台");
PrintWriter pw = response.getWriter();
String name=request.getParameter("username");
String pwd=request.getParameter("pwd");
// System.out.println(name);
// System.out.println(pwd);
UserService service = new UserService();
if(service.login(name, pwd)){
pw.print("<h1 style='color:red'>登录成功</h1>");
}else{
pw.print("<h1 style='color:green'>登录失败</h1>");
}
pw.flush();
pw.close();
}
/**
* @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);
}
}
创建实体
User类中代码如下:
package entity;
public class User {
private String id;
private String username;
private String pwd;
private String sex;
private int age;
private String phone;
private String email;
private String idcard;
private String addr;
public User(String id, String username, String pwd, String sex, int age, String phone, String email, String idcard,
String addr) {
super();
this.id = id;
this.username = username;
this.pwd = pwd;
this.sex = sex;
this.age = age;
this.phone = phone;
this.email = email;
this.idcard = idcard;
this.addr = addr;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", pwd=" + pwd + ", sex=" + sex + ", age=" + age
+ ", phone=" + phone + ", email=" + email + ", idcard=" + idcard + ", addr=" + addr + "]";
}
}
同样的方法在dao包中,创建一个。class文件。
UserDAO类中代码如下:
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import entity.User;
import util.JDBCUtil;
/**
* t_user表的数据库访问层
* @author 樊**
*
*/
public class UserDAO {
/**
* 通过用户名和密码查询用户
* @param name
* @param pwd
* @return
*/
public User selectUserByAuth(String name,String pwd){
User u = null;
String sql = "select * from t_user where username ='"+name+"' and pwd='"+pwd+"' ";
ResultSet rs = JDBCUtil.search(sql);
try {
while(rs.next()){
String id = rs.getString("id");
String username= rs.getString("username");
String pass= rs.getString("pwd");
String sex= rs.getString("sex");
int age= rs.getInt("age");
String phone= rs.getString("phone");
String email= rs.getString("email");
String idcard= rs.getString("idcard");
String addr= rs.getString("addr");
u = new User(id,username,pass,sex,age,phone,email,idcard,addr);
}
} catch (SQLException e) {
e.printStackTrace();
}
return u;
}
}
在service包中,创建一个class文件。
UserService中的代码如下:
package service;
import dao.UserDAO;
public class UserService {
private UserDAO dao = new UserDAO();
public boolean login(String name,String pwd){
boolean isOk = false;
if(dao.selectUserByAuth(name, pwd) != null){
isOk = true;
}
return isOk;
}
}
至此所有的代码写完了,就差运行了,坚持一下。
然后在浏览器中运行:http://127.0.0.1:8080/user_manager/login.jsp
-------------------------------我的天终于写完了---------------------------------
声明:我提前建立好了数据库