?实体类对象,对象名和数据库表名相同,成员变量和数据库的数据字段名相同
package bean;
public class User {
private int id;
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
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;
}
}
?这里的接口为了让后端和数据库操作分离
package dao;
import bean.User;
public interface UserDao {
/**
* 获取数据库中的登陆信息
* @param loginUser 后端给一个包含username和password的User
* @return 数据库返回null则说明登陆信息有误,否则登陆成功
*/
public User getLoginInformation(User loginUser);
}
?数据库的具体的操作逻辑,他继承了Druid数据库操作,也实现了上面的接口
package dao.impl;
import bean.User;
import dao.UserDao;
import util.DruidUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl extends DruidUtil implements UserDao {
User user = new User();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
@Override
public User getLoginInformation(User loginUser) {
try {
connection = getConnection();
preparedStatement = connection.prepareStatement("select * from user where username = ? and password = ?");
preparedStatement.setString(1,loginUser.getUsername());
preparedStatement.setString(2,loginUser.getPassword());
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
}
return user;
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
close(resultSet,preparedStatement,connection);
}
return null;
}
}
?
这里是一个接口,如果是前后端一起开发则直接根据接口,前端需要给后端什么数据,后端返回给前端的数据就确定了?
package service.impl;
import bean.User;
import dao.impl.UserDaoImpl;
import service.UserService;
public class UserServiceImpl implements UserService {
@Override
public User getUserDao(User loginUser) {
User loginInformation = new UserDaoImpl().getLoginInformation(loginUser);
return loginInformation;
}
}
package servlet;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 登陆验证的过滤器
*/
@WebFilter("/*")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
//强制转换
HttpServletRequest request1 = (HttpServletRequest) request;
//1判断是否是登陆相关的资源:获取与登陆相关的资源路径
String requestURI = request1.getRequestURI();
//2判断是否包含登陆相关资源路径
if (requestURI.contains("/login.jsp") || requestURI.contains("/UserServlet")){
//包含,证明用户就是想登陆,放行
chain.doFilter(request, response);
}else {
//不包含,需要验证用户是否登陆
//3从session中获取user
Object user = request1.getSession().getAttribute("user");
if (user != null){
//登陆了,放行
chain.doFilter(request, response);
}else {
//没有登陆,跳转登陆页面
request1.setAttribute("login_msg","您尚未登陆,请登录");
request1.getRequestDispatcher("/login.jsp").forward(request1,response);
}
}
}
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
}
package servlet;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class SessionListener implements HttpSessionListener {
/**
* session的创建
* @param httpSessionEvent
*/
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("session创建");
}
/**
* session的销毁
* @param httpSessionEvent
*/
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("session销毁");
}
}
package servlet;
import bean.User;
import com.mysql.cj.Session;
import service.impl.UserServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
UserServiceImpl userService = new UserServiceImpl();
User userDao = userService.getUserDao(loginUser);
if (userDao.getId() == 0){
//登陆失败,
//提示信息
request.setAttribute("login_msg","登陆失败,请检查账号或密码");
//转发到login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else {
//登陆成功,
//将用户存入session
session.setAttribute("user",userDao);
//跳转页面
response.sendRedirect(request.getContextPath()+"/success.jsp");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
测试类,测试一下,上面的数据库操作是否没有问题?
package test;
import bean.User;
import org.junit.Test;
import service.impl.UserServiceImpl;
public class UserTest {
@Test
public void userTest(){
User loginUser = new User();
loginUser.setUsername("superbaby");
loginUser.setPassword("123");
UserServiceImpl userService = new UserServiceImpl();
User userDao = userService.getUserDao(loginUser);
System.out.println(userDao);
//User{id=1, username='superbaby', password='123'}
}
}
德鲁伊的实现代码?
package util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DruidUtil {
private static DataSource dataSource;
static {
try {
//加载配置文件
Properties properties = new Properties();
properties.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
//获取DataSource
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**获取连接的方法
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 获取连接池的方法
*/
public static DataSource getDataSource(){
return dataSource;
}
/**
*DQL查询
* 释放资源
*/
public static void close(ResultSet rs, Statement stmt, Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* DML增删改
* 释放资源
*/
public static void close(Statement stmt, Connection conn){
DruidUtil.close(null,stmt,conn);
}
}
?德鲁伊的配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/day14
username=root
password=xxxx
#初始化连接数量
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
</body>
</html>
登陆页面?
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/UserServlet" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登陆">
</form>
<!-- 出错显示的信息框 -->
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span>×</span>
</button>
<strong>${login_msg}</strong>
</div>
</body>
</html>
?退出的逻辑实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
session.removeAttribute("user");
Object user = session.getAttribute("user");
if (user == null){
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
%>
</body>
</html>
?登陆成功页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%User user = (User) session.getAttribute("user");
response.getWriter().write("登陆成功!"+user.getUsername()+"欢迎您");%>
<br>
<a href="${pageContext.request.contextPath}/session.jsp">退出</a>
</body>
</html>
|