pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.luo</groupId>
<artifactId>september-examination</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>september-examination</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--数据库驱动-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--web开发予以支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--操作数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--偷懒专用-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!--用来处理文件上传的一个通用工具类-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--分页-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.5</version>
</dependency>
<!--thymeleaf,我们都是基于3.x开发-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--当引入这个jar包的时候 默认的静态根目录变成了templates-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
pojo
package com.luo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
mapper
package com.luo.mapper;
import com.luo.pojo.User;
import com.luo.util.PageUtil;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper //这个注解表示这是一个Mybatis的mapper类 还可以使用@MapperScan("扫描包的路径")
@Repository//@Repository的功能是将数据访问层(Dao层)的类识别并标注为SpringBean,具体方式为直接在DAO类上标注即可。
public interface UserMapper {
List<User> queryUser();
int updateUser(User user);
int deleteUser(@Param("id") int id);
int AddUser(User user);
/**
* 分页查询
*/
List<User> queryBookByAjax(@Param("pageUtil") PageUtil<User> pageUtil);
/**
* 查询总条数
*/
int countBooks();
}
service
package com.luo.service;
import com.luo.pojo.User;
import com.luo.util.PageUtil;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserService {
List<User> queryUser();
int updateUser(User user);
int deleteUser(@Param("id") int id);
int AddUser(User user);
/**
* 分页查询
*/
PageUtil<User> queryBookByAjax(@Param("pageUtil") PageUtil<User> pageUtil);
/**
* 查询总条数
*/
int countBooks();
}
package com.luo.service;
import com.luo.mapper.UserMapper;
import com.luo.pojo.User;
import com.luo.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public List<User> queryUser() {
return userMapper.queryUser();
}
@Override
public int updateUser(User user) {
return userMapper.updateUser(user);
}
@Override
public int deleteUser(int id) {
return userMapper.deleteUser(id);
}
@Override
public int AddUser(User user) {
return userMapper.AddUser(user);
}
@Override
public PageUtil<User> queryBookByAjax(PageUtil<User> pageUtil) {
List<User> list = userMapper.queryBookByAjax(pageUtil);
pageUtil.setList(list);
return pageUtil;
}
@Override
public int countBooks() {
return userMapper.countBooks();
}
}
controller
package com.luo.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luo.pojo.User;
import com.luo.service.UserService;
import com.luo.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
//构造器注入
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping("/queryUser")
@ResponseBody
public String queryUser(Model model) throws JsonProcessingException {
List<User> list = userService.queryUser();
for (User user : list) {
System.out.println(user);
}
model.addAttribute("list", list);
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(list);
return string;
}
//跳转到index.html页面
@RequestMapping("/intoindex")
public String intoIndex() {
return "index";
}
//修改方法
@RequestMapping("/updateUser")
@ResponseBody
public String updateUser(User user) throws JsonProcessingException {
int number = userService.updateUser(user);
ObjectMapper mapper = new ObjectMapper();
String num = mapper.writeValueAsString(number);
return num;
}
//删除
@RequestMapping("/deleteUser")
@ResponseBody
public String deleteUser(int id) throws JsonProcessingException {
int number = userService.deleteUser(id);
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(number);
return string;
}
//跳转到新增页面
@RequestMapping("/toaddUser")
public String toaddUser() {
return "addUser";
}
//新增
@RequestMapping("/AddUser")
public String AddUser(User user) {
int i = userService.AddUser(user);
if (i > 0) {
return "index";
}
return "addUser";
}
//分页
@RequestMapping("/queryBookByAjax")
@ResponseBody
public String queryBookByAjax(int index) throws JsonProcessingException {
PageUtil<User> pageUtil = new PageUtil<User>();
//查询当前表的总记录数
int i = userService.countBooks();
//每页显示几条数据
pageUtil.setPageSize(3);
//给总页数赋值
pageUtil.setTotalCount(i);
//给当前页赋值
pageUtil.setCurrPageNo(index);
//调用查询方法
pageUtil = userService.queryBookByAjax(pageUtil);
//查询出来的结果转化为Json格式的字符串
ObjectMapper mapper = new ObjectMapper();
String message = mapper.writeValueAsString(pageUtil);
//返回
return message;
}
//进入index1页面
@RequestMapping("/toindex")
public String toindex() {
return "index1";
}
//上传文件
@PostMapping("/fileUpload")
@ResponseBody
public String FileUpload(@RequestParam("file") MultipartFile[] multipartFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
for (int i = 0; i < multipartFile.length; i++) {
if (multipartFile[i].getSize() > 0 && !multipartFile[i].isEmpty()) {
//获取文件的名称
String originalFilename = multipartFile[i].getOriginalFilename();
// 这里需要注意的是ApplicationHome是属于SpringBoot的类
// 获取项目下resources/static/img路径
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//读取jar包中的文件流。
String driPath = applicationHome.getSource().getParentFile().toString();
String url = driPath + "\\classes\\img\\";
System.out.println(url);
//创建一个文件 存储位置是tomcat的img里面
File file = new File(url + "/" + originalFilename);
System.out.println("文件路径是:" + file);
multipartFile[i].transferTo(file);
} else {
return "上传失败!";
}
}
return "上传成功!";
}
}
userMapper.xml
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.luo.mapper.UserMapper">
<select id="queryUser" resultType="User">
select * from user
</select>
<update id="updateUser" parameterType="User">
update user set name =#{name},pwd=#{pwd} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
<insert id="AddUser" parameterType="User">
insert user(id,name,pwd) values (null,#{name},#{pwd})
</insert>
<select id="queryBookByAjax" parameterType="com.luo.util.PageUtil" resultType="User">
select * from user limit ${(pageUtil.currPageNo-1)*pageUtil.pageSize},#{pageUtil.pageSize}
</select>
<select id="countBooks" resultType="int">
select count(*) from user
</select>
</mapper>
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
[v-clock]{
display: none;
}
</style>
</head>
<body>
<div class="container" id="vue">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户列表 —— 显示所有用户</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="/toaddUser">新增</a>
<a href="#" class="btn btn-primary" v-on:click="ShowUpload">上传文件</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>id</th>
<td>用户名</td>
<th>密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="info in info.listUser">
<td>{{info.id}}</td>
<td>{{info.name}}</td>
<td>{{info.pwd}}</td>
<td><a href="#" v-on:click="showUpdate(info)">修改</a>||<a href="#" v-on:click="deleteUser(info.id)">删除</a></td>
</tr>
</tbody>
</table>
<a href="#" v-on:click="init">首页</a>
<a href="#" v-on:click="Show(-1)">上一页</a>
<a href="#" v-on:click="Show(1)">下一页</a>
<a href="#" v-on:click="totalPageCount1">尾页</a>
<div v-if="info.showUpdateFalge" class="col-md-12 column">
<hr>
<table border="2px">
<tr><th>用户名</th><td><input type="text" v-model="info.udUser.name"></td></tr>
<tr><th>密码</th><td><input type="text" v-model="info.udUser.pwd"></td></tr>
<tr><th>操作</th><td><input type="button" value="修改" v-on:click="update()"></td></tr>
</table>
</div>
<div v-if="this.info.showFileUpload" class="col-md-12 column">
<input type="file" name="file" id="fileInput">
<button v-on:click="fileUpload">上传</button>
</div>
</div>
</div>
</div>
</body>
<script>
let vm=new Vue({
el: "#vue",
//data:属性:vm
data(){
//请求的返回参数合适,必须和json字符串一样
return{
info: {
//这个是返回过来的json对象
listUser: [],
user: {},
showUpdateFalge: false,
udUser: {},
sureDelBox: '',
index: 1,
totalPageCount: 0,
showFileUpload: false
}
}
},
mounted(){//钩子函数,链式编程 ES6新特性。
var index=this.info.index;
axios.get('/queryBookByAjax?index='+index).then(response=>{
this.info.listUser=response.data.list;
this.info.index=response.data.currPageNo;
this.info.totalPageCount=response.data.totalPageCount;
});
}
,methods: {
queryUser: function (index) {
this.info.index=index;
axios.get('/queryBookByAjax?index='+index).then(response=>{
this.info.listUser=response.data.list;
this.info.index=response.data.currPageNo;
this.info.totalPageCount=response.data.totalPageCount;
});
}
//显示修改方法。
,showUpdate: function (user) {
this.info.showUpdateFalge=true; //显示 修改的div
this.info.udUser=user; // 把修改哪一行对象 赋值。
},
//修改方法
update: function () {
axios.get('/updateUser',{params:this.info.udUser}).then(response=>{
this.info.showUpdateFalge=false; //修改完毕后 隐藏div
if (response.data==0){
alert("失败了!")
}else{
this.queryUser();//再查询一遍
}
});
},
deleteUser: function (id) {
axios.get('/deleteUser?id='+id).then(response=>{
if (response.data==0){
alert("失败了!");
}else{
this.queryUser();//再查询一遍5
}
});
},init: function () {//首页
this.info.index=1;
this.queryUser(this.info.index);
},totalPageCount1: function () {//尾页
var index= this.info.index;
index= this.info.totalPageCount;
this.queryUser(index);
},Show: function (number) {//上一页下一页
this.info.index=this.info.index+number;
if (this.info.index<=0){
this.info.index=1;
}
if (this.info.index>=this.info.totalPageCount){
this.info.index=this.info.totalPageCount;
}
this.queryUser(this.info.index);
},
fileUpload: function () {//上传文件
let inputElement = document.getElementById("fileInput");
console.log(inputElement);
let param = new FormData(); // 创建form对象
param.append("file",inputElement.files[0]); // 通过append向form对象添加数据
let config = {
headers: { "Content-Type":"multipart/form-data" }
};
axios.post("/fileUpload", param, config)
.then(res => {
if (res.data==="上传成功!"){
alert("上传成功!");
this.info.showFileUpload=false; //上传成功关闭div
}else{
alert("上传失败!");
}
});
},ShowUpload: function () {
//显示上传文件div
this.info.showFileUpload=true;
}
}
});
</script>
</html>
新增页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
<div>
<table border="2px">
<form action="/AddUser">
<tr><th>用户名</th><td><input type="text" name="name"></td></tr>
<tr><th>密码</th><td><input type="text" name="pwd"></td></tr>
<tr><th>操作</th><td><input type="submit" value="新增"></td></tr>
</form>
</table>
</div>
</center>
</body>
</html>
效果图