综合案例(Servlet JDBC)
- 要求:实现登录功能、展示所有用户功能
- 以下仅展示关键代码
1.数据库
代码语言:javascript复制CREATE TABLE admin(
username VARCHAR(20) PRIMARY KEY,
PASSWORD VARCHAR(20) NOT NULL,
phone varchar(11) NOT NULL,
Address varchar(20) NOT NULL
)CHARSET=utf8;
INSERT INTO admin(username,PASSWORD,phone,address)
VALUES('gavin','123456','12345678901','北京市昌平区');
INSERT INTO admin(username,PASSWORD,phone,address)
VALUES('aaron','123456','12345678901','北京市昌平区');
2.DBUtils
代码语言:javascript复制package com.qf.servletProject.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DbUtils {
private static DruidDataSource ds;
private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
static {
Properties properties = new Properties();
InputStream inputStream = DbUtils.class.getResourceAsStream("/database.properties");
try {
properties.load(inputStream);
ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = THREAD_LOCAL.get();
try {
if (connection == null) {
connection = ds.getConnection();
THREAD_LOCAL.set(connection);
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void begin() {
Connection connection = null;
try {
connection = getConnection();
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void commit() {
Connection connection = null;
try {
connection = getConnection();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(connection, null, null);
}
}
public static void rollback() {
Connection connection = null;
try {
connection = getConnection();
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(connection, null, null);
}
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
THREAD_LOCAL.remove();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.AdminDaoImpl
代码语言:javascript复制package com.qf.servletProject.dao.impl;
import com.qf.servletProject.dao.AdminDao;
import com.qf.servletProject.entity.Admin;
import com.qf.servletProject.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class AdminDaoImpl implements AdminDao {
private QueryRunner queryRunner = new QueryRunner();
@Override
public int insert(Admin admin) {
return 0;
}
@Override
public int delete(String username) {
return 0;
}
@Override
public int update(Admin admin) {
return 0;
}
@Override
public Admin select(String username) {
try {
Admin admin = queryRunner.query(DbUtils.getConnection(),"select * from admin where username=?;",new BeanHandler<Admin>(Admin.class),username);
return admin;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Admin> selectAll() {
try {
List<Admin> admins = queryRunner.query(DbUtils.getConnection(),"select * from admin",new BeanListHandler<Admin>(Admin.class));
return admins;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
4.AdminServiceImpl
代码语言:javascript复制package com.qf.servletProject.service.impl;
import com.qf.servletProject.dao.AdminDao;
import com.qf.servletProject.dao.impl.AdminDaoImpl;
import com.qf.servletProject.entity.Admin;
import com.qf.servletProject.service.AdminService;
import com.qf.servletProject.utils.DbUtils;
import java.util.List;
public class AdminServiceImpl implements AdminService {
private AdminDao adminDao = new AdminDaoImpl();
@Override
public Admin login(String username, String password) {
Admin result = null;
try {
DbUtils.begin();
Admin admin = adminDao.select(username);
if(admin!=null){
if(admin.getPassword().equals(password)){
result = admin;
}
}
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return result;
}
@Override
public List<Admin> showAllAdmin() {
List<Admin> admins = null;
try {
DbUtils.begin();
admins = adminDao.selectAll();
DbUtils.commit();
} catch (Exception e) {
DbUtils.rollback();
e.printStackTrace();
}
return admins;
}
}
5.HTML页面代码
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="/WebProject_war_exploded/login" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="登录" />
</form>
</body>
</html>
6.LoginServlet
代码语言:javascript复制package com.qf.servletProject.servlet;
import com.qf.servletProject.entity.Admin;
import com.qf.servletProject.service.AdminService;
import com.qf.servletProject.service.impl.AdminServiceImpl;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1.收参
String username = req.getParameter("username");
String password = req.getParameter("password");
//2.调用业务逻辑
AdminService adminService = new AdminServiceImpl();
Admin admin = adminService.login(username,password);
//3.处理结果
PrintWriter printWriter = resp.getWriter();
if(admin!=null){
//响应给客户端一个结果页面,显示登录成功
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>登录成功!</h1>");
printWriter.println("</body>");
printWriter.println("</html>");
}else{
//响应给客户端一个结果页面,显示登录失败!
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>登录失败!</h1>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
7.ShowAllAdminServlet
代码语言:javascript复制package com.qf.servletProject.servlet;
import com.qf.servletProject.entity.Admin;
import com.qf.servletProject.service.AdminService;
import com.qf.servletProject.service.impl.AdminServiceImpl;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(value = "/showall")
public class ShowAllAdminServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
AdminService adminService = new AdminServiceImpl();
List<Admin> adminList = adminService.showAllAdmin();
PrintWriter printWriter = resp.getWriter();
if(adminList!=null){
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>显示所有</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<table border='1'>");
printWriter.println(" <tr>");
printWriter.println(" <td>username</td>");
printWriter.println(" <td>password</td>");
printWriter.println(" <td>phone</td>");
printWriter.println(" <td>address</td>");
printWriter.println(" </tr>");
for(Admin admin : adminList){
printWriter.println(" <tr>");
printWriter.println(" <td>" admin.getUsername() "</td>");
printWriter.println(" <td>" admin.getPassword() "</td>");
printWriter.println(" <td>" admin.getPhone() "</td>");
printWriter.println(" <td>" admin.getAddress() "</td>");
printWriter.println(" </tr>");
}
printWriter.println("</table>");
printWriter.println("</body>");
printWriter.println("</html>");
}else{
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>显示所有</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h3>当前没有用户!</h3>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}