在程序设计中,我们把采用模型(Model)、视图(View)、视图(Controller)三层分离的设计方式称为MVC设计模式。
MVC设计模式由以下三部分组成:
模型(Model):对应的组件是JavaBean(Java类)。模型可以分为业务 逻辑和数据模型,它们代表应用程序的业务逻辑和状态。
视图(View):对应的组件是JSP或HTML文件。视图提供了可交互的客户界面,向客户显示模型数据。
控制器(Controller):对应的组件是Servlet。控制器响应客户的请求,根据客户的请求来操作模型,并且把模型的响应结果由视图展示给客户。
MVC设计模型的优点和好处
1、各司其职、互不干涉
如果某一层的需求发生了变化,就只需要更改相应层中的代码,而不会影响到其他层。
2、有利于在开发中的分工
由于按层把系统分开,那么就能更好地实现开发中的分工。网页设计人员可以开发JSP页面,对于业务熟悉的开发人员可以开发模型中相关业务处理的方法,而其他开发人员可开发控制器,以进行程序控制。
3、有利于组件的重用
如控制层可独立成一个通用的组件,视图层也可做成通用的操作界面。把显示与数据分离,这样就增加了各个模块的可重用性
原理图
对于dao层属于那一层,两种说法:
第一种说法:dao属于model,处理逻辑
第二种说法:dao属于数据库持久层,操作数据库
Servlet的MVC简单搭建
项目结构
1、controller层 LoginServlet代码
package com.javaweb.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.javaweb.dao.UserDao;
import com.javaweb.model.User;
import com.javaweb.util.DbUtil;
import com.mysql.jdbc.Connection;
/*controller层*/
public class LoginServlet extends HttpServlet {
DbUtil db = new DbUtil();
UserDao userDao = new UserDao();
/**
* 序列化操作的时候系统会把当前类的serialVersionUID写入到序列化文件中,
* 当反序列化时系统会去检测文件中的serialVersionUID,判断它是否与当前类的serialVersionUID一致,
* 如果一致就说明序列化类的版本与当前类版本是一样的,可以反序列化成功,否则失败。
*/
private static final long serialVersionUID = 1L;
@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 {
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection con = null;
try {
User user = new User(username, password);
con = db.getCon();
User currentUser = userDao.login(con, user);
if (currentUser == null) {
// System.out.println("no");
request.setAttribute("error", "用户名或者密码错误");
request.setAttribute("username", username);
request.setAttribute("password", password);
request.getRequestDispatcher("javaweb-mvc/login.jsp").forward(request, response);
} else {
// System.out.println("yes");
HttpSession session = request.getSession();
session.setAttribute("currentUser", currentUser);
response.sendRedirect("javaweb-mvc/success.jsp");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、Model层 User代码
package com.javaweb.model;
//model层,实体类
public class User {
private int id;
private String username;
private String password;
public User() {
super();
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User(int id, String username, String password) {
super();
this.id = id;
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;
}
}
3、数据持久层 UserDao代码
package com.javaweb.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.javaweb.model.User;
//数据持久层
public class UserDao {
public User login(Connection con,User user) throws SQLException{
User resultUser=null;
String sql="select * from user where name=? and pass=?";
PreparedStatement ps=con.prepareStatement(sql);//
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ResultSet rs=ps.executeQuery();
if(rs.next()){
resultUser=new User();
resultUser.setUsername(rs.getString("name"));
resultUser.setPassword(rs.getString("pass"));
}
return resultUser;
}
}
4、工具类代码
package com.javaweb.util;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
public class DbUtil {
private String url = "jdbc:mysql://localhost:3306/test";
private String user = "root";
private String password = "root";
private String driver = "com.mysql.jdbc.Driver";
public Connection getCon() throws Exception {
Class.forName(driver);
Connection con = (Connection) DriverManager.getConnection(url, user, password);
return con;
}
public static void getClose(Connection con) throws SQLException {
if (con != null) {
con.close();
}
}
}
5、Servlet代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>javaweb-mvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javaweb.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
6、视图层view代码
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
<table>
<tr>
<th colspan="2">登录界面</th>
</tr>
<tr>
<td>账号</td>
<td><input type="text" id="username" name="username" value="${username}"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" id="password" name="password" value="${password}"></td>
</tr>
<tr>
<td><input type="submit" value="提交"></td>
<td><font color="red">${error}</font></td>
</tr>
</table>
</form>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>登录成功</p>
当前用户:${currentUser.username}<br/>
当前密码:${currentUser.password}<br/>
</body>
</html>