黑马课程
需求:对表tbl_book进行新增、修改、删除、根据ID查询和查询所有
javax.servlet javax.servlet-api 3.1.0 provided org.springframework spring-webmvc 5.2.10.RELEASE com.fasterxml.jackson.core jackson-databind 2.9.0 mysql mysql-connector-java 5.1.46 org.springframework spring-jdbc 5.2.10.RELEASE com.alibaba druid 1.1.16 org.mybatis mybatis 3.5.6 org.mybatis mybatis-spring 1.3.0 org.springframework spring-test 5.2.10.RELEASE junit junit 4.12 test
org.apache.tomcat.maven tomcat7-maven-plugin 2.2 80 /
package org.example.config;@Configuration
@ComponentScan({"org.example.service","org.example.dao"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MyBatisConfig.class})
@EnableTransactionManagement//开启注解式事务驱动
public class SpringConfig {
}
这里的org.example.dao可以不添加,程序依然是可以运行的,但需要设置一下IDEA报错
package org.example.config;public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}//事务管理器@Beanpublic PlatformTransactionManager platformTransactionManager(DataSource dataSource){DataSourceTransactionManager dstm = new DataSourceTransactionManager();dstm.setDataSource(dataSource);return dstm;}
}
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&useServerPrepStmts=true
jdbc.username=root
jdbc.password=123456
package org.example.config;public class MyBatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("org.example.domain");ssfb.setDataSource(dataSource);return ssfb;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("org.example.dao");return msc;}
}
package org.example.config;@Configuration
@ComponentScan({"org.example.controller", "org.example.config"})
@EnableWebMvc//功能之一:开启json数据类型自动转换
public class SpringMvcConfig {
}
package org.example.config;//用于放行前端页面
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry){registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");registry.addResourceHandler("/css/**").addResourceLocations("/css/");registry.addResourceHandler("js/**").addResourceLocations("/js/");registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");}
}
package org.example.config;public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {//加载Spring容器配置:管理service和dao@Overrideprotected Class>[] getRootConfigClasses(){return new Class[]{SpringConfig.class};}//加载SpringMVC容器配置:管理controller//Spring不能访问SpringMVC的容器,但SpringMVC能访问Spring的容器,两者是父子容器:子容器可以访问父容器@Overrideprotected Class>[] getServletConfigClasses(){return new Class[]{SpringMvcConfig.class};}//设置哪些请求归属springMVC处理:全部(之后对前端资源放行)@Overrideprotected String[] getServletMappings(){return new String[]{"/"};}//中文乱码处理:仅解决post@Overrideprotected Filter[] getServletFilters(){CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter};}
}
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+');
编写模型类
public class Book {private Integer id;private String type;private String name;private String description;//getter...setter...toString省略
}
编写Dao接口
package org.example.dao;@Repository
public interface BookDao {@Insert("insert into tbl_book values (null, #{type}, #{name}, #{description})")public int save(Book book);@Delete("delete from tbl_book where id = #{id}")public int delete(Integer id);@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")public int update(Book book);@Select("select * from tbl_book where id = #{id}")public Book getById(Integer id);@Select("select * from tbl_book")public List getAll();
}
package org.example.service;@Transactional
public interface BookService {//业务层接口命名需要清晰,并且编写注释文档,这里暂时忽略public boolean save(Book book);public boolean delete(Integer id);public boolean update(Book book);public Book getById(Integer id);public List getAll();
}
package org.example.service.impl;@Service
public class BookServiceImpl implements BookService {@Autowiredprivate BookDao bookDao;@Overridepublic boolean save(Book book) {return bookDao.save(book) > 0;}@Overridepublic boolean delete(Integer id) {return bookDao.delete(id) > 0;}@Overridepublic boolean update(Book book) {return bookDao.update(book) > 0;}@Overridepublic Book getById(Integer id) {return bookDao.getById(id);}@Overridepublic List getAll() {return bookDao.getAll();}
}
package org.example.controller;@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic boolean save(@RequestBody Book book){return bookService.save(book);}@DeleteMapping("/{id}")public boolean delete(@PathVariable Integer id){return bookService.delete(id);}@PutMappingpublic boolean update(@RequestBody Book book){return bookService.update(book);}@GetMapping("/{id}")public Book getById(@PathVariable Integer id){return bookService.getById(id);}@GetMappingpublic List getAll(){return bookService.getAll();}
}
package org.example.service;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {@Autowiredprivate BookService bookService;@Testpublic void testGetById(){Book book = bookService.getById(1);System.out.println(book);}@Testpublic void testGetAll(){List bookList = bookService.getAll();System.out.println(bookList);}
}
这是一种测试方法,还可以通过postman进行测试
SSM基础整合:Spring配置、整合MyBatis、整合SpringMVC、RESTful标准器开发
为了方便前后端交互,采用以下格式进行数据传输
//统一的数据返回结果类
public class Result{private Object data;private Integer code;private String msg;
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TkfSAraq-1676097927478)(C:\Users\jiang\AppData\Roaming\Typora\typora-user-images\image-20230126182515353.png)]
这个格式是根据项目组要求具体设置
步骤1:在cotroller包下创建数据返回结果类Result
package org.example.controller;public class Result {private Integer code;private Object data;private String msg;//推荐创建多个构造方法public Result() {}public Result(Integer code, Object data) {this.code = code;this.data = data;}public Result(Integer code, Object data, String msg) {this.code = code;this.data = data;this.msg = msg;}//省略了getter, setter, toString
}
步骤2:设置code
package org.example.controller;public class Code {//以1结尾表示成功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;//以0结尾表示失败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;
}
步骤3:修改之前的BookController
package org.example.controller;@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic Result save(@RequestBody Book book){boolean flag = bookService.save(book);return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR, flag);}@DeleteMapping("/{id}")public Result delete(@PathVariable Integer id){boolean flag = bookService.delete(id);return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR, flag);}@PutMappingpublic Result update(@RequestBody Book book){boolean flag = bookService.update(book);return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR, flag);}@GetMapping("/{id}")public Result getById(@PathVariable Integer id){Book book = bookService.getById(id);Integer code = book != null ? Code.GET_OK : Code.GET_ERR;String msg = book != null ? "" : "数据查询失败,请重试!";return new Result(code, book, msg);}@GetMappingpublic Result getAll(){List bookList = bookService.getAll();Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;String msg = bookList != null ? "" : "数据查询失败,请重试!";return new Result(code, bookList, msg);}
}
问题描述
当程序出现异常时,前面的Result设置也无法反馈消息,前端得到的将是页面错误
此时就需要对异常进行统一处理
异常的种类及出现异常的原因:
任何一个位置都有可能出现异常,而且这些异常难以避免,最好的方式是对这些异常进行统一处理
约定
所有的异常均抛出到表现层进行处理
表现层通过异常分类处理所有异常
表现层处理异常方法:AOP
异常处理器:集中地、统一地处理项目中出现的异常
在Controller包中创建异常处理器 ProjectExceptionAdvice
package org.example.controller;@RestControllerAdvice
public class ProjectExceptionAdvice {@ExceptionHandler(Exception.class)public void doException(Exception ex){System.out.println("catched!!");}
}
@RestControllerAdvice
:声明这个类是做异常处理的,这是RESTful风格的,还有@ControllerAdvice是非RESTful风格的
@ExceptionHandler
:设置拦截异常的种类,Exception.class表明拦截所有异常
在BookController里的方法中加入 int i = 1/0,模拟异常产生
此时再在浏览器或者postman中测试,可以看到不再报错,而是空白,表明异常已被拦截
业务异常(BusinessException)
系统异常(SystemException)
其他异常(Exception)
编程人员未预期到的异常,如:用到的文件不存在
步骤1:自定义异常类
package org.example.exception;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;}//getter, setter
}
package org.example.exception;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;}
}
这两个类分别用于处理系统异常和错误异常,代码是一样的,只是为了做分类
步骤2:异常编码
package org.example.controller;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;//定义异常类型public static final Integer SYSTEM_ERR = 50001;public static final Integer BUSINESS_ERROR = 50002;public static final Integer SYSTEM_UNKNOWN_ERR = 59999;
}
步骤3:编写异常处理器分类处理异常
package org.example.controller;@RestControllerAdvice
public class ProjectExceptionAdvice {//1. 拦截系统异常@ExceptionHandler(SystemException.class)public Result doSystemException(SystemException ex){//记录日志//发送消息给运维//发送消息给开发人员return new Result(ex.getCode(), null, ex.getMessage());}//2. 拦截业务异常@ExceptionHandler(BusinessException.class)public Result doBusinessException(BusinessException ex){return new Result(ex.getCode(), null, ex.getMessage());}//3. 拦截其他异常@ExceptionHandler(Exception.class)public Result doException(Exception ex){//记录日志//发送消息给运维//发送消息给开发人员return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙,请稍后再试");}}
步骤4:拦截异常示例:异常包装
以BookServiceImpl里的getById()示例,如下:
@Override
public Book getById(Integer id) {//将可能出现的异常进行包装,转换成自定义异常//1. 模拟业务异常if(id == 1){throw new BusinessException(Code.BUSINESS_ERROR, "您的路径错误!");}//2. 模拟系统异常try{int i = 1/0;}catch (ArithmeticException e){throw new SystemException(Code.SYSTEM_ERR, "服务器访问超时,请重试!", e);}return bookDao.getById(id);
}
业务异常示例
访问:http://localhost/books/1
系统异常示例
访问:http://localhost/books/2
前提准备:将前端页面复制到webapp下
需求:在页面中展示所有数据
前端首先有一个表格,与数据 dataList 数据模型双向绑定
...
在script中和后端交互获取数据
需求:点击新增弹出新增表单,
首先要有一个新建按钮,绑定 handleCreate() 点击事件
新建
handleCreate() 方法使得新增表单可见
data: {dialogFormVisible: false,//控制表单是否可见
},
method: {//每次弹出添加串口时,清理掉上次新增的残留数据resetForm(){this.formData = {};}//弹出添加窗口handleCreate() {this.dialogFormVisible = true;this.resetForm();},
}
控制表单中的数据与 formData 绑定
控制表单的确定按钮,绑定了 handleAdd() 点击事件
...
确定
点击确定按钮后,将数据传送到后台,并保存
data: {formData: {},//表单数据
},
methods: {//添加handleAdd() {axios.post("/books", this.formData).then(resp => {//如果新增成功,关闭弹窗,显示数据if(resp.data.code == 20011){this.dialogFormVisible = false;this.$message.success("添加成功");}else if(resp.data.code = 20010){//添加失败,可以通过输入超过数据库表限制的type来模拟//这里是自定义显示数据还是使用resp.data.msg,看后端有无返回msg信息this.$message.error("添加失败");}else{//出现异常this.$message.error(resp.data.msg);}}).finally(() => {this.getAll();})},
}
需求:点击编辑按钮,弹出表单,表单上需要回显数据。修改之后点击
在编辑按钮上绑定 handleUpdate(scope.row) 点击事件
编辑
弹出编辑窗口,并回显数据
data: {dialogFormVisible4Edit: false,//编辑表单是否可见
}
methods: {//弹出编辑窗口handleUpdate(row) {//row里面就包含了当前行的信息,row.id,row.type,row.name,row.description//根据id查找数据,并回显到编辑窗口上//这里不能直接用row里的其他数据,因为这样在编辑时,即便还没有修改,页面的数据也被暂时改变了axios.get("/books/"+row.id).then(resp => {if(resp.data.code == 20041){this.dialogFormVisible4Edit = true;this.formData = resp.data.data;}else{this.$message.error(resp.data.msg);}})},
}
在编辑窗口上有一个确定按钮,绑定了
确定
点击后确认修改,将数据提交给后端
methods: {//编辑handleEdit() {axios.put("/books", this.formData).then(resp => {if(resp.data.code == 20031){this.dialogFormVisible4Edit = false;this.$message.success("修改成功");}else if(resp.data.code == 20030){this.$message.success("修改失败,请输入正确的数据!");}else{this.$message.success(resp.data.msg);}}).finally(() => {this.getAll();})},
}
methods: {// 删除handleDelete(row) {//弹出提示框 确定删除 取消删除this.$confirm("确认删除?", "提示", {type:"info"}).then(() => {axios.delete("/books/"+row.id).then(resp => {if(resp.data.code == 20021){this.$message.success("删除成功");}else if(resp.data.code == 20020){this.$message.error("无法删除,请联系客服!")}else{this.$message.error(resp.data.msg);}}).finally(() => {this.getAll();});}).catch(() => {this.$message.error("取消删除");});}
}
拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
作用
拦截器和过滤器之间的区别
拦截器一般用于表现层,推荐将放在controller包下,即 org.example.controller.interceptor.ProjectInterceptor
package org.example.controller.interceptor;//这里的interceptor包在controller包下,而SpringMvcConfig配置类中已经引入,如果不再controller包下,还需要在SpringMvcConfig扫描
@Component
public class ProjectInterceptor implements HandlerInterceptor {//HandlerInterceptor里有preHandle、postHandle、afterCompletion三个方法@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("preHandle ...");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("postHandle ...");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("afterCompletion ...");}
}
package org.example.config;@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {@Autowiredprivate ProjectInterceptor projectInterceptor;@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry){registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");registry.addResourceHandler("/css/**").addResourceLocations("/css/");registry.addResourceHandler("js/**").addResourceLocations("/js/");registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");}@Overrideprotected void addInterceptors(InterceptorRegistry registry){//当访问/books路径,及/books/*这下一级路径时会被拦截registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*");}
}
package org.example.config;@Configuration
@ComponentScan({"org.example.controller", "org.example.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
如果仅设置拦截"/books"路径,则
访问 http://localhost/books 时会被拦截
但访问 http://localhost/books/1 时不会被拦截
删除SpringMvcSupport配置类,拦截器ProjectInterceptor不变,最后的配置类可以简化写成如下方式:
package org.example.config;@Configuration
@ComponentScan({"org.example.controller"})
@EnableWebMvc//功能之一:开启json数据类型自动转换
public class SpringMvcConfig implements WebMvcConfigurer {@Autowiredprivate ProjectInterceptor projectInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry){registry.addInterceptor(projectInterceptor).addPathPatterns("/books");//当访问/books这个路径时拦截}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");registry.addResourceHandler("/css/**").addResourceLocations("/css/");registry.addResourceHandler("js/**").addResourceLocations("/js/");registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");}
}
这种方式实现了 WebMvcConfigurer 接口,侵入性比较强
1. request
可以从request中获取数据
String contentType = request.getHeader("Content-Type");
2. response:可以向响应数据中添加数据
3. handler
handler:是org.springframework.web.method.HandlerMethod
的对象
封装了正在执行的对象的方法
HandlerMethod hm = (HandlerMethod) handler;
System.out.println(hm.getMethod().getName());
4. modelAndView:封装了页面跳转的相关信息,一般不怎么用
5. ex:可以拿到执行过程中出现的异常信息
创建两个拦截器ProjectInterceptor和ProjectInterceptor2,配置如下
package org.example.config;@Configuration
@ComponentScan({"org.example.controller"})
@EnableWebMvc//功能之一:开启json数据类型自动转换
public class SpringMvcConfig implements WebMvcConfigurer {@Autowiredprivate ProjectInterceptor projectInterceptor;@Autowiredprivate ProjectInterceptor2 projectInterceptor2;@Overridepublic void addInterceptors(InterceptorRegistry registry){registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*");registry.addInterceptor(projectInterceptor2).addPathPatterns("/books", "/books/*");}
}
发现执行顺序:先进后出
规则
示例:3个拦截器的情况
(1)3个拦截器都return true,执行顺序为
pre1 - pre2 - pre3 - controller - post3 - post2 - post1 - after3 - after2 - after1(2)第3个拦截器return false,执行顺序为
pre1 - pre2 - pre3 - after2 - after1(3)第2个拦截器return false,执行顺序为
pre1 - pre2 - after1(3)第1个拦截器return false,执行顺序为
pre1