1.SSM整合
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 10:14
*/
@Configuration
@ComponentScan({"com.itheima.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=169527
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 10:13
*/
@Configuration
public class JdbcConfig {
// 可以调用的原因,Spring已经加载了
//@PropertySource("classpath:jdbc.properties")
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean // 注册为bean类,以使Spring进行管理
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds=new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
4.创建MybatisConfig配置类
package com.itheima.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 10:13
*/
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("co.itheima.entity");
return factoryBean;
}
@Bean // 注册到Spring后方法的名称就会变黄高亮
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.itheima.dao");
return mapperScannerConfigurer;
}
}
5.创建SpringMVC配置类
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 10:13
*/
@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMVCConfig {
}
6 :创建Web项目入口配置类
package com.itheima.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 15:59
*/
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
// 对于root加载的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{ SpringConfig.class};
}
//对于Web容器加载的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMVCConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
功能模块开发
1.创建数据库以及表
CREATE DATABASE ssm_db CHARACTER SET utf8;
USE ssm_db;
CREATE TABLE tbl_book( id INT PRIMARY KEY AUTO_INCREMENT,
TYPE VARCHAR(20),
NAME VARCHAR(50),
description VARCHAR(255) );
INSERT INTO `tbl_book`(`id`,`type`,`name`,`description`) VALUES (1,'计算机理 论','Spring实战 第五版','Spring入门经典教程,深入理解Spring原理技术内幕'),
(2,'计算机理 论','Spring 5核心原理与30个类手写实践','十年沉淀之作,手写Spring精华思想'),
(3,'计算机理 论','Spring 5设计模式','深入Spring源码刨析Spring源码中蕴含的10大设计模式'),
(4,'计算机 理论','Spring MVC+Mybatis开发从入门到项目实战','全方位解析面向Web应用的轻量级框架,带你 成为Spring MVC开发高手'),
(5,'计算机理论','轻量级Java Web企业应用实战','源码级刨析 Spring框架,适合已掌握Java基础的读者'),
(6,'计算机理论','Java核心技术 卷Ⅰ 基础知识(原书 第11版)','Core Java第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新'),(7,'计算 机理论','深入理解Java虚拟机','5个纬度全面刨析JVM,大厂面试知识点全覆盖'),
(8,'计算机理 论','Java编程思想(第4版)','Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉'), (9,'计算机理论','零基础学Java(全彩版)','零基础自学编程的入门图书,由浅入深,详解Java语言 的编程思想和核心技术'),
(10,'市场营销','直播就这么做:主播高效沟通实战指南','李子柒、李佳 奇、薇娅成长为网红的秘密都在书中'),(11,'市场营销','直播销讲实战一本通','和秋叶一起学系列网 络营销书籍'),
(12,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的 书,10堂课轻松实现带货月入3W+');
2 编写模型类
package com.itheima.entity;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:11
*/
public class Book {
private Integer id;
private String type;
private String name;
private String description;
public Book() {
}
public Book(Integer id, String type, String name, String description) {
this.id = id;
this.type = type;
this.name = name;
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package com.itheima.dao;
import com.itheima.entity.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:14
*/
public interface BookDao {
// 写法1
// @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
//写法2 第一个type是表的字段名,第二个type.#{type}是book的属性
@Insert("insert into tbl_book(type,name,description) values(#{type},#{name},#{description})")
public void save(Book book);
@Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
public void update(Book book);
@Delete("delete from tbl_book where id=#{id}")
public void delete(Integer id);
@Select("select * from tbl_book where id=#{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List<Book> getAll();
}
package com.itheima.service;
import com.itheima.entity.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:15
*/
@Transactional
public interface BookService {
/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);
/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);
/**
* 删除按照id
* @param id
* @return
*/
public boolean delete(Integer id);
/**
* 根据ID查询
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查询所有
* @return
*/
public List<Book> getAll();
}
BookServiceImpl
package com.itheima.service.impl;
import com.itheima.dao.BookDao;
import com.itheima.entity.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:15
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public boolean save(Book book) {
bookDao.save(book);
return true;
}
@Override
public boolean update(Book book) {
bookDao.update(book);
return true;
}
@Override
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
@Override
public Book getById(Integer id) {
return bookDao.getById(id);
}
@Override
public List<Book> getAll() {
return bookDao.getAll();
}
}
5 编写Contorller类
package com.itheima.controller;
import com.itheima.entity.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:15
*/
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book){
return bookService.save(book);
}
@PutMapping
public boolean update( @RequestBody Book book){
return bookService.update(book);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable("id") Integer id){
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable("id") Integer id){
return bookService.getById(id);
}
@GetMapping
public List<Book> getAll(){
return bookService.getAll();
}
}
6 单元测试
package com.itheima.service;
import com.itheima.config.SpringConfig;
import com.itheima.entity.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 20:50
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById(){
Book book = bookService.getById(1);
System.out.println(book);
}
@Test
public void testGetAll(){
List<Book> books = bookService.getAll();
books.forEach(book -> {
System.out.println(book);
});
}
}
修改
删除
查询单个
查询所有
结果封装
package com.itheima.controller;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 21:42
*/
public class Result {
private Object data;
private Integer code;
private String msg;
public Result() {
}
public Result(Object data, Integer code, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Result(Object data, Integer code) {
this.data = data;
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
状态码
package com.itheima.controller;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 21:45
*/
// 状态码
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
}
修改Controller中的返回值:
package com.itheima.controller;
import com.itheima.entity.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:15
*/
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book){
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
}
@PutMapping
public Result update( @RequestBody Book book){
boolean flag = bookService.update(book);
return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag) ;
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable("id") Integer id){
boolean delete = bookService.delete(id);
return new Result(delete?Code.DELETE_OK:Code.DELETE_ERR,delete);
}
@GetMapping("/{id}")
public Result getById(@PathVariable("id") Integer id){
Book book = bookService.getById(id);
Integer code= book!=null?Code.GET_OK:Code.GET_ERR;
String msg= book!=null?"":"数据查询失败,请重试";
return new Result(book,code,msg);
}
@GetMapping
public Result getAll(){
List<Book> books = bookService.getAll();
Integer code= books!=null?Code.GET_OK:Code.GET_ERR;
String msg= books!=null?"":"数据查询失败,请重试";
return new Result(books,code,msg);
}
}
Postman工具测试:
添加单个图书成功:
查询单个成功
查询单个失败:
查询所有
3,统一异常处理
@GetMapping("/{id}")
public Result getById(@PathVariable("id") Integer id) {
//手动添加一个错误信息
if (id == 1) {
int i = 1 / 0;
}
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? "" : "数据查询失败,请重试";
return new Result(book, code, msg);
}
当postman查询id=1的结果的时候:
前端接收到这个信息后和之前约定的格式不一致,这个问题该如何解决?在解决问题之前,先来看下异常的种类及出现异常的原因:
package com.itheima.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/5 15:02
*/
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class)
public Result doException(Exception ex){
System.out.println("嘿嘿,异常哪里跑!!");
return new Result(666,null);
}
}
知识点:
package com.itheima.exception;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/5 15:21
*/
public class BusinessException extends RuntimeException{
private Integer code;
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
package com.itheima.exception;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/5 15:21
*/
public class SystemException extends RuntimeException{
private Integer code;
public SystemException( Integer code,String message) {
super(message);
this.code = code;
}
public SystemException(Integer code,String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
@Override
public Book getById(Integer id) {
if(id==1){
throw new BusinessException(Code.BUSINESS_ERR,"请不要用你的技术挑战我的耐性");
}
//将可能出现的异常进行自定义包装,转换为自定义异常
try{
int i=1/0;
}catch (Exception e){
throw new SystemException(Code.SYSTEM_ERR,"服务器访问超时,请重试",e);
}
return bookDao.getById(id);
}
package com.itheima.controller;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/5 15:02
*/
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex) {
// 记录日志
//发送消息给运维
//发送邮件给开发人员
return new Result(ex.getCode(), null, ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex) {
return new Result(ex.getCode(), null, ex.getMessage());
}
@ExceptionHandler(Exception.class)
public Result doException (Exception ex){
// 记录日志
//发送消息给运维
//发送邮件给开发人员
System.out.println("嘿嘿,异常哪里跑!!");
return new Result(Code.SYSTEM_UNKNOWN_ERR, null,"系统繁忙,请稍后再试");
}
}
如果传入的是其他参数,会报SystemException
4,前后台协议联调
4.1 环境准备
加载前台页面到Webapp后,因为添加了静态资源,SpringMVC会拦截,所有需要在SpringConfig的配置类中将静态资源进行放行。新建SpringMvcSupport:
package com.itheima.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/5 22:57
*/
@Configuration
public class SpringMVCSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
并且需要在SpringMVCConfig的配置类中扫描一下:
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 10:13
*/
@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMVCConfig {
}
//列表
getAll() {
//发送Ajax请求
axios.get("/books").then((res)=>{
this.dataList=res.data.data;
})
},
结果:
4.3 添加功能
//弹出添加窗口
handleCreate() {
this.dialogFormVisible=true;
},
//重置表单
resetForm() {
},
//添加
handleAdd () {
//发送Ajax请求
axios.post("/books",this.formData).then((res)=>{
// 如果插入成功,则关闭弹层,显示数据
this.dialogFormVisible=false;
this.getAll();
})
},
//添加
handleAdd () {
//发送Ajax请求
axios.post("/books",this.formData).then((res)=>{
// 如果插入成功,则关闭弹层,显示数据
if(res.data.code==20011){
this.dialogFormVisible=false;
this.$message.success("添加成功")
}else if(res.data.code==20010){
this.$message.error("添加失败")
}else{
this.$message.error(res.data.msg)
}
}).finally(()=>{
this.getAll();
})
},
package com.itheima.dao;
import com.itheima.entity.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/5/22 16:14
*/
public interface BookDao {
// 写法1
//@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
//写法2 第一个type是表的字段名,第二个type.#{type}是book的属性
@Insert("insert into tbl_book(type,name,description) values(#{type},#{name},#{description})")
public int save(Book book);
@Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
public int update(Book book);
@Delete("delete from tbl_book where id=#{id}")
public int delete(Integer id);
@Select("select * from tbl_book where id=#{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List<Book> getAll();
}
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable("id") Integer id) {
boolean delete = bookService.delete(id);
return new Result(delete ? Code.DELETE_OK : Code.DELETE_ERR, delete);
}
处理完新增后,会发现新增还存在一个问题.新增成功后,再次点击新增按钮会发现之前的数据还存在,这个时候就需要在新增的时候将表单内容清空。
//弹出添加窗口
handleCreate() {
this.dialogFormVisible=true;
resetForm();
},
//重置表单
resetForm() {
this.formData={};
},
scope.row代表的是当前行的行数据,也就是说,scope.row就是选中行对应的json数据,如下:
//弹出编辑窗口
handleUpdate(row) {
//console.log(row);//row.id
//查询数据,根据id查询
axios.get("/books"+row.id).then((res)=>{
if(res.data.code==20041){
this.formData=res.data.data;
this.dialogFormVisible4Edit=true;
}else{
this.$message.error(res.data.msg);
}
})
//展示弹窗,在弹窗中加载数据
},
//编辑
handleEdit() {
//发送Ajax请求
axios.put("/books",this.formData).then((res)=>{
// 如果插入成功,则关闭弹层,显示数据
if(res.data.code==20031){
this.dialogFormVisible=false;
this.$message.success("修改成功")
}else if(res.data.code==20030){
this.$message.error("修改失败")
}else{
this.$message.error(res.data.msg)
}
}).finally(()=>{
this.getAll();
});
},
4.6 删除功能
// 删除
handleDelete(row) {
//1.弹出提示框
this.$confirm("此操作永久删除当前的数据,是否继续?", "提示", {
type: "info"
}).then(() => {
//2.做删除业务
//查询数据,根据id查询
axios.delete("/books/" + row.id).then((res) => {
// console.log(res.data.data);
if (res.data.code == 20021) {
//展示弹层,加载数据
this.$message.success("删除成功");
} else {
this.$message.error("删除失败");
}
});
}).catch(() => {
//3.取消删除
this.$message.info("取消删除操作");
}).finally(() => {
this.getAll();
});
效果:
books.html完整的前端代码:
<!DOCTYPE html>
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SpringMVC案例</title>
<meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
<!-- 引入样式 -->
<link rel="stylesheet" href="../plugins/elementui/index.css">
<link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/style.css">
</head>
<body class="hold-transition">
<div id="app">
<div class="content-header">
<h1>图书管理</h1>
</div>
<div class="app-container">
<div class="box">
<div class="filter-container">
<el-input placeholder="图书名称" v-model="pagination.queryString" style="width: 200px;"
class="filter-item"></el-input>
<el-button @click="getAll()" class="dalfBut">查询</el-button>
<el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
</div>
<el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
<el-table-column type="index" align="center" label="序号"></el-table-column>
<el-table-column prop="type" label="图书类别" align="center"></el-table-column>
<el-table-column prop="name" label="图书名称" align="center"></el-table-column>
<el-table-column prop="description" label="描述" align="center"></el-table-column>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
<el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 新增标签弹层 -->
<div class="add-form">
<el-dialog title="新增图书" :visible.sync="dialogFormVisible">
<el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right"
label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="图书类别" prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="图书名称" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="handleAdd()">确定</el-button>
</div>
</el-dialog>
</div>
<!-- 编辑标签弹层 -->
<div class="add-form">
<el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit">
<el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right"
label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="图书类别" prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="图书名称" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible4Edit = false">取消</el-button>
<el-button type="primary" @click="handleEdit()">确定</el-button>
</div>
</el-dialog>
</div>
</div>
</div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
pagination: {},
dataList: [],//当前页要展示的列表数据
formData: {},//表单数据
dialogFormVisible: false,//控制表单是否可见
dialogFormVisible4Edit: false,//编辑表单是否可见
rules: {//校验规则
type: [{required: true, message: '图书类别为必填项', trigger: 'blur'}],
name: [{required: true, message: '图书名称为必填项', trigger: 'blur'}]
}
},
//钩子函数,VUE对象初始化完成后自动执行
created() {
this.getAll();
},
methods: {
//列表
getAll() {
//发送ajax请求
axios.get("/books").then((res) => {
this.dataList = res.data.data;
});
},
//弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
//重置表单
resetForm() {
this.formData = {};
},
//添加
handleAdd() {
//发送ajax请求
axios.post("/books", this.formData).then((res) => {
console.log(res.data);
//如果操作成功,关闭弹层,显示数据
if (res.data.code == 20011) {
this.dialogFormVisible = false;
this.$message.success("添加成功");
} else if (res.data.code == 20010) {
this.$message.error("添加失败");
} else {
this.$message.error(res.data.msg);
}
}).finally(() => {
this.getAll();
});
},
//弹出编辑窗口
handleUpdate(row) {
// console.log(row); //row.id 查询条件
//查询数据,根据id查询
axios.get("/books/" + row.id).then((res) => {
// console.log(res.data.data);
if (res.data.code == 20041) {
//展示弹层,加载数据
this.formData = res.data.data;
this.dialogFormVisible4Edit = true;
} else {
this.$message.error(res.data.msg);
}
});
},
//编辑
handleEdit() {
//发送ajax请求
axios.put("/books", this.formData).then((res) => {
//如果操作成功,关闭弹层,显示数据
if (res.data.code == 20031) {
this.dialogFormVisible4Edit = false;
this.$message.success("修改成功");
} else if (res.data.code == 20030) {
this.$message.error("修改失败");
} else {
this.$message.error(res.data.msg);
}
}).finally(() => {
this.getAll();
});
},
// 删除
handleDelete(row) {
//1.弹出提示框
this.$confirm("此操作永久删除当前的数据,是否继续?", "提示", {
type: "info"
}).then(() => {
//2.做删除业务
//查询数据,根据id查询
axios.delete("/books/" + row.id).then((res) => {
// console.log(res.data.data);
if (res.data.code == 20021) {
//展示弹层,加载数据
this.$message.success("删除成功");
} else {
this.$message.error("删除失败");
}
});
}).catch(() => {
//3.取消删除
this.$message.info("取消删除操作");
}).finally(() => {
this.getAll();
});
},
}
})
</script>
</html>
package com.itheima.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/12 0:13
*/
@Component
public class ProjectInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandler");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandler");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterHandler");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
package com.itheima.config;
import com.itheima.controller.interceptor.ProjectInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* Created by IntelliJ IDEA.
*
* @Author : Runqiang Jiang
* @create 2022/6/12 0:17
*/
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("../pages/").addResourceLocations("/pages/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandler");
return true;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandler");
String header = request.getHeader("Content-type");
System.out.println("preHandler: "+header);
HandlerMethod handlerMethod = (HandlerMethod) handler;
String name = handlerMethod.getMethod().getName();//方法名称
System.out.println("prehandler:"+name);
return true;
}
后台运行结果:
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandler");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterHandler");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
package com.itheima.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class ProjectInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String contentType = request.getHeader("Content-Type");
HandlerMethod hm = (HandlerMethod)handler;
System.out.println("preHandle...222");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...222");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...222");
}
}
配置拦截器类:
package com.itheima.config;
import com.itheima.controller.interceptor.ProjectIntercepto;
import com.itheima.controller.interceptor.ProjectInterceptor2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectIntercepto projectInterceptor;
@Autowired
private ProjectInterceptor2 projectInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
}
}