spring创建项目xml文件的配置以及使用spring+c3p0连接池+jsp、servlet+elementUI+Vue简单实现学生管理系统的增删改查
spring创建项目xml文件的配置以及使用spring+c3p0连接池+jsp、servlet简单实现学生管理系统的增删改查
1- spring容器的简单介绍
Spring: 中文意思为春天 给整个软件行业带来了春天
2002年 Road Jahnson首次推出了Spring框架雏形interface21框架
2004年3月24 Srping以interface21框架为基础 经过重新设计 发布了1.0正式版
Spring理念: 使现有技术更加实用 本身就是大杂烩 整合现有的框架技术 解决企业应用开发的复杂性而创建的
Spring 是一个开源框架, Spring 是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design 中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为JavaEE 应用程序开发提供集成的框架。Spring 使用基本的JavaBean 来完成以前只可能由EJB 完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java 应用都可以从Spring 中受益。Spring 的核心是控制反转(IoC)和面向切面(AOP)。简单来
说,Spring 是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。
JavaEE 开发分成三层结构:
- WEB 层:Spring MVC.
- 业务层:Bean 管理:(IOC)
- 持久层:Spring 的JDBC 模板.ORM 模板用于整合其他的持久层框架.
Spring官方网站:
https://docs.spring.io
官方下载地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
GitHub下载地址:https://github.com/spring-projects
下载spring中的jar网址:https://repo.spring.io/libs-release-local/org/springframework/spring/4.3.29.RELEASE/
Spring优点:
- Spring框架是一个开源、免费的框架、容器
- Spring是一个轻量级、非侵入式的
- JavaEE更加容易使用
- 面向对象的设计比如何实现技术都重要
- 代码更加容易测试
- JavaBean提供了应用程序配置的最好方法
- 在java中,已检查异常被过度使用。框架不应该迫使捕获不能恢复的异常
- 对事务的支持,对框架的支持
- 控制反转IOC,反向切面AOp
Spring组成:
- 最完善的轻量级核心框架
- 通用的的事务管理抽象层
- JDBC抽象层
- 集成了Toplink、JDO、and iBATIS SQL Maps
- AOP功能
- 灵活的的MVC Web框架
为什么学习Spring?
- 方便解耦,简化开发
Spring 就是一个大工厂,可以将所有对象创建和依赖关系维护,交给Spring 管理 - AOP 编程的支持
Spring 提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能 - 声明式事务的支持
只需要通过配置就可以完成对事务的管理,而无需手动编程 - 方便程序的测试
Spring 对Junit4 支持,可以通过注解方便的测试Spring 程序 - 方便集成各种优秀框架
Spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、
MyBatis、Quartz 等)的直接支持 - 降低JavaEE API 的使用难度
Spring 对JavaEE 开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封
装,使这些API 应用难度大大降低
spring版本–3.x、4.x、5.x
2-简单的搭建一个spring框架项目
2.1-首先进入官网 https://spring.io/ 点击projects后点击framework
2.2 点击github这个头像
2.3 往下翻 点击图示位置
2.4 接下来创建一个简单的spring项目
2.4.1 Spring 框架核心模块
2.4.2 创建项目成功后 导入相应的jar包
2.4.3 创建包
2.4.3.1 pojo包下的Student实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int sid;
private String sname;
private String sex;
private int age;
private String addr;
private int cid;
public void init(){
System.out.println("Student实体类初始化方法被调用......");
}
public void destory(){
System.out.println("Student实体类方法调用被销毁....");
}
}
2.4.3.2 建立resources资源目录 定义spring的配置文件 applicationContext.xml(当然文件名可以任意定义)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
2.4.3.3 测试
//测试spring中的bean对象常用属性
@Test
public void test01(){
//1.1得到spring容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
Student stu01 = context.getBean(Student.class);
Student stu02 = context.getBean(Student.class);
System.out.println("stu01 = " + stu01);
//1.2)测试spring的默认作用域为单例模式
System.out.println(stu01==stu02);
context.close();
}
Student实体类初始化方法被调用......
stu01 = Student(sid=0, sname=null, sex=null, age=0, addr=null, cid=0)
true
Student实体类方法调用被销毁....
2.4.4 spring创建对象的三种方式
2.4.4.1 使用构造器无参创建bean对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
bean 标签的一些常用属性说明:
① name:代表为自定义的bean 起一个名字,可以存放特殊字符。
② id:代表为自定义的bean 指定一个id,不能存放特殊字符。
③ class:代表自定义bean 的完整类名,包括包名。
④ abstract:代表自定义bean 是否是抽象类,true:是抽象类,false:不是抽象类
⑤ init-method:代表自定义bean 的初始化方法.
⑥ destroy-method:代表自定义bean 的销毁方法。
⑦ scope:代表自定义bean 的作用范围。可取值如下:
singleton:代表此对象为单例。【默认值】(常用)
prototype:代表此对象为多例。(常用)
request:代表此对象在一次请求有效。
session:代表此对象在浏览器不关闭的情况下有效。
-->
<!--bean-->
<bean id="student" class="com.zelin.pojo.Student" init-method="init" destroy-method="destory" scope="singleton"/>
</beans>
测试
//测试spring中的bean对象常用属性
@Test
public void test01(){
//1.1得到spring容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
Student stu01 = context.getBean(Student.class);
Student stu02 = context.getBean(Student.class);
System.out.println("stu01 = " + stu01);
//1.2)测试spring的默认作用域为单例模式
System.out.println(stu01==stu02);
context.close();
}
测试结果
Student实体类初始化方法被调用......
stu01 = Student(sid=0, sname=null, sex=null, age=0, addr=null, cid=0)
true
Student实体类方法调用被销毁....
2.4.4.2 使用静态工厂方法创建对象
BeanFactory
/**
* @author wf
* @date 2020-10-16 18:45
* 使用静态方法创建bean对象
*/
public class BeanFactory {
public static Student getStudent(){
return new Student();
}
}
配置文件
<!--bean对象:第二种方式:使用静态方法创建对象-->
<bean id="beanFactory" class="com.zelin.factory.BeanFactory" factory-method="getStudent"/>
测试
//2.使用静态方法获取bean对象
@Test
public void test02(){
//2.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stu02 = (Student) context.getBean("beanFactory");
System.out.println("stu02 = " + stu02);
}
测试结果
//2.使用静态方法获取bean对象
@Test
public void test02(){
//2.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stu02 = (Student) context.getBean("beanFactory");
System.out.println("stu02 = " + stu02);
}
2.4.4.3 使用对象工厂方式创建bean对象
BeanStudent.java
/**
* 第三种方式:使用对象工厂方式构造bean对象
*/
public class BeanStudent {
public Student getStudent(){
return new Student();
}
}
配置文件
<!--第三种方式:使用对象工厂方式构造对象-->
<bean id="factoryStu" class="com.zelin.factory.BeanStudent"/>
<bean id="studentBean" factory-bean="factoryStu" factory-method="getStudent"/>
测试
//3.使用对象工厂方法获取bean对象
@Test
public void test03(){
//3.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stu03 = (Student) context.getBean("studentBean");
System.out.println("stu03 = " + stu03);
}
测试结果
Student实体类初始化方法被调用......
stu03 = Student(sid=0, sname=null, sex=null, age=0, addr=null, cid=0)
2.4.5 IOC-控制反转(Inverse Of Control)
以前程序中的javabean 对象是由我们程序员创建完成,现在由spring 容器帮我们创建完成,并且以前javabean 的依赖关系也是我们程序员自己定义,现在也由spring 容器帮我们创建这种依赖关系,所以,这种控制权以前由我们完成现在改由spring 容器完成,这样,控制权发生了反转。
2.4.6 DI-依赖注入(Dependency-Injection)
就是我们可以在spring 的配置文件中定义javabean 时,可以为其指定依赖关系,这样,我们在程序中的这种依赖就不需要我们程序员去干预。
2.4.7属性的赋值(简单属性赋值)
2.4.7.1 方法一:setter方法实现属性的赋值【最常用的方法】
配置文件
<bean id="student" class="com.zelin.pojo.Student" init-method="init" destroy-method="destory" scope="singleton">
<!--实现属性赋值方法一:setter方法实现-->
<property name="sid" value="1001"/>
<property name="sname" value="刘亦菲"/>
<property name="sex" value="女"/>
<property name="age" value="18"/>
<property name="addr" value="上海"/>
<property name="cid" value="2005"/>
</bean>
测试代码
//4.setter方法实现属性赋值
@Test
public void test04(){
//4.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stud = (Student) context.getBean("student");
System.out.println("stud = " + stud);
}
实现结果
stud = Student(sid=1001, sname=刘亦菲, sex=女, age=18, addr=上海, cid=2005)
2.4.7.2 方法二:构造方法实现属性的赋值【较使用】
配置文件
<!--第二种实现属性注入方式:构造方法为属性进行赋值-->
<bean id="stud01" class="com.zelin.pojo.Student">
<!--使用index下标 不常用 因为Index容易出错-->
<!--<constructor-arg index="0" value="1001"/>-->
<!--<constructor-arg index="1" value="刘亦菲"/>-->
<!--<constructor-arg index="2" value="女"/>-->
<!--<constructor-arg index="3" value="18"/>-->
<!--<constructor-arg index="4" value="上海"/>-->
<!--<constructor-arg index="5" value="1987"/>-->
<!--使用name属性-->
<constructor-arg name="sid" value="1001"/>
<constructor-arg name="sname" value="刘亦菲"/>
<constructor-arg name="addr" value="上海"/>
<constructor-arg name="sex" value="1001"/>
<constructor-arg name="age" value="18"/>
<constructor-arg name="cid" value="1987"/>
</bean>
测试代码
//5.方法二:构造器方法实现属性赋值
@Test
public void test05(){
//5.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stud02 = (Student) context.getBean("stud01");
System.out.println("stud02 = " + stud02);
}
实现结果
stud02 = Student(sid=1001, sname=刘亦菲, sex=1001, age=18, addr=上海, cid=1987)
2.4.7.3 方法三:p标签或c标签实现属性的赋值【不常使用】
下面以p标签方式实现属性的赋值
配置文件:需要导入p标签的配置
xmlns:p="http://www.springframework.org/schema/p
<!--第三种方式实现属性的赋值:p标签或者c标签-->
<bean id="stud02" class="com.zelin.pojo.Student"
p:sid="1003" p:sname="刘亦菲" p:sex="女"
p:addr="上海" p:age="25" p:cid="1009"/>
测试代码
//6.方法三:p标签或c标签实现属性赋值
@Test
public void test06(){
//6.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stud02 = (Student) context.getBean("stud02");
System.out.println("stud02 = " + stud02);
}
实现结果
stud02 = Student(sid=1003, sname=刘亦菲, sex=女, age=25, addr=上海, cid=1009)
2.4.7.4 方法四:spel实现属性的赋值【不常使用】 spel: spring Expression Language
配置文件
<!--第四种方式实现属性的赋值:spel的注入-->
<bean name="stud03" class="com.zelin.pojo.Student">
<property name="sid" value="#{stud01.sid}"/>
<property name="sname" value="孙悟空"/>
<property name="age" value="#{stud02.age}"/>
<property name="sex" value="#{stud01.sex}"/>
<property name="addr" value="#{stud01.addr}"/>
<property name="cid" value="#{stud02.cid}"/>
</bean>
测试代码
//7.方法四:spel注入实现属性赋值
@Test
public void test07(){
//6.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
Student stud03 = (Student) context.getBean("stud03");
System.out.println("stud03 = " + stud03);
}
实现结果
stud03 = Student(sid=1001, sname=孙悟空, sex=1001, age=25, addr=上海, cid=1009)
2.4.8 属性的赋值(复杂赋值: Arrays数组 List列表 Map集合 Properties 属性)
实体类
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CollectionBean {
private String[] names; //Arrays
private List<Student> students; //List
private Map<String,Student> maps; //Map
private Properties properties; //Properties
}
配置文件
<bean name="colBean" class="com.zelin.pojo.CollectionBean">
<!--数组-->
<property name="names">
<array>
<value>唐僧</value>
<value>孙悟空</value>
<value>猪八戒</value>
</array>
</property>
<!--列表-->
<property name="students">
<list>
<value>#{stud01}</value>
<value>#{stud02}</value>
<value>#{stud03}</value>
</list>
</property>
<!--map-->
<property name="maps">
<map>
<entry key="#{stud01.sname}" value="#{stud01}"/>
<entry key="#{stud02.sname}" value="#{stud02}"/>
<entry key="#{stud03.sname}" value="#{stud03}"/>
</map>
</property>
<!--Properties-->
<property name="properties">
<props>
<prop key="#{stud01.sname}">#{stud01.sname}</prop>
<prop key="#{stud02.sname}">#{stud02.sname}</prop>
<prop key="#{stud02.sname}">#{stud03.sname}</prop>
</props>
</property>
</bean>
测试
//8.复杂属性赋值
@Test
public void test08(){
//8.1得到spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext.xml");
CollectionBean colleationBean = (CollectionBean) context.getBean("colBean");
System.out.println("colleationBean = " + colleationBean);
}
结果
colleationBean = CollectionBean(names=[唐僧, 孙悟空, 猪八戒], students=[Student(sid=1001, sname=刘亦菲, sex=1001, age=18, addr=上海, cid=1987), Student(sid=1003, sname=刘亦菲, sex=女, age=25, addr=上海, cid=1009), Student(sid=1001, sname=孙悟空, sex=1001, age=25, addr=上海, cid=1009)], maps={刘亦菲=Student(sid=1003, sname=刘亦菲, sex=女, age=25, addr=上海, cid=1009), 孙悟空=Student(sid=1001, sname=孙悟空, sex=1001, age=25, addr=上海, cid=1009)}, properties={刘亦菲=孙悟空})
2-5 使用spring+c3p0连接数据库测试
需要导入对应的包
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--1-加载属性文件-->
<context:property-placeholder location="classpath*:properties/db.properties"/>
<!--2-定义数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
在resources资源目录下创建文件夹properties 然后创建db.properties文件 负责数据库的配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///chrisfeng
jdbc.user=root
jdbc.password=123456
测试
//测试在spring下能不能连接本地数据库
public class TestDataBase {
private ApplicationContext context;
@Before
public void init(){
//1.获取spring容器
context = new ClassPathXmlApplicationContext("classpath:spring/application-dao.xml");
}
@Test
public void test01() throws SQLException {
//1.获取数据源
DataSource dataSource = (DataSource) context.getBean("dataSource");
//2.得到QueryRunner对象
QueryRunner runner = new QueryRunner(dataSource);
//3.查询数据库
List<Student> students = runner.query("select * from student", new BeanListHandler<>(Student.class));
//4.遍历查询后的学生列表
for (Student student : students) {
System.out.println(student);
}
}
}
测试结果
Student(sid=2, sname=双双, sex=女, age=24, addr=武汉, cid=4)
Student(sid=3, sname=刘亦菲, sex=女, age=18, addr=上海, cid=3)
Student(sid=4, sname=游金龙, sex=男, age=23, addr=湖南长沙, cid=4)
Student(sid=7, sname=彭于晏, sex=男, age=23, addr=香港, cid=3)
Student(sid=9, sname=周杰伦, sex=男, age=35, addr=*, cid=2)
Student(sid=11, sname=武林高手, sex=男, age=35, addr=青岛, cid=3)
Student(sid=15, sname=林峰, sex=女, age=27, addr=南京, cid=3)
Student(sid=16, sname=杨幂, sex=女, age=35, addr=长沙, cid=2)
Student(sid=17, sname=荔枝, sex=女, age=25, addr=九江, cid=2)
Student(sid=18, sname=李蕾, sex=女, age=24, addr=九江, cid=2)
Student(sid=21, sname=大水阿比, sex=女, age=25, addr=杭州, cid=2)
Student(sid=22, sname=嘿嘿, sex=女, age=23, addr=杭州, cid=4)
Student(sid=23, sname=张天爱, sex=女, age=34, addr=梅州, cid=3)
Student(sid=24, sname=杨颖, sex=男, age=35, addr=上海, cid=3)
Student(sid=26, sname=哈哈哈, sex=女, age=26, addr=黑龙江, cid=3)
Student(sid=27, sname=哈哈哈, sex=男, age=29, addr=哈尔滨, cid=1)
测试成功!没问题
3-使用spring+c3p0连接池+servlet+elementUi+vue实现简单的学生管理系统的增删改查
3.1 前端部分index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生列表</title>
<!--1.引入vue-->
<script src="plugins/vue.min.js"></script>
<!--2.引入axios-->
<script src="plugins/axios.min.js"></script>
<!-- 3.引入样式 -->
<link rel="stylesheet" href="plugins/element-ui/lib/theme-chalk/index.css">
<!-- 4.引入组件库 -->
<script src="plugins/element-ui/lib/index.js"></script>
<style>
*{
padding: 0px;
margin: 0px;
}
.el-header, .el-footer {
background-color: #B3C0D1;
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: white;
color: #333;
text-align: center;
line-height: 100px;
height: 800px;
}
.el-container .el-main {
background-color: #E9EEF3;
color: #333;
text-align: center;
padding: 0px;
}
body > .el-container {
margin-bottom: 40px;
}
.el-table{
margin: 0;
padding:0;
}
#dd{
text-align: right;
margin-top: -5px;
}
</style>
</head>
<body>
<el-container id="d1">
<el-header>学生后台管理系统</el-header>
<el-container>
<el-aside width="200px">
<el-menu :default-openeds="['1']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-message"></i>后台管理</template>
<el-menu-item-group>
<el-menu-item index="1-1">首页</el-menu-item>
</el-menu-item-group>
</el-submenu>
<el-submenu index="2">
<template slot="title"><i class="el-icon-menu"></i>学生管理</template>
<el-menu-item-group>
<el-menu-item index="2-1">学生列表</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<el-main>
<!--{{studentsListIds}}-->
<el-table
:data="students"
border
:header-cell-style="headContent"
:cell-style = "contentData"
stripe
style="width: 100%"
@selection-change="handleSelectionChange">
<el-table-column
type="selection"
label="删除">
</el-table-column>
<el-table-column
prop="sid"
label="学号">
</el-table-column>
<el-table-column
prop="sname"
label="学生姓名"
>
</el-table-column>
<el-table-column
prop="sex"
label="学生性别"
>
</el-table-column>
<el-table-column
prop="age"
label="学生年龄"
>
</el-table-column>
<el-table-column
prop="addr"
label="学生地址"
>
</el-table-column>
<el-table-column
prop="cname"
label="所在班级">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="200">
<template slot-scope="scope">
<el-button @click="handleClick(scope.row)" type="primary" size="mini">修改</el-button>
</template>
</el-table-column>
</el-table>
<div style="margin-top: 20px" id="dd">
<el-col :span="8">
<div class="grid-content bg-purple-light">
<!--{{sname}}-->
<el-input
placeholder="请输入查询学生的关键字"
v-model="sname"
clearable>
</el-input>
</div>
</el-col>
<el-col :span="8">
<div class="grid-content bg-purple-light">
<!--{{addr}}-->
<el-input
placeholder="请输入查询住址的关键字"
v-model="addr"
clearable>
</el-input>
</div>
</el-col>
<el-button type="danger" @click="delStu()" icon="el-icon-delete">批量删除</el-button>
<el-button @click="addStu()" type="success" icon="el-icon-plus" >添加</el-button>
<el-button @click="search()" type="success" icon="el-icon-search" >查询列表</el-button>
<el-button @click="returnList()" type="success" icon="el-icon-refresh" >返回列表</el-button>
</div>
</el-main>
</el-container>
<!-- 弹出框显示点击修改时 显示当前对应学生对象的值-->
<el-dialog title="学生信息" :visible.sync="dialogFormVisible">
<!--{{student}}-->
<el-form :model="student">
<el-form-item label="学生姓名" :label-width="formLabelWidth">
<el-input v-model="student.sname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="学生性别" :label-width="formLabelWidth">
<el-radio v-model="student.sex" label="男">男</el-radio>
<el-radio v-model="student.sex" label="女">女</el-radio>
</el-form-item>
<el-form-item label="学生年龄" :label-width="formLabelWidth">
<el-input v-model="student.age" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="学生地址" :label-width="formLabelWidth">
<el-input v-model="student.addr" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="所在班级" :label-width="formLabelWidth">
<el-select v-model="student.cid" placeholder="请选择所在班级" style="width: 100%">
<el-option v-for="c in classes" :label="c.cname" :value="c.cid"></el-option>
</el-select>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="save()">确 定</el-button>
</div>
</el-dialog>
</el-container>
</body>
<script>
new Vue({
el:"#d1",
data:{
students:[],
dialogFormVisible: false, //默认弹出框不弹出
student: { //单个学生信息
sname: '',
sex: '',
age: '',
addr: '',
cid: '',
},
formLabelWidth: '120px',
classes:[], //查询所有班级信息
sname:'', //查询学生姓名关键字
addr:'', //查询学生住址关键字
page:1, //当前页面
pageSize:3, //每页的数量
total:20, //学生总数
studentsListIds:[],
},
methods: {
//1.定义查询所有学生的方法
findAllStudents() {
axios.get("student?cmd=list").then(response => { //找到servlet对应的方法 查询学生数据
this.students = response.data; //将后端传来的数据赋值给数组 属性必须一一对应
})
},
//2.设置表头居中以及表格内容居中
headContent() {
return "text-align:center;color:blue;background:aqua;";
},
contentData() {
return "text-align:center";
},
//3.查询所有班级信息
findAllClasses() {
axios.get("classes?cmd=list").then(response => {
this.classes = response.data;
})
},
//4.查看单个学生对象 点击表格修改
handleClick(row){ //row表示当前这一行
//console.log(row) //row表示当前这一行学生对象的值
this.dialogFormVisible = true; //显示弹出框
this.student = row; //将当前数据显示在弹出框页面当中
},
//5.添加学生
addStu(){
this.dialogFormVisible = true; //显示弹出框
this.student = {}; //清空学生对象
},
//6.修改学生或者添加学生(保存学生)
save(){
//6.1)关闭对话框
this.dialogFormVisible = false;
//6.2)定义url
let url = "student?cmd=add";
//6.3)判断此时对话框中学生对象是否存在sid
if(this.student.sid){
//6.4)执行修改
url = "student?cmd=update"
}
//6.5)执行后台操作
axios.post(url,"stud="+JSON.stringify(this.student)).then(response=>{
console.log(response);
//6.5.1)获取后台传送的信息
if(response.data.success){
this.findAllStudents();; //说明数据添加或者修改成功 刷新页面
}else{
this.$message({
showClose: true,
message: resp.data.message,
type: 'error'
}); //说明添加数据或者修改数据失败
}
})
},
//7.查询学生
search(){
//7.1)将需要查询的关键字传入后端
axios.get("student?cmd=search&sname="+this.sname+"&addr="+this.addr).then(response=>{
console.log(response.data);
this.students = response.data; //返回后端查询的数据
})
},
//8.返回列表
returnList(){
this.sname = "";
this.addr = "";
axios.get("student?cmd=list").then(response=>{ //找到servlet对应的方法 查询学生数据
this.students = response.data; //将后端传来的数据赋值给数组 属性必须一一对应
})
},
//10.用户点击复选框
handleSelectionChange(val) {
this.studentsListIds = val;
},
//11.根据选中的学生对象删除对应的学生
delStu(){
//11.1)获取对应的id数
let ids=[]; //定义存放选中的编号数组
this.studentsListIds.forEach(stud=>{
//11.2)添加编号到数组中
ids.push(stud.sid);
});
console.log(ids);
//11.3)把数组传入到后端中
axios.get("student?cmd=deleteStu&ids="+ids).then(resp=>{
console.log(resp.data);
if(resp.data.success){
this.findAllStudents();; //说明数据删除成功 刷新页面
}else{
this.$message({
showClose: true,
message: resp.data.message,
type: 'error'
});
}
})
}
},
created(){ //创建vue实例后调用方法
this.findAllStudents();
this.findAllClasses();
}
})
</script>
3.2 后端
3.2.1 servlet层
StudentServlet.java
package com.zelin.servlet;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zelin.pojo.Result;
import com.zelin.pojo.Student;
import com.zelin.service.StudentService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
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.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 19:57
*/
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
private StudentService studentService;
@Override
public void init() throws ServletException {
//得到spring容器
WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
studentService = ac.getBean(StudentService.class);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.设置编码格式
req.setCharacterEncoding("UTF8");
resp.setContentType("text/html;charset=UTF8");
//2.获取参数
String cmd = req.getParameter("cmd");
//3.判断参数 选择不同的方法
if(StrUtil.isNotBlank(cmd)){
if("list".equals(cmd)){
list(req,resp); //列表学生
}else if("add".equals(cmd)){
addStu(req,resp); //添加学生
}else if("update".equals(cmd)){
update(req,resp); //修改学生
}else if("search".equals(cmd)){
search(req,resp); //查询所有学生
}else if("deleteStu".equals(cmd)){
deleteStu(req,resp); //批量删除
}
}
}
//2.查询所有学生
private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//2.1)查询所有学生
List<Student> studentList = studentService.findAll();
//2.2)输出打印
resp.getWriter().println(JSON.toJSONString(studentList));
//2.3)刷新
resp.getWriter().flush();
} catch (SQLException e) {
e.printStackTrace();
}
}
//3.添加学生
private void addStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
//3.0)定义结果对象
Result result = null;
try {
//3.1)获取前端传过来的参数
String stud = req.getParameter("stud");
//3.2)将json字符串转为学生对象
Student student = JSON.parseObject(stud, Student.class);
//3.3)将添加的学生数据添加到数据库中
studentService.insert(student);
//3.4)返回结果给前端
result = new Result(true,"添加学生成功!");
} catch (Exception e) {
e.printStackTrace();
result = new Result(false,"添加学生对象失败!");
}
//3.5)返回结果给前端页面
resp.getWriter().println(JSON.toJSONString(result));
//3.6)刷新页面
resp.getWriter().flush();
}
//4.修改学生
private void update(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
//4.1)定义结果对象
Result result = null;
try {
//4.2)获取前端传过来的参数
String stud = req.getParameter("stud");
//4.3)将json字符串转为学生对象
Student student = JSON.parseObject(stud, Student.class);
//4.4)将修改后的学生数据添加到数据库中
studentService.update(student);
//4.5)返回结果给前端
result = new Result(true,"修改学生成功!");
} catch (Exception e) {
e.printStackTrace();
result = new Result(false,"修改学生对象失败!");
}
//4.6)返回结果给前端页面
resp.getWriter().println(JSON.toJSONString(result));
//4.7)刷新页面
resp.getWriter().flush();
}
//6.查询学生
private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
try {
//6.1)获取前端传来的参数
String sname = req.getParameter("sname");
String addr = req.getParameter("addr");
System.out.println("姓名关键字为:"+sname+"住址关键字为:"+addr);
//6.2)传入数据库
List<Student> students = studentService.search(sname,addr);
//6.3)输出打印
resp.getWriter().println(JSON.toJSONString(students));
//6.4)刷新
resp.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
//8.批量删除
private void deleteStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
Result result = null;
try{
//8.1)获取前端参数
String ids = req.getParameter("ids");
System.out.println(ids);
//8.2)传入数据库
studentService.deleteStu(ids);
result = new Result(true,"修改学生成功!");
} catch (Exception e) {
e.printStackTrace();
result = new Result(false,"修改学生对象失败!");
}
//8.3)返回结果给前端页面
resp.getWriter().println(JSON.toJSONString(result));
//8.4)刷新页面
resp.getWriter().flush();
}
}
ClassesServlet
package com.zelin.servlet;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zelin.pojo.Classes;
import com.zelin.service.ClassesService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
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.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 21:00
*/
@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {
private ClassesService classesService;
@Override
public void init() throws ServletException {
//得到spring容器
WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
classesService = ac.getBean(ClassesService.class);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.设置编码格式
req.setCharacterEncoding("UTF8");
resp.setContentType("text/html;charset=UTF8");
//2.获取参数
String cmd = req.getParameter("cmd");
//3.判断参数 选择不同的方法
if(StrUtil.isNotBlank(cmd)){
if("list".equals(cmd)){
list(req,resp);
}
}
}
//2.查询所有班级
private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//2.1)查询所有学生
List<Classes> classesList = classesService.findAll();
//2.2)输出打印
resp.getWriter().println(JSON.toJSONString(classesList));
//2.3)刷新
resp.getWriter().flush();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.2.2 service层
StudentService接口
package com.zelin.service;
import com.zelin.pojo.Student;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 20:06
*/
public interface StudentService {
List<Student> findAll() throws SQLException;
void insert(Student student) throws SQLException;
void update(Student student) throws SQLException;
void deleteStu(String ids) throws SQLException;
List<Student> search(String sname, String addr) throws SQLException;
}
StudentServiceImpl.java
package com.zelin.service.impl;
import com.zelin.dao.StudentDao;
import com.zelin.pojo.Student;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 20:06
*/
public class StudentServiceImpl implements com.zelin.service.StudentService {
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
//1.查询所有学生
@Override
public List<Student> findAll() throws SQLException {
return studentDao.findAll();
}
//2.添加学生
@Override
public void insert(Student student) throws SQLException {
studentDao.insert(student);
}
//3.修改学生对象
@Override
public void update(Student student) throws SQLException {
studentDao.update(student);
}
//4.批量删除学生
@Override
public void deleteStu(String ids) throws SQLException {
String[] split = ids.split(",");
System.out.println(split);
for (String sid : split) {
studentDao.deleteStu(sid);
}
}
//5.关键字查询学生
public List<Student> search(String sname, String addr) throws SQLException {
return studentDao.search(sname,addr);
}
}
ClassesService接口
package com.zelin.service;
import com.zelin.pojo.Classes;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 21:02
*/
public interface ClassesService {
List<Classes> findAll() throws SQLException;
}
ClassesServiceImpl
package com.zelin.service.impl;
import com.zelin.dao.ClassesDao;
import com.zelin.pojo.Classes;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 21:02
*/
public class ClassServiceImpl implements com.zelin.service.ClassesService {
private ClassesDao classesDao ;
public void setClassesDao(ClassesDao classesDao) {
this.classesDao = classesDao;
}
@Override
public List<Classes> findAll() throws SQLException {
return classesDao.findAll();
}
}
3.3.3 dao层
StudentDao接口
package com.zelin.dao;
import com.zelin.pojo.Student;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 20:14
*/
public interface StudentDao {
List<Student> findAll() throws SQLException;
void insert(Student student) throws SQLException;
void update(Student student) throws SQLException;
void deleteStu(String sid) throws SQLException;
List<Student> search(String sname, String addr) throws SQLException;
}
ClaaaesDao接口
package com.zelin.dao;
import com.zelin.pojo.Classes;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 21:04
*/
public interface ClassesDao {
List<Classes> findAll() throws SQLException;
}
StudentDaoImpl
package com.zelin.dao.impl;
import cn.hutool.core.util.StrUtil;
import com.zelin.dao.StudentDao;
import com.zelin.pojo.Student;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 20:14
*/
public class StudentDaoImpl implements StudentDao {
private QueryRunner runner;
//setter方法注入runner属性
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
//1.查询所有学生信息
@Override
public List<Student> findAll() throws SQLException {
return runner.query("select st.*,cname from student st,classes c where c.cid = st.cid",
new BeanListHandler<>(Student.class));
}
//2.添加学生
@Override
public void insert(Student student) throws SQLException {
runner.update("insert into student values(null,?,?,?,?,?)",
student.getSname(),student.getSex(),student.getAge(),
student.getAddr(),student.getCid());
}
//3.修改学生对象
@Override
public void update(Student student) throws SQLException {
runner.update("update student set sname=?,sex=?,age=?,addr=?,cid=? where sid=? ",
student.getSname(),student.getSex(),student.getAge(),
student.getAddr(),student.getCid(),student.getSid());
}
//4.批量删除学生
@Override
public void deleteStu(String sid) throws SQLException {
runner.update("delete from student where sid=?",sid);
}
//5.关键字查询学生
@Override
public List<Student> search(String sname, String addr) throws SQLException {
String sql = "select st.*,cname from student st,classes c where c.cid = st.cid";
if(StrUtil.isNotBlank(sname)){
sql += " and sname like '%"+sname+"%'";
}
if(StrUtil.isNotBlank(addr)){
sql += " and addr like '%"+addr+"%'";
}
System.out.println("SQL = "+sql);
return runner.query(sql,new BeanListHandler<>(Student.class));
}
}
ClassesDaoImpl
package com.zelin.dao.impl;
import com.zelin.dao.ClassesDao;
import com.zelin.pojo.Classes;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
/**
* @author wf
* @date 2020-10-08 21:04
*/
public class ClassesDaoImpl implements ClassesDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
@Override
public List<Classes> findAll() throws SQLException {
return runner.query("select * from classes ",
new BeanListHandler<>(Classes.class));
}
}
3.2.4 pojo
Student
package com.zelin.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author wf
* @date 2020-10-16 17:30
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int sid;
private String sname;
private String sex;
private int age;
private String addr;
private int cid;
public void init(){
System.out.println("Student实体类初始化方法被调用......");
}
public void destory(){
System.out.println("Student实体类方法调用被销毁....");
}
}
Classes
package com.zelin.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author wf
* @date 2020-10-16 20:40
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Classes {
private int cid;
private String cname;
}
Result
package com.zelin.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author wf
* @date 2020-10-08 21:24
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
private boolean success;
private String message;
}
3.2.5 配置web.xml 否则会报错
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--1.加载全局配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/application-dao.xml</param-value>
</context-param>
<!--2.加载spring监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
效果演示