vue-ssm项目
目录
一、准备阶段
1.创建新的工程项目
2.添加web
(1).点击模块添加web模块
(2).在main文件夹下创建webapp文件夹
将web模块路径修改为webapp
3.添加tomcat
war包
要添加<packaging>war</packaging>
使工程更改为war包并刷新
4.连接数据库
5.在pom文件中导入依赖
<dependencies> <!--oss的依赖--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.15.1</version> </dependency> <!--文件上传依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--pageHelper的依赖 分页依赖--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> </dependency> <!--spring webmvc依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.15.RELEASE</version> </dependency> <!--mybatis的依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <!--mysql驱动依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.31</version> </dependency> <!--druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> <!--spring和mybatis整合的依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> <!--spring框架依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.15.RELEASE</version> </dependency> <!--json格式转换注解的依赖--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> <!--servlet-api--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!--jsp-api--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <!--测试依赖--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!--pojo实体类构造器注解依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <!--jstl标签库的依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
6.在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"> <!--注册DispatchServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--如果没有指定参数默认解析WEB-INF/servlerName-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--编码过滤器--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
7.创建spring框架配置文件
在resources(配置文件)下创建
取名没有具体限制但是要见名知意
在spring.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--1.包扫描--> <context:component-scan base-package="com.lzq.controller,com.lzq.service"/> <!--2.注解驱动--> <mvc:annotation-driven/> <!--3.静态资源放行--> <mvc:default-servlet-handler/> <!--4.视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> </bean> <!--5.配置数据源--> <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db2"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--6. SqlSessionFactory:理解为mybatis文件--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 分页拦截器 --> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <!--使用下面的方式配置参数,一行配置一个 --> <value> params=value1 </value> </property> </bean> </array> </property> <property name="dataSource" ref="datasource"/> <!--指定mybatis映射文件的路径--> <property name="mapperLocations" value="classpath*:mapper/*.xml"/> </bean> <!--7.设置dao接口的代理实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sessionFactory"/> <!--dao接口所在的包--> <property name="basePackage" value="com.lzq.dao"/> </bean> <!--文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="52428800"></property> </bean> </beans>
8.创建java代码各个包
1.在java目录下创建包
2.在resources目录下创建
3.创建之后目录所代表的意义
controller代表控制层
调用业务层,转换数据格式返还给前端
dao代表持久层
操作数据库,对数据库进行增删改查
pojo代表实体层
通过反射接受数据库数据
service代表业务层
对dao层数据进行操作返还给控制层
util代表封装的工具类
util包存放封装好的工具类使用
vo代表视图对象
vo包中存放实体类(该实体类用来限制返还给前端数据的格式)
9.导入渲染前端需要的文件
二、实现crud功能
1.查询功能
目录
controller层
StudentController
@Controller @RequestMapping("/student") public class StudentContorller { @Autowired private StudentService studentService; @RequestMapping("/list") @ResponseBody public Requs findAll(){ List<Student> all = studentService.findAll(); if (all.size()==0){ return new Requs(500,"查询失败",null); } return new Requs(200,"查询成功",all); } }
dao层
StudentDao
public interface StudentDao { List<Student> findAll(); }
pojo层
Student
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer sid; private String name; private Integer age; private String sex; private Integer cid; private String headImg; private Clazz clazz; }
Calzz
@Data @AllArgsConstructor @NoArgsConstructor public class Clazz { private Integer id; private String cname; }
service层
StudentService
public interface StudentService { List<Student> findAll(); }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public List<Student> findAll() { List<Student> all = studentDao.findAll(); return all; } }
vo层
Requs
@Data @AllArgsConstructor @NoArgsConstructor public class Requs { private Integer code; private String msg; private Object data; }
mepper
StudentMapper
<mapper namespace="com.lzq.dao.StudentDao"> <resultMap id="mystudent" type="com.lzq.pojo.Student" autoMapping="true"> <id property="sid" column="sid"/> <association property="clazz" javaType="com.lzq.pojo.Clazz"> <id property="id" column="id"/> </association> </resultMap> <select id="findAll" resultType="com.lzq.pojo.Student"> select s.sid,s.name,s.cid,s.sex,s.age,s.headImg,c.id,c.cname from student s join clazz c on s.cid = c.id </select> </mapper>
前端页面
min.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/14 Time: 13:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link rel="stylesheet" href="/css/index.css"> <script type="text/javascript" src="/js/index.js"></script> </head> <body> <div id="aaa"> <%--查询所有数据表格开始--%> <el-table :data="list" border style="width: 100%"> <el-table-column prop="sid" label="学生编号" width="180"> </el-table-column> <el-table-column prop="headImg" label="学生头像" width="180"> </el-table-column> <el-table-column prop="name" label="学生姓名" width="180"> </el-table-column> <el-table-column prop="age" label="学生年龄"> </el-table-column> <el-table-column prop="sex" label="学生性别"> </el-table-column> <el-table-column prop="age" label="学生年龄"> </el-table-column> </el-table> <%--查询所有数据表格结束--%> </div> </body> <script> let a = new Vue({ el:"#aaa", data:{ //所有数据 list:{}, }, created(){ this.getlist() }, methods:{ getlist(){ var that = this; axios.post("/student/list").then(function (requs){ if (requs.data.code==200){ that.list = requs.data.data; }else { alert(requs.data.msg); } }) } } }) </script> </html>
2.删除功能
脑图
controller层
StudentController
@RequestMapping("/del") @ResponseBody public Requs delById(Integer id) { Integer integer = studentService.delById(id); if (integer == 0) { return new Requs(500, "操作失败", null); } return new Requs(200, "删除成功", null); }
dao层
StudentDao
Integer delBySid(Integer id);
pojo层
Student
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer sid; private String name; private Integer age; private String sex; private Integer cid; private String headImg; private Clazz clazz; }
Calzz
@Data @AllArgsConstructor @NoArgsConstructor public class Clazz { private Integer id; private String cname; }
service层
StudentService
public interface StudentService { Integer delById(Integer id); }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public Integer delById(Integer id) { Integer integer = studentDao.delBySid(id); return integer; } }
vo层
Requs
@Data @AllArgsConstructor @NoArgsConstructor public class Requs { private Integer code; private String msg; private Object data; }
mepper
StudentMapper
<mapper namespace="com.lzq.dao.StudentDao"> <resultMap id="mystudent" type="com.lzq.pojo.Student" autoMapping="true"> <id property="sid" column="sid"/> <association property="clazz" javaType="com.lzq.pojo.Clazz"> <id property="id" column="id"/> </association> </resultMap> <delete id="delBySid"> delete from student where sid=#{id} </delete> </mapper>
前端页面
min.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/14 Time: 13:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link rel="stylesheet" href="/css/index.css"> <script type="text/javascript" src="/js/index.js"></script> </head> <body> <div id="aaa"> <%--查询所有数据表格开始--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--查询所有数据表格结束--%> </div> </body> <script> let a = new Vue({ el: "#aaa", data: { //头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, methods: { //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
3.添加功能
脑图
controller层
StudentController
@RequestMapping("/inset") @ResponseBody public Requs inset(@RequestBody Student student) { System.out.println(student); Integer inset = studentService.inset(student); if (inset == 0) { return new Requs(500, "添加失败", null); } return new Requs(200, "添加成功", null); }
dao层
StudentDao
Integer insertAll(Student student);
pojo层
Student
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer sid; private String name; private Integer age; private String sex; private Integer cid; private String headImg; private Clazz clazz; }
Calzz
@Data @AllArgsConstructor @NoArgsConstructor public class Clazz { private Integer id; private String cname; }
service层
StudentService
public interface StudentService { Integer inset(Student student); }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public Integer inset(Student student) { Integer integer = studentDao.insertAll(student); return integer; } }
vo层
Requs
@Data @AllArgsConstructor @NoArgsConstructor public class Requs { private Integer code; private String msg; private Object data; }
mepper
StudentMapper
<mapper namespace="com.lzq.dao.StudentDao"> <resultMap id="mystudent" type="com.lzq.pojo.Student" autoMapping="true"> <id property="sid" column="sid"/> <association property="clazz" javaType="com.lzq.pojo.Clazz"> <id property="id" column="id"/> </association> </resultMap> <insert id="insertAll"> insert into student values (#{name},#{age},#{sex},#{cid},null,#{headImg}) </insert> </mapper>
前端页面
min.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/14 Time: 13:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link rel="stylesheet" href="/css/index.css"> <script type="text/javascript" src="/js/index.js"></script> </head> <body> <div id="aaa"> <el-button type="success" @click="dialogVisible = true">添加</el-button> <%--添加数据对话框开始--%> <el-dialog title="添加学生" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <%--添加表单开始--%> <el-form ref="form" :model="myform" label-width="80px"> <%--添加头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--添加头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myform.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myform.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myform.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myform.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <%--添加表单结束--%> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="inset">确 定</el-button> </span> </el-dialog> <%--添加数据对话框结束--%> <%--查询所有数据表格开始--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--查询所有数据表格结束--%> </div> </body> <script> let a = new Vue({ el: "#aaa", data: { //头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 必须使用数组 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, methods: { //添加学生表单确定提交事件 inset() { var that = this; axios.post("/student/inset", this.myform).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible = false; that.$message.success(requs.data.msg) that.myform = ""; that.imageUrl = ""; } else { that.$message.error(requs.data.msg) } }) }, //所有班级信息 getclazz() { var that = this; axios.get("/clazz/list").then(function (requs) { console.log(requs.data); that.clazz1 = requs.data.data; }) }, //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
4.修改功能
脑图
controller层
StudentController
@RequestMapping("/updat") @ResponseBody public Requs updat(@RequestBody Student student) { System.out.println(student); Integer integer = studentService.updatAll(student); if (integer == 0) { return new Requs(500, "修改失败", null); } return new Requs(200, "修改成功", null); }
dao层
StudentDao
Integer updateAll(Student student);
pojo层
Student
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer sid; private String name; private Integer age; private String sex; private Integer cid; private String headImg; private Clazz clazz; }
Calzz
@Data @AllArgsConstructor @NoArgsConstructor public class Clazz { private Integer id; private String cname; }
service层
StudentService
public interface StudentService { Integer updatAll(Student student); }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public Integer updatAll(Student student) { Integer integer = studentDao.updateAll(student); return integer; } }
vo层
Requs
@Data @AllArgsConstructor @NoArgsConstructor public class Requs { private Integer code; private String msg; private Object data; }
mepper
StudentMapper
<mapper namespace="com.lzq.dao.StudentDao"> <resultMap id="mystudent" type="com.lzq.pojo.Student" autoMapping="true"> <id property="sid" column="sid"/> <association property="clazz" javaType="com.lzq.pojo.Clazz"> <id property="id" column="id"/> </association> </resultMap> <update id="updateAll"> update student set name=#{name},age=#{age},sex=#{sex},cid=#{cid} where sid=#{sid} </update> </mapper>
前端页面
min.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/14 Time: 13:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link rel="stylesheet" href="/css/index.css"> <script type="text/javascript" src="/js/index.js"></script> </head> <body> <div id="aaa"> <el-button type="success" @click="dialogVisible = true">添加</el-button> <%--修改数据对话框开始--%> <el-dialog title="修改学生" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose"> <%--修改表单标签--%> <el-form ref="form" :model="myup" label-width="80px"> <%--修改头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2"> <img v-if="imageUrl2" :src="imageUrl2" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--修改头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myup.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myup.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myup.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myup.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <el-button @click="dialogVisible2 = false">取 消</el-button> <el-button type="primary" @click="myupdat">确 定</el-button> </span> </el-dialog> <%--修改数据对话框结束--%> <%--添加数据对话框开始--%> <el-dialog title="添加学生" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <%--添加表单开始--%> <el-form ref="form" :model="myform" label-width="80px"> <%--添加头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--添加头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myform.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myform.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myform.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myform.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <%--添加表单结束--%> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="inset">确 定</el-button> </span> </el-dialog> <%--添加数据对话框结束--%> <%--查询所有数据表格开始--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--查询所有数据表格结束--%> </div> </body> <script> let a = new Vue({ el: "#aaa", data: { //头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 必须使用数组 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, methods: { //修改学生提交事件 myupdat() { var that = this; axios.post("/student/updat", this.myup).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible2 = false; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }, //添加学生表单确定提交事件 inset() { var that = this; axios.post("/student/inset", this.myform).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible = false; that.$message.success(requs.data.msg) that.myform = ""; that.imageUrl = ""; } else { that.$message.error(requs.data.msg) } }) }, //所有班级信息 getclazz() { var that = this; axios.get("/clazz/list").then(function (requs) { console.log(requs.data); that.clazz1 = requs.data.data; }) }, //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
三、实现其他功能
1.分页功能
脑图
(1).引入依赖
<!--pageHelper的依赖 分页依赖--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> </dependency>
(2).在spring配置文件中配置分页拦截器
<!--6. SqlSessionFactory:理解为mybatis文件--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 分页拦截器 --> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <!--使用下面的方式配置参数,一行配置一个 --> <value> params=value1 </value> </property> </bean> </array> </property> <property name="dataSource" ref="datasource"/> <!--指定mybatis映射文件的路径--> <property name="mapperLocations" value="classpath*:mapper/*.xml"/> </bean>
(3).对查询的数据进行分页处理
controller
StudentController
@RequestMapping("/listByPage") @ResponseBody public Requs listByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize, @RequestBody Student student) { PageInfo<Student> page = studentService.queryAll(currentPage, pageSize, student); System.out.println(page); return new Requs(200, "查询所有员工成功", page); }
####
service层
StudentService
public interface StudentService { List<Student> findAll(); Integer delById(Integer id); Integer inset(Student student); Integer updatAll(Student student); //分页处理 PageInfo<Student> queryAll(Integer currentPage, Integer pageSize,Student student); }
StudentServiceImpl
public PageInfo<Student> queryAll(Integer currentPage, Integer pageSize, Student student) { PageHelper.startPage(currentPage,pageSize); List<Student> all = studentDao.findAllBylike(student); //把查询的结果封装到Page对象中。 PageInfo<Student> pageInfo=new PageInfo(all); return pageInfo; }
前端代码
list.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/14 Time: 13:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link rel="stylesheet" href="/css/index.css"> <script type="text/javascript" src="/js/index.js"></script> </head> <body> <div id="aaa"> <el-button type="success" @click="dialogVisible = true">添加</el-button> <%--分页组件 size-change:大小改变。每页显示的条数 current-change:当前页面发生改变时触发的事件 current-page: 当前页面 page-sizes: page-size:默认显示的条数 total: 总条数 --%> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[2,10 ,15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> <%--修改数据对话框开始--%> <el-dialog title="修改学生" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose"> <%--修改表单标签--%> <el-form ref="form" :model="myup" label-width="80px"> <%--修改头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2"> <img v-if="imageUrl2" :src="imageUrl2" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--修改头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myup.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myup.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myup.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myup.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <el-button @click="dialogVisible2 = false">取 消</el-button> <el-button type="primary" @click="myupdat">确 定</el-button> </span> </el-dialog> <%--修改数据对话框结束--%> <%--添加数据对话框开始--%> <el-dialog title="添加学生" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <%--添加表单开始--%> <el-form ref="form" :model="myform" label-width="80px"> <%--添加头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--添加头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myform.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myform.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myform.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myform.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <%--添加表单结束--%> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="inset">确 定</el-button> </span> </el-dialog> <%--添加数据对话框结束--%> <%--查询所有数据表格开始--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--查询所有数据表格结束--%> </div> </body> <script> let a = new Vue({ el: "#aaa", data: { //头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 必须使用数组 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, methods: { //每页显示条数时触发的事件 handleSizeChange(val) { console.log(`每页 ${val} 条`); this.pageSize = val; this.bbb(); }, //当前页切换时触发的事件 handleCurrentChange(val) { console.log(`当前页: ${val}`); this.currentPage4 = val; this.bbb(); }, //修改学生提交事件 myupdat() { var that = this; axios.post("/student/updat", this.myup).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible2 = false; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }, //添加学生表单确定提交事件 inset() { var that = this; axios.post("/student/inset", this.myform).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible = false; that.$message.success(requs.data.msg) that.myform = ""; that.imageUrl = ""; } else { that.$message.error(requs.data.msg) } }) }, //所有班级信息 getclazz() { var that = this; axios.get("/clazz/list").then(function (requs) { console.log(requs.data); that.clazz1 = requs.data.data; }) }, //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
2.文件上传功能
脑图
(1).引入依赖
<!--阿里云oss存储空间的依赖--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.15.1</version> </dependency> <!--文件上传依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
(2).在spring配置文件中配置文件上传解析器
<!--文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="52428800"></property> </bean>
(3).对上传的文件进行处理
controller层
@RequestMapping("/alyun") @ResponseBody public Requs aaa(MultipartFile file) {//形参名必须为file String pash = UploadUtil.upload(file); if (pash == null) { return new Requs(500, "上传失败", null); } return new Requs(200, "上传成功", pash); }
Util层(工具类)
UploadUtil
package com.lzq.uito; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.util.UUID; public class UploadUtil { public static String upload(MultipartFile file){ // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-beijing.aliyuncs.com"; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 //LTAI5t7bHCvLg8YucRegLG7v //wEJLCZTwDV6ArUYMwh61QtlUM3hmUZ String accessKeyId = "LTAI5t7bHCvLg8YucRegLG7v"; String accessKeySecret = "wEJLCZTwDV6ArUYMwh61QtlUM3hmUZ"; // 填写Bucket名称,例如examplebucket。 String bucketName = "lizhiqiang-01"; // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 String objectName = UUID.randomUUID()+file.getOriginalFilename(); //上传到oss的文件名称 // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。 // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { InputStream inputStream = file.getInputStream(); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // 设置该属性可以返回response。如果不设置,则返回的response为空。 putObjectRequest.setProcess("true"); // 创建PutObject请求。 PutObjectResult result = ossClient.putObject(putObjectRequest); // 如果上传成功,则返回200。 if(result.getResponse().getStatusCode()==200){ //https://qy165.oss-cn-qingdao.aliyuncs.com/%E7%BE%8E%E5%A5%B3.jpg return "https://"+bucketName+"."+endpoint+"/"+objectName; } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (Exception ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } return null; } }
前端代码
list.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/14 Time: 13:17 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link rel="stylesheet" href="/css/index.css"> <script type="text/javascript" src="/js/index.js"></script> </head> <body> <div id="aaa"> <el-button type="success" @click="dialogVisible = true">添加</el-button> <%--分页组件 size-change:大小改变。每页显示的条数 current-change:当前页面发生改变时触发的事件 current-page: 当前页面 page-sizes: page-size:默认显示的条数 total: 总条数 --%> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[2,10 ,15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> <%--修改数据对话框开始--%> <el-dialog title="修改学生" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose"> <%--修改表单标签--%> <el-form ref="form" :model="myup" label-width="80px"> <%--修改头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2"> <img v-if="imageUrl2" :src="imageUrl2" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--修改头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myup.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myup.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myup.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myup.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <el-button @click="dialogVisible2 = false">取 消</el-button> <el-button type="primary" @click="myupdat">确 定</el-button> </span> </el-dialog> <%--修改数据对话框结束--%> <%--添加数据对话框开始--%> <el-dialog title="添加学生" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <%--添加表单开始--%> <el-form ref="form" :model="myform" label-width="80px"> <%--添加头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--添加头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myform.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myform.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myform.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myform.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <%--添加表单结束--%> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="inset">确 定</el-button> </span> </el-dialog> <%--添加数据对话框结束--%> <%--查询所有数据表格开始--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--查询所有数据表格结束--%> </div> </body> <script> let a = new Vue({ el: "#aaa", data: { //头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 必须使用数组 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, methods: { //修改上传文件之后 handleAvatarSuccess2(res, file) { this.imageUrl2 = res.data; this.myup.headImg = this.imageUrl2; }, //修改上传文件之前 beforeAvatarUpload2(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, //添加上传文件之后 handleAvatarSuccess(res, file) { this.imageUrl = res.data; this.myform.headImg = this.imageUrl; }, //添加上传文件之前 beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, //每页显示条数时触发的事件 handleSizeChange(val) { console.log(`每页 ${val} 条`); this.pageSize = val; this.bbb(); }, //当前页切换时触发的事件 handleCurrentChange(val) { console.log(`当前页: ${val}`); this.currentPage4 = val; this.bbb(); }, //修改学生提交事件 myupdat() { var that = this; axios.post("/student/updat", this.myup).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible2 = false; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }, //添加学生表单确定提交事件 inset() { var that = this; axios.post("/student/inset", this.myform).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible = false; that.$message.success(requs.data.msg) that.myform = ""; that.imageUrl = ""; } else { that.$message.error(requs.data.msg) } }) }, //所有班级信息 getclazz() { var that = this; axios.get("/clazz/list").then(function (requs) { console.log(requs.data); that.clazz1 = requs.data.data; }) }, //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
3.按条件查询功能
脑图
代码
controller层
StudentController
@RequestMapping("/listByPage") @ResponseBody public Requs listByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize, @RequestBody Student student) { PageInfo<Student> page = studentService.queryAll(currentPage, pageSize, student); System.out.println(page); return new Requs(200, "查询所有员工成功", page); }
dao层
StudentDao
List<Student> findAllBylike(Student student);
pojo层
Student
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer sid; private String name; private Integer age; private String sex; private Integer cid; private String headImg; private Clazz clazz; }
Calzz
@Data @AllArgsConstructor @NoArgsConstructor public class Clazz { private Integer id; private String cname; }
service层
StudentService
public interface StudentService { PageInfo<Student> queryAll(Integer currentPage, Integer pageSize,Student student); }
StudentServiceImpl
@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; public PageInfo<Student> queryAll(Integer currentPage, Integer pageSize, Student student) { PageHelper.startPage(currentPage,pageSize); List<Student> all = studentDao.findAllBylike(student); //把查询的结果封装到Page对象中。 PageInfo<Student> pageInfo=new PageInfo(all); System.out.println(pageInfo); return pageInfo; } }
vo层
Requs
@Data @AllArgsConstructor @NoArgsConstructor public class Requs { private Integer code; private String msg; private Object data; }
mepper
StudentMapper
<mapper namespace="com.lzq.dao.StudentDao"> <resultMap id="mystudent" type="com.lzq.pojo.Student" autoMapping="true"> <id property="sid" column="sid"/> <association property="clazz" javaType="com.lzq.pojo.Clazz"> <id property="id" column="id"/> </association> </resultMap> <select id="findAllBylike" resultMap="mystudent"> select s.name, s.age, s.sex, s.cid, s.sid,c.id cid,c.cname,s.headImg from student s join clazz c on s.cid=c.id <where> <if test="name!=null and name!='' "> and name like concat('%',#{name},'%') </if> <if test="cid!=null"> and cid = #{cid} </if> </where> </select> </mapper>
前端页面
min.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/10 Time: 14:06 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <!-- 引入样式 --> <link rel="stylesheet" href="/css/index.css"> <!-- 引入组件库 --> <script type="text/javascript" src="/js/index.js"></script> <style> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409EFF; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 100px; height: 100px; line-height: 100px; text-align: center; } .avatar { width: 100px; height: 100px; display: block; } </style> </head> <body> <div id="aaa"> <%--顶部查询表单开始--%> <el-form :inline="true" :model="myfindAllby" class="demo-form-inline"> <el-form-item label="学生姓名"> <el-input v-model="myfindAllby.name" placeholder="学生姓名"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myfindAllby.cid" placeholder="学生班级"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="chaxun">查询</el-button> <el-button type="primary" @click="chongzhi">重置</el-button> <el-button type="success" @click="mytianjia">添加</el-button> </el-form-item> </el-form> <%--顶部查询表单结束--%> <%--添加数据对话框开始--%> <el-dialog title="添加学生" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <%--添加表单开始--%> <el-form ref="myform" :model="myform" label-width="80px" :rules="rules"> <%--添加头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--添加头像结束--%> <el-form-item label="学生名字" prop="name"> <el-input v-model="myform.name"></el-input> </el-form-item> <el-form-item label="学生年龄" prop="age"> <el-input v-model.number="myform.age"></el-input> </el-form-item> <el-form-item label="学生性别" prop="sex"> <%-- <el-input v-model.number="myform.sex"></el-input>--%> <el-radio v-model="myform.sex" label="男">男</el-radio> <el-radio v-model="myform.sex" label="女">女</el-radio> </el-form-item> <el-form-item label="学生班级" prop="cid"> <el-select v-model="myform.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <%--添加表单结束--%> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="inset">确 定</el-button> </span> </el-dialog> <%--添加数据对话框结束--%> <%--修改数据对话框开始--%> <el-dialog title="修改学生" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose"> <%--修改表单标签--%> <el-form ref="form" :model="myup" label-width="80px"> <%--修改头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2"> <img v-if="imageUrl2" :src="imageUrl2" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--修改头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myup.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myup.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myup.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myup.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <el-button @click="dialogVisible2 = false">取 消</el-button> <el-button type="primary" @click="myupdat">确 定</el-button> </span> </el-dialog> <%--修改数据对话框结束--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--分页组件 size-change:大小改变。每页显示的条数 current-change:当前页面发生改变时触发的事件 current-page: 当前页面 page-sizes: page-size:默认显示的条数 total: 总条数 --%> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[2,10 ,15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> </div> </body> <script> let a = new Vue({ el: "#aaa", //vue变量区 data: { myform: { name: '', age: '', }, //表单验证规则 rules: { name: [ {required: true, message: '请输入学生名字', trigger: 'blur'}, {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'} ], age: [ {required: true, message: '年龄不能为空'}, {type: 'number', message: '年龄必须为数字值'}, ], }, //修改头像地址 imageUrl2: "", //添加头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, //vue方法区 methods: { //点击添加按钮 mytianjia() { //重置添加表单 // this.$refs.myform.resetFields() this.$nextTick(() => { this.$refs.myform.resetFields() }) this.dialogVisible = true this.imageUrl = "" }, //点击查询按钮触发事件 chaxun() { this.currentPage4 = 1; this.bbb(); }, //重置按钮 chongzhi() { this.bbb(); this.myfindAllby = {}; }, //修改上传文件之后 handleAvatarSuccess2(res, file) { this.imageUrl2 = res.data; this.myup.headImg = this.imageUrl2; }, //修改上传文件之前 beforeAvatarUpload2(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, //添加上传文件之后 handleAvatarSuccess(res, file) { this.imageUrl = res.data; this.myform.headImg = this.imageUrl; }, //添加上传文件之前 beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, //每页显示条数时触发的事件 handleSizeChange(val) { console.log(`每页 ${val} 条`); this.pageSize = val; this.bbb(); }, //当前页切换时触发的事件 handleCurrentChange(val) { console.log(`当前页: ${val}`); this.currentPage4 = val; this.bbb(); }, //点击编辑事件 rowStudent(row) { //console.log(student) this.dialogVisible2 = true //this.imageUrl2 = row.headImg; //this.myup = row; //JSON.parse(JSON.stringify(row)) 深拷贝 this.$data.myup = JSON.parse(JSON.stringify(row)) this.$data.imageUrl2 = JSON.parse(JSON.stringify(row.headImg)) }, //修改学生提交事件 myupdat() { var that = this; axios.post("/student/updat", this.myup).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible2 = false; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }, //添加学生表单确定提交事件 inset() { console.log(this) var that = this; this.$refs.myform.validate((valid) => { if (valid) { axios.post("/student/inset", this.myform).then(function (requs) { console.log(111) if (requs.data.code == 200) { that.$nextTick(() => { that.$refs.myform.resetFields() }) that.bbb(); that.dialogVisible = false; that.imageUrl = ""; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) } }); }, //所有班级信息 getclazz() { var that = this; axios.get("/clazz/list").then(function (requs) { console.log(requs.data); that.clazz1 = requs.data.data; }) }, //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
四、完整代码
1.前端代码
list.jsp
<%-- Created by IntelliJ IDEA. User: LIYANGCUNZHUANG Date: 2023/5/10 Time: 14:06 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <!-- 引入样式 --> <link rel="stylesheet" href="/css/index.css"> <!-- 引入组件库 --> <script type="text/javascript" src="/js/index.js"></script> <style> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409EFF; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 100px; height: 100px; line-height: 100px; text-align: center; } .avatar { width: 100px; height: 100px; display: block; } </style> </head> <body> <div id="aaa"> <%--顶部查询表单开始--%> <el-form :inline="true" :model="myfindAllby" class="demo-form-inline"> <el-form-item label="学生姓名"> <el-input v-model="myfindAllby.name" placeholder="学生姓名"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myfindAllby.cid" placeholder="学生班级"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="chaxun">查询</el-button> <el-button type="primary" @click="chongzhi">重置</el-button> <el-button type="success" @click="mytianjia">添加</el-button> </el-form-item> </el-form> <%--顶部查询表单结束--%> <%--添加数据对话框开始--%> <el-dialog title="添加学生" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <%--添加表单开始--%> <el-form ref="myform" :model="myform" label-width="80px" :rules="rules"> <%--添加头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--添加头像结束--%> <el-form-item label="学生名字" prop="name"> <el-input v-model="myform.name"></el-input> </el-form-item> <el-form-item label="学生年龄" prop="age"> <el-input v-model.number="myform.age"></el-input> </el-form-item> <el-form-item label="学生性别" prop="sex"> <%-- <el-input v-model.number="myform.sex"></el-input>--%> <el-radio v-model="myform.sex" label="男">男</el-radio> <el-radio v-model="myform.sex" label="女">女</el-radio> </el-form-item> <el-form-item label="学生班级" prop="cid"> <el-select v-model="myform.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <%--添加表单结束--%> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="inset">确 定</el-button> </span> </el-dialog> <%--添加数据对话框结束--%> <%--修改数据对话框开始--%> <el-dialog title="修改学生" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose"> <%--修改表单标签--%> <el-form ref="form" :model="myup" label-width="80px"> <%--修改头像开始--%> <el-table-column> <el-upload class="avatar-uploader" action="/student/alyun" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2"> <img v-if="imageUrl2" :src="imageUrl2" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-table-column> <%--修改头像结束--%> <el-form-item label="学生名字"> <el-input v-model="myup.name"></el-input> </el-form-item> <el-form-item label="学生年龄"> <el-input v-model="myup.age"></el-input> </el-form-item> <el-form-item label="学生性别"> <el-input v-model="myup.sex"></el-input> </el-form-item> <el-form-item label="学生班级"> <el-select v-model="myup.cid" placeholder="请选择你的班级" style="width: 100%"> <el-option v-for="c in clazz1" :label="c.cname" :value="c.id"></el-option> </el-select> </el-form-item> </el-form> <el-button @click="dialogVisible2 = false">取 消</el-button> <el-button type="primary" @click="myupdat">确 定</el-button> </span> </el-dialog> <%--修改数据对话框结束--%> <el-table :data="aa" border style="width: 100%"> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="headImg" label="头像" width="180"> <template slot-scope="scope"> <img :src="scope.row.headImg" width="100"/> </template> </el-table-column> <el-table-column prop="age" label="年龄" width="180"> </el-table-column> <el-table-column prop="sex" label="性别"> </el-table-column> <el-table-column prop="sid" label="编号"> </el-table-column> <el-table-column prop="clazz.cname" label="班级"> </el-table-column> <el-table-column fixed="right" label="操作" width="200"> <template slot-scope="scope"> <el-button type="primary" icon="el-icon-edit" size="small" @click="rowStudent(scope.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-delete" size="small" @click="mydel(scope.row.sid)">删除 </el-button> </template> </el-table-column> </el-table> <%--分页组件 size-change:大小改变。每页显示的条数 current-change:当前页面发生改变时触发的事件 current-page: 当前页面 page-sizes: page-size:默认显示的条数 total: 总条数 --%> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[2,10 ,15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> </div> </body> <script> let a = new Vue({ el: "#aaa", //vue变量区 data: { myform: { name: '', age: '', }, //表单验证规则 rules: { name: [ {required: true, message: '请输入学生名字', trigger: 'blur'}, {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'} ], age: [ {required: true, message: '年龄不能为空'}, {type: 'number', message: '年龄必须为数字值'}, ], }, //修改头像地址 imageUrl2: "", //添加头像地址 imageUrl: "", //局部查询表单数据 myfindAllby: {}, //当前网页显示的数据数量 pageSize: 2, //当前页码 currentPage4: 1, //分页总条数 total: 0, //查询总数居 aa: [], //添加学生数据弹出对话框 dialogVisible: false, //修改学生数据弹出对话框 dialogVisible2: false, //添加学生表单对象数据 myform: {}, //修改学生表单对象数据 myup: {}, //班级信息 clazz1: [], }, //打开页面就会加载 created created() { this.bbb(); this.getclazz(); }, //vue方法区 methods: { //点击添加按钮 mytianjia() { //重置添加表单 // this.$refs.myform.resetFields() this.$nextTick(() => { this.$refs.myform.resetFields() }) this.dialogVisible = true this.imageUrl = "" }, //点击查询按钮触发事件 chaxun() { this.currentPage4 = 1; this.bbb(); }, //重置按钮 chongzhi() { this.bbb(); this.myfindAllby = {}; }, //修改上传文件之后 handleAvatarSuccess2(res, file) { this.imageUrl2 = res.data; this.myup.headImg = this.imageUrl2; }, //修改上传文件之前 beforeAvatarUpload2(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, //添加上传文件之后 handleAvatarSuccess(res, file) { this.imageUrl = res.data; this.myform.headImg = this.imageUrl; }, //添加上传文件之前 beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, //每页显示条数时触发的事件 handleSizeChange(val) { console.log(`每页 ${val} 条`); this.pageSize = val; this.bbb(); }, //当前页切换时触发的事件 handleCurrentChange(val) { console.log(`当前页: ${val}`); this.currentPage4 = val; this.bbb(); }, //点击编辑事件 rowStudent(row) { //console.log(student) this.dialogVisible2 = true //this.imageUrl2 = row.headImg; //this.myup = row; //JSON.parse(JSON.stringify(row)) 深拷贝 this.$data.myup = JSON.parse(JSON.stringify(row)) this.$data.imageUrl2 = JSON.parse(JSON.stringify(row.headImg)) }, //修改学生提交事件 myupdat() { var that = this; axios.post("/student/updat", this.myup).then(function (requs) { if (requs.data.code == 200) { that.bbb(); that.dialogVisible2 = false; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }, //添加学生表单确定提交事件 inset() { console.log(this) var that = this; this.$refs.myform.validate((valid) => { if (valid) { axios.post("/student/inset", this.myform).then(function (requs) { console.log(111) if (requs.data.code == 200) { that.$nextTick(() => { that.$refs.myform.resetFields() }) that.bbb(); that.dialogVisible = false; that.imageUrl = ""; that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) } }); }, //所有班级信息 getclazz() { var that = this; axios.get("/clazz/list").then(function (requs) { console.log(requs.data); that.clazz1 = requs.data.data; }) }, //所有学生信息 bbb() { var that = this; //如果使用json对象必须使用post提交 axios.post("/student/listByPage?currentPage=" + this.currentPage4 + "&pageSize=" + this.pageSize, this.myfindAllby).then(function (requs) { if (requs.data.code == 200) { console.log(requs) that.aa = requs.data.data.list; that.total = requs.data.data.total; } else { alert("查询失败") } console.log(requs) }) }, //删除学生信息 mydel(sid) { this.$confirm('确定删除此条学生信息?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { var that = this axios.get("/student/del?id=" + sid).then(function (requs) { if (requs.data.code == 200) { that.currentPage4 = 1; that.bbb(); that.$message.success(requs.data.msg) } else { that.$message.error(requs.data.msg) } }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }); }); } } }) </script> </html>
2.controller层
StudentController
package com.lzq.controller; import com.github.pagehelper.PageInfo; import com.lzq.pojo.Student; import com.lzq.service.StudentService; import com.lzq.uito.UploadUtil; import com.lzq.vo.Requs; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.util.List; @Controller @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @RequestMapping("/aaa") @ResponseBody public Requs findAll() { List<Student> all = studentService.findAll(); if (all.size() == 0) { return new Requs(500, "查询失败", null); } return new Requs(200, "查询成功", all); } @RequestMapping("/del") @ResponseBody public Requs delById(Integer id) { Integer integer = studentService.delById(id); if (integer == 0) { return new Requs(500, "操作失败", null); } return new Requs(200, "删除成功", null); } @RequestMapping("/inset") @ResponseBody public Requs inset(@RequestBody Student student) { System.out.println(student); Integer inset = studentService.inset(student); if (inset == 0) { return new Requs(500, "添加失败", null); } return new Requs(200, "添加成功", null); } @RequestMapping("/updat") @ResponseBody public Requs updat(@RequestBody Student student) { System.out.println(student); Integer integer = studentService.updatAll(student); if (integer == 0) { return new Requs(500, "修改失败", null); } return new Requs(200, "修改成功", null); } @RequestMapping("/listByPage") @ResponseBody public Requs listByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize, @RequestBody Student student) { PageInfo<Student> page = studentService.queryAll(currentPage, pageSize, student); System.out.println(page); return new Requs(200, "查询所有员工成功", page); } @RequestMapping("/alyun") @ResponseBody public Requs aaa(MultipartFile file) { System.out.println(file); String pash = UploadUtil.upload(file); if (pash == null) { return new Requs(500, "上传失败", null); } return new Requs(200, "上传成功", pash); } }
ClazzController
package com.lzq.controller; import com.lzq.pojo.Clazz; import com.lzq.service.ClazzService; import com.lzq.vo.Requs; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("/clazz") public class ClazzController { @Autowired private ClazzService clazzService; @RequestMapping("/list") @ResponseBody public Requs findAll(){ List<Clazz> all = clazzService.findAll(); System.out.println(all); if (all.size()==0){ return new Requs(500,"查询班级失败",null); }else { return new Requs(200,"查询班级成功",all); } } }
3.dao层
StudnetDao
package com.lzq.dao; import com.lzq.pojo.Student; import java.util.List; public interface StudentDao { List<Student> findAll(); Integer delBySid(Integer id); Integer insertAll(Student student); Integer updateAll(Student student); List<Student> findAllBylike(Student student); }
ClazzDao
package com.lzq.dao; import com.lzq.pojo.Clazz; import java.util.List; public interface ClazzDao { List<Clazz> findAll(); }
4.pojo层
Studnet
package com.lzq.pojo; import com.lzq.pojo.Clazz; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Student { private String name; private Integer age; private String sex; private Integer cid; private Integer sid; private Clazz clazz; private String headImg; }
Clazz
package com.lzq.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Clazz { private Integer id; private String cname; }
5.service层
StudentService
package com.lzq.service; import com.github.pagehelper.PageInfo; import com.lzq.pojo.Student; import org.springframework.stereotype.Service; import java.util.List; public interface StudentService { List<Student> findAll(); Integer delById(Integer id); Integer inset(Student student); Integer updatAll(Student student); PageInfo<Student> queryAll(Integer currentPage, Integer pageSize,Student student); }
ClazzService
package com.lzq.service; import com.lzq.pojo.Clazz; import java.util.List; public interface ClazzService { List<Clazz> findAll(); }
StudnetServiceImpl
package com.lzq.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lzq.dao.StudentDao; import com.lzq.pojo.Student; import com.lzq.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public List<Student> findAll() { List<Student> all = studentDao.findAll(); return all; } @Override public Integer delById(Integer id) { Integer integer = studentDao.delBySid(id); return integer; } @Override public Integer inset(Student student) { Integer integer = studentDao.insertAll(student); return integer; } @Override public Integer updatAll(Student student) { Integer integer = studentDao.updateAll(student); return integer; } public PageInfo<Student> queryAll(Integer currentPage, Integer pageSize, Student student) { PageHelper.startPage(currentPage,pageSize); List<Student> all = studentDao.findAllBylike(student); //把查询的结果封装到Page对象中。 PageInfo<Student> pageInfo=new PageInfo(all); System.out.println(pageInfo); return pageInfo; } }
ClazzServiceImpl
package com.lzq.service.impl; import com.lzq.dao.ClazzDao; import com.lzq.pojo.Clazz; import com.lzq.service.ClazzService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ClazzServiceImpl implements ClazzService { @Autowired private ClazzDao clazzDao; @Override public List<Clazz> findAll() { List<Clazz> all = clazzDao.findAll(); return all; } }
6.vo层
Requs
package com.lzq.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Requs { private Integer code; private String msg; private Object data; }
7.util层
UploadUtil
package com.lzq.uito; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.util.UUID; public class UploadUtil { public static String upload(MultipartFile file){ // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-beijing.aliyuncs.com"; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 //LTAI5t7bHCvLg8YucRegLG7v //wEJLCZTwDV6ArUYMwh61QtlUM3hmUZ String accessKeyId = "LTAI5t7bHCvLg8YucRegLG7v"; String accessKeySecret = "wEJLCZTwDV6ArUYMwh61QtlUM3hmUZ"; // 填写Bucket名称,例如examplebucket。 String bucketName = "lizhiqiang-01"; // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 String objectName = UUID.randomUUID()+file.getOriginalFilename(); //上传到oss的文件名称 // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。 // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { InputStream inputStream = file.getInputStream(); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // 设置该属性可以返回response。如果不设置,则返回的response为空。 putObjectRequest.setProcess("true"); // 创建PutObject请求。 PutObjectResult result = ossClient.putObject(putObjectRequest); // 如果上传成功,则返回200。 if(result.getResponse().getStatusCode()==200){ //https://qy165.oss-cn-qingdao.aliyuncs.com/%E7%BE%8E%E5%A5%B3.jpg return "https://"+bucketName+"."+endpoint+"/"+objectName; } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (Exception ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } return null; } }
8.mapper
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lzq.dao.StudentDao"> <resultMap id="mystudent" type="com.lzq.pojo.Student" autoMapping="true"> <id property="sid" column="sid" /> <association property="clazz" javaType="com.lzq.pojo.Clazz" autoMapping="true"> <id property="id" column="cid"/> <result property="cname" column="cname"/> </association> </resultMap> <insert id="insertAll"> insert into student values (#{name},#{age},#{sex},#{cid},null,#{headImg}) </insert> <update id="updateAll"> update student set name=#{name},age=#{age},sex=#{sex},cid=#{cid} where sid=#{sid} </update> <delete id="delBySid"> delete from student where sid=#{id} </delete> <select id="findAll" resultMap="mystudent" > select s.name, s.age, s.sex, s.cid, s.sid,c.id cid,c.cname,s.headImg from student s join clazz c on s.cid=c.id </select> <select id="findAllBylike" resultMap="mystudent"> select s.name, s.age, s.sex, s.cid, s.sid,c.id cid,c.cname,s.headImg from student s join clazz c on s.cid=c.id <where> <if test="name!=null and name!='' "> and name like concat('%',#{name},'%') </if> <if test="cid!=null"> and cid = #{cid} </if> </where> </select> </mapper>
ClazzMapper
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lzq.dao.ClazzDao"> <select id="findAll" resultType="com.lzq.pojo.Clazz"> select * from clazz </select> </mapper>