Spring SSM整合

Spring    SpringMvc  Mybatis 整合

一. 配置类

1.1、 Spring配置类

@Configuration
@ComponentScan({"com.itheima.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {}
  • @EnableTransactionManagement开启事务

1.2、SpringMvcConfig配置类

@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMvcConfig {
}

1.3. ServletConfig配置类

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {protected Class<?>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};}protected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};}protected String[] getServletMappings() {return new String[]{"/"};}// 乱码处理@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter};}
}

1.4. JdbcConfig配置类

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 dataSource = new DruidDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager ds = new DataSourceTransactionManager();ds.setDataSource(dataSource);return ds;}
}
  • 配置类内方法需要 使用@Bean注解, 注入到Spring中

1.5、Mybatis配置类 

public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);factoryBean.setTypeAliasesPackage("com.itheima.domain");return factoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.dao");return msc;}}
  • 这里需要设置domain 和dao 层

1.6、jdbc配置文件  jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=mima1234

二、业务层

2.1、domain层

public class Book {private Integer id;private String type;private String name;private String description;@Overridepublic 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;}
}

2.2、Dao层

public interface BookDao {//@Insert("insert into tbl_book values(null, #{type}, #{name}, #{description})")// 占位符表示的是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();
}

2.3、Service接口和实现类

@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();}@Service
public class BookServiceImpl implements BookService {@Autowiredprivate BookDao bookDao;public boolean save(Book book) {bookDao.save(book);return true;}public boolean update(Book book) {bookDao.update(book);return true;}public boolean delete(Integer id) {bookDao.delete(id);return false;}public Book getById(Integer id) {return  bookDao.getById(id);}public List<Book> getAll() {return bookDao.getAll();}
}

2.4、控制器类

@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic boolean save(@RequestBody Book book) {return bookService.save(book);}@PutMappingpublic boolean update(@RequestBody Book book) {return  bookService.update(book);}@DeleteMapping("/{id}")public boolean delete(@PathVariable Integer id) {return  bookService.delete(id);}@GetMapping("/{id}")public Book getById(@PathVariable Integer id) {return  bookService.getById(id);}@GetMappingpublic List<Book> getAll() {return bookService.getAll();}
}

三、封装返回值

3.1、Code类

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;
}

3.2、Result类

public class Result {private Object data;private Integer code;private  String msg;public Result() {}public Result( Integer code,Object data, String msg) {this.data = data;this.code = code;this.msg = msg;}public Result(Integer code,Object data) {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;}
}

3.3、把控制器返回类型改成Result

@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);}@PutMappingpublic 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 Integer id) {boolean flag =  bookService.delete(id);return new Result(flag ? Code.DELETE_OK : Code.DELETE_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<Book> books =  bookService.getAll();Integer code = books != null ? Code.GET_OK : Code.GET_ERR;String msg = books != null ? "" : "数据查询失败,请重试!";return new Result(code, books, msg);}
}

四、异常

4.1、异常类

public class BusinessException extends RuntimeException {private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = 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 class SystemException extends RuntimeException {private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = 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;}}

4.2、异常AOP

@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){// 记录日志// 发送消息给运维// 发送邮件给开发人员return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙请稍后重试!!!");}
}
  • @RestControllerAdvice 注解声明为AOP类 后,会自动注入到Spring内

4.3、异常使用

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);
}
  •  根据情况抛出不同异常

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/16781.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用Roles模块搭建LNMP架构

使用Roles模块搭建LNMP架构 1.Ansible-playbook中部署Nginx角色2.Ansible-playbook中部署PHP角色3.Ansible-playbook中部署MySQL角色4.启动安装分布式LNMP 1.Ansible-playbook中部署Nginx角色 创建nginx角色所需要的工作目录&#xff1b; mkdir -p /etc/ansible/playbook/rol…

【Python】jupyter Linux服务器使用

文章目录 环境使用访问 环境 pip install jupyter 使用 在你想访问的目录下执行&#xff1a; jupyter notebook --ip0.0.0.0jupyter 给出提示&#xff1a; [I 2023-07-28 14:32:43.589 ServerApp] Package notebook took 0.0000s to import [I 2023-07-28 14:32:43.597 Ser…

react中的高阶组件理解与使用

一、什么是高阶组件&#xff1f; 其实就是一个函数&#xff0c;参数是一个组件&#xff0c;经过这个函数的处理返回一个功能增加的组件。 二、代码中如何使用 1&#xff0c;高级组件headerHoc 2&#xff0c;在普通组件header中引入高阶组件并导出高阶组件&#xff0c;参数是普…

BUUCTF题目Crypto部分wp(持续更新)

Url编码 题目密文是%66%6c%61%67%7b%61%6e%64%20%31%3d%31%7d&#xff0c;根据题目名字使用python的urllib模块解码即可。flag{and 11} from urllib.parse import quote, unquotec r%66%6c%61%67%7b%61%6e%64%20%31%3d%31%7d m unquote(c, encodingutf-8) print(m)c2 quot…

Leetcode | DP | 338. 198. 139.

338. Counting Bits 重点在于这张图。 从i1开始&#xff0c;dp的array如果i是2的1次方之前的数&#xff0c;是1 dp[i - 2 ^ 0]; 如果i是2的2次方之前的数&#xff0c;是1 dp[i - 2 ^ 1]; 如果i是2的3次方之前的数&#xff0c;是1 dp[i - 2 ^ 2]; 198. House Robber 如果…

zookeeper学习(三)基础数据结构

数据模型 在 zookeeper 中&#xff0c;可以说 zookeeper 中的所有存储的数据是由 znode 组成的&#xff0c;节点也称为 znode&#xff0c;并以 key/value 形式存储数据。 整体结构类似于 linux 文件系统的模式以树形结构存储。其中根路径以 / 开头。 进入 zookeeper 安装的 …

如何查看 Chrome 网站有没有前端 JavaScript 报错?

您可以按照以下步骤在Chrome中查看网站是否存在前端JavaScript报错&#xff1a; 步骤1&#xff1a;打开Chrome浏览器并访问网站 首先&#xff0c;打开Chrome浏览器并访问您想要检查JavaScript报错的网站。 步骤2&#xff1a;打开开发者工具 在Chrome浏览器中&#xff0c;按…

【机器学习】Gradient Descent for Logistic Regression

Gradient Descent for Logistic Regression 1. 数据集&#xff08;多变量&#xff09;2. 逻辑梯度下降3. 梯度下降的实现及代码描述3.1 计算梯度3.2 梯度下降 4. 数据集&#xff08;单变量&#xff09;附录 导入所需的库 import copy, math import numpy as np %matplotlib wi…

OpenFeign 个性化_注解配置_日志_请求拦截_请求透传_FastJson解析

相关组件概念 Ribbon&#xff1a; Ribbon 是 Netflix开源的基于 HTTP 和 TCP 等协议负载均衡组件&#xff1b;Ribbon 可以用来做客户端负载均衡&#xff0c;调用注册中心的服务&#xff1b; Feign&#xff1a; Feign 是 Spring Cloud 组件中的一个轻量级 RESTful 的 HTTP 服务客…

CompletableFuture 详解

目录 简单介绍 常见操作 创建 CompletableFuture new 关键字 静态工厂方法 处理异步结算的结果 简单介绍 CompletableFuture 同时实现了 Future 和 CompletionStage 接口。 public class CompletableFuture<T> implements Future<T>, CompletionStage<T…

Android 11.0 系统限制上网系统之iptables用IOemNetd实现app上网白名单的功能实现

1.前言 在10.0的系统rom定制化开发中,对于系统限制网络的使用,在system中netd网络这块的产品需要中,会要求设置app上网白名单的功能, liunx中iptables命令也是比较重要的,接下来就来在IOemNetd这块实现app上网白名单的的相关功能,就是在 系统中只能允许某个app上网,就是…

springboot通过接口执行本地shell脚本

首先创建springboot项目 shell脚本 #!/bin/shecho Hello World&#xff01;然后编写执行shell脚本的util类 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List;pub…

selenium-web自动化测试

一、selenium环境部署 1.准备chrome浏览器&#xff08;其他浏览器也行&#xff09; 2.准备chrome驱动包 步骤一&#xff1a;查看自己的谷歌浏览器版本(浏览器版本和驱动版本一定要对应) 步骤二&#xff1a;下载对应的驱动包, 下载路径 : ChromeDriver - WebDriver for Chrom…

初识IDA工具

工具 IDA工具 链接&#xff1a;https://pan.baidu.com/s/1Zgzpws6l2M5j1wkCZHrffw 提取码&#xff1a;ruyu 里面有安装密码&#xff1a; PassWord:qY2jts9hEJGy 里面分析32位和64位启动快捷方式 打开IDA工具&#xff0c;拖入so文件 ARM AND THUMB MODE SWITCH INSTRUCTION…

PyTorch BatchNorm2d详解

通常和卷积层&#xff0c;激活函数一起使用

视频传输网安全防护体系

在电脑、手机信息安全保护得到广泛关注和普及的今天&#xff0c;监控摄像头等设备的安全防护仍为大众所忽略&#xff0c;大量视频监控网络的前端设备和数据没有任何保护&#xff0c;完全暴露在互联网中。 前端IP接入设备与后端业务系统处于直连状态&#xff0c;一旦有攻击者或…

vue3项目中数字滚动效果

前言&#xff1a; 目前大多数新的vue项目都采用了vue3去写&#xff0c; 在最近的项目中&#xff0c;需要展示数字滚动的效果&#xff0c;我就想到了之前用多的vue-count-to数字滚动插件&#xff0c;发现这个插件只使用于vue2项目&#xff0c;在vue3项目中并不试用。。。由于自己…

spring boot项目整合spring security权限认证

一、准备一个spring boot项目 1、引入基础依赖 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.sp…

自定义类型讲解

&#x1f495;痛苦难道是白忍受的吗&#xff1f;&#x1f495; 作者&#xff1a;Mylvzi 文章主要内容&#xff1a;自定义类型讲解 一.结构体 定义&#xff1a; 数组&#xff1a;多组相同类型元素的集合 结构体&#xff1a;多组不同类型元素的集合-->管理多组不同类型数据…

计算机视觉实验:人脸识别系统设计

实验内容 设计计算机视觉目标识别系统&#xff0c;与实际应用有关&#xff08;建议&#xff1a;最终展示形式为带界面可运行的系统&#xff09;&#xff0c;以下内容选择其中一个做。 1. 人脸识别系统设计 (1) 人脸识别系统设计&#xff08;必做&#xff09;&#xff1a;根据…