在该案例中,通过servlet实现了用户登录的功能。主要涉及前端页面请求数据,servlet程序处理请求,业务逻辑层调用相关的dao层,在数据库提取数据并return给service层进行验证,将验证结果经过servlet返还给前端页面,进行显示。
相关代码
创建admin数据表
CREATE TABLE `admin` (
`username` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`phone` VARCHAR(11) NOT NULL,
`Address` VARCHAR(20) NOT NULL,
PRIMARY KEY (`username`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb3
创建前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="/servlet_war_exploded/login" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
创建Admin.java实体类
package com.ws.servletProject.entity;
public class Admin {
private String username;
private String password;
private String phone;
private String Address;
public Admin() {
}
public Admin(String username, String password, String phone, String address) {
this.username = username;
this.password = password;
this.phone = phone;
Address = address;
}
@Override
public String toString() {
return "Admin{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", Address='" + Address + '\'' +
'}';
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
创建配置文件database.properties
通过该文件提供数据库的一些信息的配置,然后会通过DbUtils.java程序来加载该文件,连接数据库
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/practice?useUnicode=true&characterEncoding=utf-8&userSSL=false&serverTimezone=GMT%2B8
#url=jdbc:mysql://localhost:3306/girls
username=root
password=123
#initial connection Size
initialSize=10
#min idle connecton size
minIdle=5
#max active connection size
maxActive=20
#max wait time (5000 mil seconds)
maxWait=5000
创建工具类DbUtils.java
该程序主要通过创建数据库连接池(德鲁伊连接池),提供连接,事务控制以及释放连接资源
package com.ws.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;
@SuppressWarnings({"all"})
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();//在连接池中拿取一个connection
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);//提交事务时候释放连接,connection,statement,resoultset
}
}
//事务回滚
public static void rollback(){
Connection connection = null;
try {
connection = getConnection();
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeAll(connection,null,null);//提交事务时候释放连接,connection,statement,resultset
}
}
//释放资源
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();
}
}
}
创建DAO层相关代码
创建AdminDao.java接口
该接口规定操作数据库的一些方法
package com.ws.servletProject.dao;
import com.ws.servletProject.entity.Admin;
import java.util.List;
public interface AdminDao {
public int insert(Admin admin);
public int delete(String username);
public int update(Admin admin);
public Admin select(String username);
public List<Admin> selectAll();
}
创建AdminDaoImpl.java实现接口类
通过该程序可以对数据库实现具体的SQL语句操作,实质上也算是工具类
package com.ws.servletProject.dao.impl;
import com.ws.servletProject.dao.AdminDao;
import com.ws.servletProject.entity.Admin;
import com.ws.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> query = queryRunner.query(DbUtils.getConnection(), "select * from admin;", new BeanListHandler<Admin>(Admin.class));
return query;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
创建业务逻辑层相关代码(service)
创建AdminService.java接口
该程序主要是用来规定一些业务逻辑的方法
package com.ws.servletProject.service;
import com.ws.servletProject.entity.Admin;
import java.util.List;
public interface AdminService {
public Admin login(String username, String password);//通过servlet传入的 username,password 调用AdminDao对象进行数据提取,并且验证
public List<Admin> showAllAdmin();//展示所有用户的方法
}
创建AdminServiceImpl.java实现类
package com.ws.servletProject.service.impl;
import com.ws.servletProject.dao.AdminDao;
import com.ws.servletProject.dao.impl.AdminDaoImpl;
import com.ws.servletProject.entity.Admin;
import com.ws.servletProject.service.AdminService;
import com.ws.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;//创建一个Admin类,用来返回数据
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;
}
}
创建LoginServlet.java
package com.ws.servletProject.servlet;
import com.ws.servletProject.entity.Admin;
import com.ws.servletProject.service.AdminService;
import com.ws.servletProject.service.impl.AdminServiceImpl;
import com.ws.servlet_.HttpsServlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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 HttpsServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//接收参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//调用业务逻辑进行验证
AdminService adminService = new AdminServiceImpl();
Admin admin = adminService.login(username, password);
//验证用户是否存在之后,对返回的结果进行处理
//响应给客户端一个结果
PrintWriter writer = resp.getWriter();
if (admin != null){
writer.println("<html>");
writer.println("<head>");
writer.println("<meta charset='UTF-8'>");
writer.println("<title>结果</title>");
writer.println("</head>");
writer.println("<body>");
writer.println("<h1>登录成功!</h1>");
writer.println("</body>");
writer.println("</html>");
}else {
writer.println("<html>");
writer.println("<head>");
writer.println("<meta charset='UTF-8'>");
writer.println("<title>结果</title>");
writer.println("</head>");
writer.println("<body>");
writer.println("<h1>登录失败!</h1>");
writer.println("</body>");
writer.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}