java mvc 案例_JavaWeb(五):MVC案例

MVC是Model-View-Controller的简称,即模型-视图-控制器。

MVC是一种设计模式,它把应用程序分成三个核心模块:模型、视图、控制器,它们各自处理自己的任务。模型是应用程序的主体部分,模型表示业务数据和业务逻辑。一个模型能为多个视图提供数据。由于应用于模型的代码只需写一次就可以被多个视图重用,所以提高了代码的可重用性。视图是用户看到并与之交互的界面,作用如下:视图向用户显示相关的数据,接受用户的输入,不进行任何实际的业务处理。控制器接受用户的输入并调用模型和视图去完成用户的需求。控制器接收请求并决定调用哪个模型组件去处理请求,然后决定调用哪个视图来显示模型处理返回的数据。

3b0cdf312087ba6d5145ad07f07354e3.png

把逻辑部分、访问数据库的部分放在Servlet,显示部分放在JSP页面。

发请求到服务器,服务器调用Servlet,Servlet做一个控制器,根据请求的情况取去调用Java类,Java类完成业务逻辑和访问数据库的操作,根据POJO的返回结果转向JSP,JSP进行显示,显示的时候可以使用一些标准标签库。

POJO里包含处理逻辑、业务逻辑,并去访问数据库。

Servlet根据不同的返回结果转向不同的JSP页面,转向的方式包括重定向和转发。

model:

e6d7c5995db6d150e01d28d4ca794b7b.png

controller:Servlet

view:JSP

一、查询和删除

1.1 查询

需求

点击超链接后在页面显示所有学生考试信息

数据库

字段

flowId

type

idCard

examCard

studentName

location

grade

数据表截图

7a60218f8bd956d40d9a90f089d1e008.png

Bean

public classStudent {privateInteger flowId;private inttype;privateString idCard;privateString examCard;privateString studentName;privateString location;private intgrade;publicInteger getFlowId() {returnflowId;

}public voidsetFlowId(Integer flowId) {this.flowId =flowId;

}public intgetType() {returntype;

}public void setType(inttype) {this.type =type;

}publicString getIdCard() {returnidCard;

}public voidsetIdCard(String idCard) {this.idCard =idCard;

}publicString getExamCard() {returnexamCard;

}public voidsetExamCard(String examCard) {this.examCard =examCard;

}publicString getStudentName() {returnstudentName;

}public voidsetStudentName(String studentName) {this.studentName =studentName;

}publicString getLocation() {returnlocation;

}public voidsetLocation(String location) {this.location =location;

}public intgetGrade() {returngrade;

}public void setGrade(intgrade) {this.grade =grade;

}public Student(Integer flowId, int type, String idCard, String examCard, String studentName, String location, intgrade) {this.flowId =flowId;this.type =type;this.idCard =idCard;this.examCard =examCard;this.studentName =studentName;this.location =location;this.grade =grade;

}//反射需要一个无参的构造器

publicStudent(){

}

}

流程

3ecaecd7578aa1897051b0d941a95411.png

页面

超链接的页面 c.jsp

Title

List All Student

c.jsp截图

2789eb4a7705d8e8414ca25854e48933.png

转发的页面 students.jsp

User: JieZhao

Date:2019/8/13Time:13:38To changethis template use File | Settings |File Templates.--%>

Title

stus = (List)request.getAttribute("students");%>

FlowId Type IdCard ExamCard StudentName Location Grade

for(Student student: stus){%>

代码

Dao

public classStudentDao {public ListgetAll(){

List students = new ArrayList<>();

Connection connection= null;

PreparedStatement preparedStatement= null;

ResultSet resultSet= null;try{

String driverClass= "com.mysql.jdbc.Driver";

String url= "jdbc:mysql:///aidata";

String user= "root";

String passward= "root";

Class.forName(driverClass);

connection=DriverManager.getConnection(url, user, passward);

String sql= "SELECT flow_id, type, id_card, exam_card, sutdent_name, Location, Grade FROM examstudent";

preparedStatement=connection.prepareStatement(sql);

resultSet=preparedStatement.executeQuery();while(resultSet.next()){int flowId = resultSet.getInt(1);int type = resultSet.getInt(2);

String idCard= resultSet.getString(3);

String examCard= resultSet.getString(4);

String studentName= resultSet.getString(5);

String location= resultSet.getString(6);int grade = resultSet.getInt(7);

Student student= newStudent(flowId, type, idCard, examCard, studentName, location, grade);

students.add(student);

}

}catch(Exception e){

e.printStackTrace();

}finally{try{if(resultSet != null){

resultSet.close();

}

}catch(SQLException e){

e.printStackTrace();

}try{if(preparedStatement != null){

preparedStatement.close();

}

}catch(SQLException e){

e.printStackTrace();

}try{if(connection != null){

connection.close();

}

}catch(SQLException e){

e.printStackTrace();

}

}returnstudents;

}

}

Servlet

public class ListAllStudentsServlet extendsHttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsIOException, ServletException {

StudentDao studentDao= newStudentDao();

List students =studentDao.getAll();

request.setAttribute("students", students); //结果添加到students属性里,存到request里

request.getRequestDispatcher("/students.jsp").forward(request, response);//将request转发到students.jsp页面

}

}

配置web.xml

listAllStudent

com.aidata.mvc.ListAllStudentsServlet

listAllStudent

/listAllStudent

1.2 删除

students.jsp里添加删除按钮

Dao里添加删除方法

public voiddeleteByFlowId(Integer flowId){

List students = new ArrayList<>();

Connection connection= null;

PreparedStatement preparedStatement= null;try{

String driverClass= "com.mysql.jdbc.Driver";

String url= "jdbc:mysql:///aidata";

String user= "root";

String password= "root";

Class.forName(driverClass);

connection=DriverManager.getConnection(url, user, password);

String sql= "DELETE FROM examstudent WHERE flow_id = ?";

preparedStatement=connection.prepareStatement(sql);

preparedStatement.setInt(1, flowId);

preparedStatement.executeUpdate();

}catch(Exception e){

e.printStackTrace();

}finally{try{if(preparedStatement != null){

preparedStatement.close();

}

}catch(SQLException e){

e.printStackTrace();

}try{if(connection != null){

connection.close();

}

}catch(SQLException e){

e.printStackTrace();

}

}

}

Servlet添加删除的Servlet

public class DeleteStudentServlet extendsHttpServlet {protected voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsIOException, ServletException {

String flowId= request.getParameter("flowId");

StudentDao studentDao= newStudentDao();

studentDao.deleteByFlowId(Integer.parseInt(flowId));

List students =studentDao.getAll();

request.setAttribute("students", students);

request.getRequestDispatcher("/listAllStudent").forward(request, response); // 重定向到servlet

}

}

配置web.xml

deleteStudent

com.aidata.mvc.DeleteStudentServlet

deleteStudent

/deleteStudent

二、案例

2.1 架构分析

下面开始做一个小案例:利用MVC模式对数据进行增删改查

没有业务层,直接由Servlet调用DAO,所以也没有事务操作,可以在DAO中直接获取Connection对象

采取MVC设计模式

使用到的技术:

MVC设计模式:JSP、Servlet

数据库使用MySQL

连接数据库使用C3P0数据库连接池

JDBC工具采用DBUtils

页面的提示操作采用jQuery

技术难点:

多个请求如何使用一个Servlet

模糊查询

在创建或修改的情况下,验证用户名已经被使用,并给出提示信息

051b48372faccb483adf4eae49f970dd.png

2.2 DAO层

DAO 模式

DAO (DataAccessobjects 数据存取对象)是指位于业务逻辑和持久化数据之间实现对持久化数据的访问。通俗来讲,就是将数据库操作都封装起来。

对外提供相应的接口

在面向对象设计过程中,有一些"套路”用于解决特定问题称为模式。

DAO 模式提供了访问关系型数据库系统所需操作的接口,将数据访问和业务逻辑分离对上层提供面向对象的数据访问接口。

从以上 DAO 模式使用可以看出,DAO 模式的优势就在于它实现了两次隔离。

1、隔离了数据访问代码和业务逻辑代码。业务逻辑代码直接调用DAO方法即可,完全感觉不到数据库表的存在。分工明确,数据访问层代码变化不影响业务逻辑代码,这符合单一职能原则,降低了藕合性,提高了可复用性。

2、隔离了不同数据库实现。采用面向接口编程,如果底层数据库变化,如由 MySQL 变成 Oracle 只要增加 DAO 接口的新实现类即可,原有 MySQ 实现不用修改。这符合 "开-闭" 原则。该原则降低了代码的藕合性,提高了代码扩展性和系统的可移植性。

一个典型的DAO 模式主要由以下几部分组成。

1、DAO接口: 把对数据库的所有操作定义成抽象方法,可以提供多种实现。

2、DAO 实现类: 针对不同数据库给出DAO接口定义方法的具体实现。

3、实体类:用于存放与传输对象数据。

4、数据库连接和关闭工具类: 避免了数据库连接和关闭代码的重复使用,方便修改。

数据库

建立数据表

Create tablecustomers(

idint primary keyauto_increment,

namevarchar(30) not null unique,

addressvarchar(30),

phonevarchar(30)

);

# 为 name 字段添加唯一约束alter table customers add constraint name_uk unique(name);

数据表截图

1a3931fdd92536724ffbe69349b621d7.png

C3P0数据源

使用eclipse

添加c3p0的jar包和mysql驱动的jar包到根目录的lib目录中

添加commons-dbutils-1.3.jar到根目录的lib目录中

添加c3p0的配置文件到src目录

c3p0-config.xml

root

root

com.mysql.jdbc.Driver

jdbc:mysql:///aidata

5

5

5

10

20

5

实体类

Customer.java

packagecom.aidata.mvcapp.domain;public classCustomer {privateInteger id;privateString name;privateString address;privateString phone;publicInteger getId() {returnid;

}public voidsetId(Integer id) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicString getAddress() {returnaddress;

}public voidsetAddress(String address) {this.address =address;

}publicString getPhone() {returnphone;

}public voidsetPhone(String phone) {this.phone =phone;

}

@OverridepublicString toString() {return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", phone=" + phone + "]";

}

}

数据库连接和关闭工具类

JdbcUtils.java

packagecom.aidata.mvcapp.db;importjava.sql.Connection;importjava.sql.SQLException;importjavax.sql.DataSource;importcom.mchange.v2.c3p0.ComboPooledDataSource;/*** @ClassName JdbcUtils

* @Description JDBC操作的工具类

*@authorJZ

* @Date

*@version1.0.0*/

public classJdbcUtils {/*** @Description 释放连接

*@paramconnection*/

public static voidreleaseConnection(Connection connection) {try{if (connection != null) {

connection.close();

}

}catch(Exception e) {//TODO: handle exception

}

}private static DataSource dataSource = null;//数据源只能创建一次,所以用static

static{

dataSource= ne

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值