前言
写Java Web项目时会发现,一个中型或者大型项目 随着代码的增多,会发现:代码既可以写在src目录下,也可以
写在WebContent目录下。src下可以建很多包 ,WebContent下可以建很多文件夹。
所以问题就来了:一个新的类 到底往哪个目录下的哪个文件夹里写?
此时解决办法就是:需要一个模式去规范,到底哪个类该往哪里写
MVC设计模式
下面先来看看什么是MVC:
M:Model(模型)。应用程序的核心功能,管理这个模块中庸的数据和值(bean, dao);用于状态改变(一般是业务逻辑)如保存数据、删除数据、查询数据等操作。
V:View(视图):提供模型的展示,管理模块如何显示给用户,他是应用程序的外观;(jsp/html)
C:Controller(控制器):对用户的输入做出反应,管理用户和视图的交互,是连接模型和视图的按钮。(servlet/service)
下面看看M、V、C三者的架构:
MVC用于将WEB(UI)层进行职责解耦。在Web MVC模式下,模型无法主动推数据给视图,如果用户想要视图更新,需要再发送一次请求(即请求-响应模型)
说明:MVC设计模式不属于23种设计模式
MVC-实例
下面来看一看根据MVC模式在IDEA中建目录的截图:
bean包:存放实体类
JavaBeans :是Java中一种特殊的类(换言之:JavaBean就是一个Java类).
一个Java类 ,满足以下要求,则可称为一个JavaBean
a. public修饰的类,提供public 无参构造方法
b. 所有属性 都是private
C. 提供getter和setter方法
从使用层面来看,JavaBean分为2大类:
a. 封装业务逻辑的JavaBean(eg:LoginDao.java 封装了登录逻辑)
b. 封装数据的JavaBean(实体类:eg:Student.java Vadio.java 。往往对应于数据库中的一张表,即数据库中有个Student表,项目中就有个Student.java类)
通常:表名=类名,列名=属性名
JavaBean是一个可以重复使用的组件,通过编写一个组件来实现某种通用功能,“一次编写、任何地方执行、任何地方重用”。
dao包:用于操作数据库,放数据库操作信息,需要定义操作数据库的接口
service包:是servlet和dao包的衔接转,在WEB项目中,servlet调用service,service调用dao实现服务器到数据库数据的CRUD操作。该包需要有接口和实现类。
util包:存放数据库连接池的工具包
web包:存放servlet类.
同时,需要添加相关依赖包,并配置好路径:
下面来看看本实例中bean包的代码:
student:
package com.yhp.bean;
/**
* Administrator
* mvcdemo
* 面向对象面向君 不负代码不负卿
*/
//实体类(javabean)
//类名=表名 列名=属性名
public class Student {
private int studentId;
private String studentNo;
private String stuName;
private int stuAge;
public Student() {
}
public Student(int studentId, String studentNo, String stuName, int stuAge) {
this.studentId = studentId;
this.studentNo = studentNo;
this.stuName = stuName;
this.stuAge = stuAge;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
}
dao包:对数据库的操作,
StudentDao接口:
package com.yhp.dao;
import com.yhp.bean.Student;
import java.util.List;
//定义操作数据库的方法
public interface StudentDao {
//查询所有的学生
public List<Student> getall();
//增加学生信息
boolean addStudent(Student student);
//通过学生编号studentno删除学生信息
boolean delStudentByNo(String num);
//修改学生信息
boolean updateStudent(Student student)throws NullPointerException;
}
对数据库数据CRUD的接口实现:
StudentDaoImpl:
package com.yhp.dao.impl;
import com.yhp.bean.Student;
import com.yhp.dao.StudentDao;
import com.yhp.util.DruidUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Administrator
* mvcdemo
* 面向对象面向君 不负代码不负卿
*/
public class StudentDaoImpl extends DruidUtil implements StudentDao {
/**
* 查询所有学生的信息
*
* @return
*/
@Override
public List<Student> getall() {
List list = new ArrayList();
Connection connection = null;
PreparedStatement prepstmt = null;
ResultSet resultSet = null;
try {
connection = getConnection();
String sql = "select * from student";
prepstmt = connection.prepareStatement(sql);
resultSet = prepstmt.executeQuery();
while (resultSet.next()) {
Student student = new Student();
student.setStudentId(resultSet.getInt("studentid"));
student.setStudentNo(resultSet.getString("studentno"));
student.setStuName(resultSet.getString("stuname"));
student.setStuAge(resultSet.getInt("stuage"));
list.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(connection, prepstmt, resultSet);
}
return list;
}
/**
* 增加学生信息
*/
@Override
public boolean addStudent(Student student) {
boolean flag = false;
Connection connection = null;
PreparedStatement prepstmt = null;
ResultSet resultSet = null;
try {
connection = DruidUtil.getConnection();
String sql = "insert into student(studentid,studentno,stuname,stuage)values(?,?,?,?)";
prepstmt = connection.prepareStatement(sql);
prepstmt.setInt(1, student.getStudentId());
prepstmt.setString(2, student.getStudentNo());
prepstmt.setString(3, student.getStuName());
prepstmt.setInt(4, student.getStuAge());
int n = prepstmt.executeUpdate();
if (n > 0) {
flag = true;
}
// List<Student> studentall = getall();
// studentall.add()
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(connection, prepstmt, resultSet);
}
return flag;
}
@Override
public boolean delStudentByNo(String num) {
boolean flag = false;
if (num == null) {
throw new IllegalArgumentException();
}
Connection conn = null;
PreparedStatement prepstmt = null;
ResultSet rs = null;
try {
conn = DruidUtil.getConnection();
prepstmt = conn.prepareStatement("delete from student where studentno=?");
prepstmt.setString(1, num);
prepstmt.executeUpdate();
int n = prepstmt.executeUpdate();
if (n > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(conn, prepstmt, rs);
}
return flag;
}
@Override
public boolean updateStudent(Student student) {
boolean flag = false;
if (student == null) {
throw new IllegalArgumentException();
}
if (student.getStudentNo() == null) {
throw new NullPointerException("The student's NO. can not be null");
}
Connection conn = null;
PreparedStatement prepstmt = null;
ResultSet rs = null;
try {
conn = DruidUtil.getConnection();
prepstmt = conn.prepareStatement("update student set studentid=?,studentno=?,stuname=?,stuage=? where id=?");
prepstmt.setInt(1, student.getStudentId());
prepstmt.setString(2, student.getStudentNo());
prepstmt.setString(3, student.getStuName());
prepstmt.setInt(4, student.getStuAge());
int n = prepstmt.executeUpdate();
if (n > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(conn, prepstmt, rs);
}
return flag;
}
}
service包中
StudentService接口:
package com.yhp.service;
import com.yhp.bean.Student;
import java.util.List;
//定义操作数据库的方法
public interface StudentService {
//查询所有的学生
public List<Student> getall();
//添加学生
boolean addStudent(Student student);
//通过学生编号studentno删除学生信息
boolean delStudentByNo(String num);
//修改学生信息
boolean updateStudent(Student student)throws NullPointerException;
}
接口实现,StudentServiceImpl:
package com.yhp.service.impl;
import com.yhp.bean.Student;
import com.yhp.dao.StudentDao;
import com.yhp.dao.impl.StudentDaoImpl;
import com.yhp.service.StudentService;
import java.util.List;
/**
* Administrator
* mvcdemo
* 主要调用dao中的 方法
*/
public class StudentServiceImpl implements StudentService {
private StudentDao dao=new StudentDaoImpl();
@Override
public List<Student> getall() {
return dao.getall();
}
@Override
public boolean addStudent(Student student) {
return dao.addStudent(student);
}
@Override
public boolean delStudentByNo(String num) {
return dao.delStudentByNo(num);
}
@Override
public boolean updateStudent(Student student) throws NullPointerException {
return dao.updateStudent(student);
}
}
数据库连接池-这里使用的是德鲁伊连接池
util包:DruidUtil定义了获取数据库连接的方法
package com.yhp.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import javax.xml.transform.Result;
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;
//德鲁伊德 连接池 工具类
/**
* 定义了获得连接的方法和 关闭资源的方法
*/
public class DruidUtil {
private static DataSource ds=null;
static{
InputStream is = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
Properties ppt = new Properties();
try {
ppt.load(is);
ds = DruidDataSourceFactory.createDataSource(ppt);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 用于从DBCP连接池中取出一个连接给用户
* @return DBCP连接池中的一个连接对象.
*/
public static Connection getConnection(){
try {
return ds.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
/**
* 用于释放连接 , 执行环境 , 结果集 等资源
* @param conn 要释放的连接资源
* @param state 要释放的执行环境资源
* @param result 要释放的结果集资源
*/
public static void close(Connection conn,Statement state,ResultSet result) {
if(result != null) {
try {
result.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(state != null) {
try {
state.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
在看服务器类代码之前,先来看看jsp页面。
<%--
Created by IntelliJ IDEA.
User: Administrator
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<br>
<h1>请在下方输入必要的-添加-信息</h1>
<form action="/addstudent" method="post">
<p>add-studentid:<input type="text" name="addstuid">
<p>add-studentno:<input type="text" name="addstuno">
<p>add-stuname:<input type="text" name="addstuname">
<p>add-stuage:<input type="text" name="addstuage"></p>
<input type="submit" value="添加"/>
</form>
</br>
<br>
<form action="/delstudent" method="post">
<p>
请输入要-删除-的学生编号del-studentno:<input type="text" name="delstuno">
</p>
<input type="submit" value="删除"/>
</form>
</br>
<h1>请在下方输入-待更新-的信息</h1>
<form action="/updstudent" method="post">
<p>updstudentid:<input type="text" name="updstuid">
<p>updstudentno:<input type="text" name="updstuno">
<p>updstuname:<input type="text" name="updstuname">
<p>updstuage:<input type="text" name="updstuage"></p>
<input type="submit" value="更新"/>
</form>
<h1><a href="/getallstudent">点这里-查询-全部students信息</a></h1>
</body>
</html>
主要是方便本例子的CRUD功能测试,对所有数据都采用表单post提交。
增加信息的AddStuServlet:
package com.yhp.web;
import com.yhp.bean.Student;
import com.yhp.service.StudentService;
import com.yhp.service.impl.StudentServiceImpl;
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;
import java.util.List;
/**
* @Author: Mind
* @Description:
* @Date Created in 2021-01-31 22:08
*/
@WebServlet(value = "/addstudent")
public class AddStuServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
// 1.接受参数
String stuid = req.getParameter("addstuid"); //getParameter()是客户端(B端)将请求参数值传给服务器(s端),永远返回字符串
String stuno = req.getParameter("addstuno");
String stuname = req.getParameter("addstuname");
String stuage = req.getParameter("addstuage");
//2.调取service方法
StudentService studentService=new StudentServiceImpl();
// List<Student> students = studentService.getall();
Student student = new Student();
try {
int intstuid = Integer.parseInt(stuid); //将string类型解析为int 类型
int intstuage = Integer.parseInt(stuage);
student.setStudentId(intstuid);
student.setStuAge(intstuage);
} catch (NumberFormatException e) {
e.printStackTrace();
}
student.setStudentNo(stuno);
student.setStuName(stuname);
studentService.addStudent(student);
// //3.跳转页面
req.setAttribute("addstuinfo",student);
req.getRequestDispatcher("addsuccess.jsp").forward(req,resp);
}
}
删除信息的DelStuServlet:
package com.yhp.web;
import com.yhp.service.StudentService;
import com.yhp.service.impl.StudentServiceImpl;
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;
/**
* @Author: Mind
* @Description:
* @Date Created in 2021-01-31 22:10
*/
@WebServlet(value = "/delstudent")
public class DelStuServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
//1.接收参数
String delstuno1 = req.getParameter("delstuno");
//2.调取service方法,删除
StudentService studentService=new StudentServiceImpl();
boolean flag =studentService.delStudentByNo(delstuno1);
//3.跳转页面
if(flag){
req.setAttribute("delflag", true);
req.getRequestDispatcher("delete.jsp").forward(req,resp);
}
}
}
改:UpdStuServlet
package com.yhp.web;
import com.yhp.bean.Student;
import com.yhp.service.StudentService;
import com.yhp.service.impl.StudentServiceImpl;
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;
/**
* @Author: Mind
* @Description:
* @Date Created in 2021-01-31 22:10
*/
@WebServlet(value = "/updstudent")
public class UpdStuServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
// 1.接受参数
String stuid = req.getParameter("updstuid"); //getParameter()是客户端(B端)将请求参数值传给服务器(s端),永远返回字符串
String stuno = req.getParameter("updstuno");
String stuname = req.getParameter("updstuname");
String stuage = req.getParameter("updstuage");
//2.调取service方法
StudentService studentService=new StudentServiceImpl();
// List<Student> students = studentService.getall();
Student student = new Student();
try {
int intstuid = Integer.parseInt(stuid); //将string类型解析为int 类型
int intstuage = Integer.parseInt(stuage);
student.setStudentId(intstuid);
student.setStuAge(intstuage);
} catch (NumberFormatException e) {
e.printStackTrace();
}
student.setStudentNo(stuno);
student.setStuName(stuname);
studentService.updateStudent(student);
// //3.跳转页面
req.setAttribute("updstuinfo",student);
req.getRequestDispatcher("updsuccess.jsp").forward(req,resp);
}
}
查:FindStuServlet
package com.yhp.web;
import com.yhp.bean.Student;
import com.yhp.service.StudentService;
import com.yhp.service.impl.StudentServiceImpl;
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;
import java.util.List;
@WebServlet(value = "/getallstudent")
public class FindStuServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受参数
//2.调取service方法
StudentService studentService=new StudentServiceImpl();
List<Student> students = studentService.getall();
//3.跳转页面
req.setAttribute("students",students);
req.getRequestDispatcher("show.jsp").forward(req,resp);
}
}
druid.properties文件:主要是对数据库查询表的设置,和对最大连接数的设置等。
运行效果图![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ad40013ceacd62d24c20af8d9c9417bd.png)
添加信息的功能测试截图:
查询功能的测试截图:
可以看到数据已经成功添加到数据库中啦。
总结
-
对于本例,使用到了MVC设计模式,HTML,JSP,JDBC,MySQL,Servlet等知识点。
-
在servlet类中,Service方法都可分为1.获取参数 2.调用service方法,3.跳转页面三个步骤。
-
获取参数通过getParameter()获取jsp页面上的参数,并该函数永远只返回string类型的参数。对于需要获取int类型的参数,需要用parseInt()解析。
-
在获取到jsp上传来的参数以后,通过…Servlet类调用service不同方法,,service调用dao来实现对数据库数据的不同操作。
-
具体的对数据操作的逻辑,是写在dao包里面的。
-
MVC可以让程序看起来更有逻辑。对于新手而言,可以遵从这样的固定模式即:先写bean包中实体类,再写dao接口,再写具体的实现类。
-
MVC设计模式,能很好的帮助我们梳理项目代码逻辑,应该熟练掌握创建每个包的作用。