JSP:MVC设计模式

1 基本概念

  MVC是模型(Model)、视图(View)以及控制器(Controller)的简写,是一种将数据、界面显示和业务逻辑进行分离的组织方式,这样在改进界面及用户交互时,不需要重新编写业务逻辑,从而提高了 代码的可维护性

  M:

    封装业务数据的JavaBean(Bean 或 Entity) 

      业务逻辑的JavaBean(Service)

      访问数据库的 DAO对象

 

  V:

    负责数据收集 和 数据展现,通常由JSP文件完成

 

  C:

    主要负责流程控制 和 页面跳转,通常由Servlet完成

 

 

2 基本模型

 

3 案例: 实现一个简单的登录功能

<1> 项目结构

 

 

//Use Xmind to illustrate their relationships  

 

 

 

 

<2> 代码

1. 视图层: login.jsp

<%@ page contentType="text/html;charset=utf-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>实现简单的登录功能</title>
</head>
<body>
<form action="login" method="post">
  用户名:<input type="text" name="userName"/><br/>&nbsp;&nbsp;&nbsp;&nbsp;码:<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>

 

2. 视图层:main.jsp (登录成功后的页面)

<%@ page import="com.lagou.demo03.bean.User" %>
<%
-- Created by IntelliJ IDEA. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>主页面</title> </head> <body> <h1>登录成功,欢迎<%= ((User)session.getAttribute("user")).getUserName() %>使用!</h1> </body> </html>

 

3. bean/User.java

package com.lagou.demo03.bean;

public class User {
    private int id;
    private String userName;
    private String password;

    public User() {
    }

    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{" +
                "userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

 

4. dao/UserDao.java

package com.lagou.demo03.dao;

import com.lagou.demo03.bean.User;

public interface UserDao {
    // 自定义抽象方法描述登录功能的实现
    public abstract User userLogin(User user);
}

 

5. dao/UserDaoImp.java

package com.lagou.demo03.dao;

import com.lagou.demo03.bean.User;
import com.lagou.demo03.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImp implements UserDao {
    @Override
    public User userLogin(User user) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 1.获取数据库连接
            connection = DbUtil.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 tu = new User(resultSet.getString("userName"), resultSet.getString("password"));
                return tu; // 表示查找成功
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4.释放相关的资源
            try {
                DbUtil.closeResource(connection, preparedStatement);
                if (null != resultSet) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return  null; // 表示查找失败
    }
}

 

6. factory/UserDaoFactory.java

package com.lagou.demo03.factory;

import com.lagou.demo03.bean.User;
import com.lagou.demo03.dao.UserDao;
import com.lagou.demo03.dao.UserDaoImp;

public class UserDaoFactory {

    /**
     * 通过静态工程方法模式来实现UserDao实现类对象的创建并返回
     * @return
     */
    public static UserDao getUserDao() {
        return new UserDaoImp();
    }
}

 

7. service/UserService.java

package com.lagou.demo03.service;

import com.lagou.demo03.bean.User;
import com.lagou.demo03.dao.UserDao;
import com.lagou.demo03.factory.UserDaoFactory;

public class UserService {
    private UserDao userDao;

    public UserService() {
        this.userDao = UserDaoFactory.getUserDao();
    }
    /**
     * 自定义成员方法,实现根据参数指定的User对象,来调用DAO层实现登录功能
     * @param user
     * @return
     */
    public User userLoginService(User user) {
        return userDao.userLogin(user);
    }
}

 

8.  servlet/LoginServlet.java

package com.lagou.demo03.servlet;

import com.lagou.demo03.bean.User;
import com.lagou.demo03.service.UserService;

import javax.servlet.RequestDispatcher;
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;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    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("登录失败,用户名或密码错误!");
            request.setAttribute("error", "登录失败,用户名或密码错误!");
            // 实现服务器跳转  共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request, response);
        } else {
            System.out.println("登录成功,欢迎使用!");
            // 将登录成功的用户信息放入session对象中实现多个请求共享
            request.getSession().setAttribute("user", user);
            // 实现客户端跳转
            response.sendRedirect("main.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

9.  test/UserService.java

package com.lagou.demo03.test;

import com.lagou.demo03.bean.User;
import com.lagou.demo03.dao.UserDao;
import com.lagou.demo03.dao.UserDaoImp;
import com.lagou.demo03.service.UserService;

public class UserServiceTest {

    public static void main(String[] args) {

        UserDao userDao = new UserDaoImp();
        UserService userService = new UserService();
        User admin = userService.userLoginService(new User("admin", "1234566"));
        System.out.println("找到的数据为:" + admin);
    }
}

 

10. util/DbUtil.java

package com.lagou.demo03.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DbUtil {
    private static String jdbcName;   // 用于描述驱动信息
    private static String dbUrl;      // 用于描述URL信息
    private static String dbUserName; // 用户描述用户名信息
    private static String dbPassword; // 用户描述密码信息

    // 进行静态成员的初始化操作
    static {
        jdbcName = "com.mysql.jdbc.Driver";
        dbUrl = "jdbc:mysql://localhost:3306/db_web";
        dbUserName = "root";
        dbPassword = "123456";
        try {
            Class.forName(jdbcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        return con;
    }

    /**
     * 关闭连接
     * @param con
     * @throws SQLException
     */
    public static void closeResource(Connection con, PreparedStatement psts) throws SQLException {
        if (null != con) {
            con.close();
        }
        if (null != psts) {
            psts.close();
        }
    }
}

 

4 练习题

 

 

 

 

 

 

 

posted @ 2021-09-16 14:40  Jasper2003  阅读(311)  评论(0编辑  收藏  举报