MVC是模型(Model)和视图(View)以及控制器(Controller)的简写,是一种将数据、界面显示和业务 逻辑进行分离的组织方式,这样在改进界面及用户交互时,不需要重新编写业务逻辑,从而提高了 代码的可维护性。
DAO对象。
V:主要负责数据收集 和 数据展现,通常由JSP文件完成。
C:主要负责流程控制 和 页面跳转,通常由Servlet完成。
原始的登录验证方法:
改进的登录验证方法:
这样实现了解耦,从而具备了更好的扩展性。
创建空工程,在工程中创建javaEE模块
配置中设置tomcat的部署
编写login界面
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - login</title>
</head>
<body>
<form action="loginServlet" method="post">
用户名:<input type="text" name="userName"><br>
密 码:<input type="text" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
编写servlet
LoginServlet
package com.example.login_demo.servlet;
import com.example.login_demo.pojo.User;
import com.example.login_demo.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取的用户名和密码
String userName = request.getParameter("userName");
System.out.println("获取的用户名:" + userName);
String password = request.getParameter("password");
System.out.println("获取的密码:" + password);
}
}
单元测试:
运行tomcat
访问登录界面,发送登录请求
数据准备,db_web数据库下准备t_user表
编写DbUtils,实现jdbc的封装
package com.example.login_demo.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DbUtils {
private static String jdbcName;
private static String dbUrl;
private static String dbUserName;
private static String dbPassword;
static {
jdbcName = "com.mysql.jdbc.Driver";
dbUrl = "jdbc:mysql://localhost:3306/db_web?useSSL=false";
dbUserName = "root";
dbPassword = "root";
try {
Class.forName(jdbcName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
return connection;
}
public static void closeResource(Connection connection, PreparedStatement preparedStatement) throws SQLException {
if (null != connection){
connection.close();
}
if (null != preparedStatement){
preparedStatement.close();
}
}
}
原始数据类型User
package com.example.login_demo.pojo;
public class User {
private int id;
private String userName;
private String password;
public User(String userName, String password) {
this.userName = userName;
this.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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
dao层直接操作数据库
UserDao接口
package com.example.login_demo.dao;
import com.example.login_demo.pojo.User;
public interface UserDao {
//查询用户
User userLogin(User user);
}
UserDaoImpl接口实现类
package com.example.login_demo.dao;
import com.example.login_demo.pojo.User;
import com.example.login_demo.utils.DbUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
@Override
public User userLogin(User user) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1、获取数据库连接
connection = DbUtils.getConnection();
//2、准备sql语句
String sql = "select * from t_user where userName = ? and password = ?";
//3、执行sql返回结果
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, user.getUserName());
preparedStatement.setString(2, user.getPassword());
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
User returnUser = new User(resultSet.getString("userName"), resultSet.getString("password"));
returnUser.setId(Integer.parseInt(resultSet.getString("id")));
return returnUser; //查找成功
}
}catch (SQLException e){
e.printStackTrace();
}finally {
//4、释放资源
try {
DbUtils.closeResource(connection, preparedStatement);
if (null != resultSet){
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;//查找失败
}
public static void main(String[] args) {
UserDao userDao = new UserDaoImpl();
User admin = userDao.userLogin(new User("admin", "12345"));
System.out.println("查找到的用户:" + admin);
}
}
单元测试:
执行UserDaoImpl中的测试代码
UserDaoFactory实现:简单的静态工厂实现UserDao的实例创建,实现创建和使用的解耦
package com.example.login_demo.factory;
import com.example.login_demo.dao.UserDao;
import com.example.login_demo.dao.UserDaoImpl;
public class UserDaoFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
service层实现dao层调用
package com.example.login_demo.service;
import com.example.login_demo.dao.UserDao;
import com.example.login_demo.factory.UserDaoFactory;
import com.example.login_demo.pojo.User;
public class UserService {
private UserDao userDao;
public UserService(){
this.userDao = UserDaoFactory.getUserDao();
}
public User userLoginService(User user){
return userDao.userLogin(user);
}
}
LoginServlet
package com.example.login_demo.servlet;
import com.example.login_demo.pojo.User;
import com.example.login_demo.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取的用户名和密码
String userName = request.getParameter("userName");
System.out.println("获取的用户名:" + userName);
String password = request.getParameter("password");
System.out.println("获取的密码:" + password);
//2、创建UserService类型的对象实现数据的校验功能
UserService userService = new UserService();
User user = userService.userLoginService(new User(userName, password));
if (null != user){
System.out.println("登录成功!");
}else {
System.out.println("登录失败!");
}
}
}
单元测试:
修改LoginServlet,当成功时,跳转到成功界面;当失败时,跳转回登录界面并显示账号或者密码错误
package com.example.login_demo.servlet;
import com.example.login_demo.pojo.User;
import com.example.login_demo.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取的用户名和密码
String userName = request.getParameter("userName");
System.out.println("获取的用户名:" + userName);
String password = request.getParameter("password");
System.out.println("获取的密码:" + password);
//2、创建UserService类型的对象实现数据的校验功能
UserService userService = new UserService();
User user = userService.userLoginService(new User(userName, password));
if (null != user){
System.out.println("登录成功!");
//登录成功的信息放入session对象实现多个请求共享
request.getSession().setAttribute("user", user);
//实现客户端跳转
response.sendRedirect("main.jsp");
}else {
System.out.println("登录失败,用户名或者密码错误!");
request.setAttribute("error", "登录失败,用户名或者密码错误!");
//实现服务器跳转,使用转发,共享request
RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
requestDispatcher.forward(request, response);
}
}
}
main.jsp
<%@ page import="com.example.login_demo.pojo.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页面</title>
</head>
<body>
<h1>登录成功!欢迎 <%=(User)session.getAttribute("user")%> !</h1>
</body>
</html>
login.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - login</title>
</head>
<body>
<form action="loginServlet" method="post">
用户名:<input type="text" name="userName"><br>
密 码:<input type="text" name="password"><br>
<span style="color: red"><%=request.getAttribute("error") == null?"":request.getAttribute("error")%></span><br>
<input type="submit" value="登录">
</form>
</body>
</html>
测试: