Loading... ## 总结前: 东西有点多,确实有点难,只是了解了个有里面可能有这个东西,这个东西有什么用,但是如果让我熟练的进行使用,可能还比较困难,嘿嘿,可能过不了多少天就会忘记了,只能到时候再查! ## 总结 ### 大概的项目框架  ## config配置类 ### jdbcConfig 连接数据库的基本信息 ```java package com.bdm.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-6:57 */ public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.password}") private String password; @Value("${jdbc.username}") private String username; @Bean public DataSource dataSource(){ final DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setUrl(url); return dataSource; } @Bean public PlatformTransactionManager transactionManager(DataSource dataSource){ final DataSourceTransactionManager ds = new DataSourceTransactionManager(); ds.setDataSource(dataSource); return ds; } } ``` ### MyBatisConfig 配置mybatis映射的路径与类型 ```java package com.bdm.config; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; import javax.xml.crypto.Data; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-6:58 */ public class MyBatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean .setDataSource(dataSource); factoryBean.setTypeAliasesPackage("com.bdm.domain"); return factoryBean; } @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ final MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.bdm.dao"); return msc; } } ``` ### servletConfig 配置过滤器 ```java package com.bdm.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:36 */ public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } ``` ### SpringConfig spring的核心配置类 ```java package com.bdm.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; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-6:56 */ @Configuration @ComponentScan({"com.bdm.service"}) @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class, MyBatisConfig.class}) // 开启事务 @EnableTransactionManagement public class SpringConfig { } ``` ### SpringMvcConfig SpringMvc的核心配置类与拦截器 ```java package com.bdm.config; import com.bdm.controller.interceptor.ProjectInterceptor; 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.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:37 */ @Configuration @ComponentScan({"com.bdm.controller"}) @EnableWebMvc public class SpringMvcConfig implements WebMvcConfigurer { @Autowired private ProjectInterceptor projectInterceptor; // 注入拦截器 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/"); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*"); } } ``` ## controller接口管理 ### ProjectInterceptor 拦截器关键实现 ```java package com.bdm.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; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-15:47 */ @Component public class ProjectInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("interceptor ..."); return true; //为true放行,false拦截 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("post interceptor ..."); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("after interceptor ..."); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } } ``` ### BookController 接口实现类 ```java package com.bdm.controller; import com.bdm.domain.Book; import com.bdm.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:47 */ @RestController @RequestMapping("/books") public class BookController { @Autowired private BookService bookService; @PostMapping public Result save(@RequestBody Book book) { final boolean flag = bookService.save(book); return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag); } @PutMapping public Result update(@RequestBody Book book) { final boolean flag = bookService.update(book); return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag); } @DeleteMapping("/{id}") public Result delete(@PathVariable Integer id) { System.out.println(id); final boolean flag = bookService.deleteById(id); return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag); } @GetMapping("/{id}") public Result getById(@PathVariable Integer id) { final 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); } @GetMapping public Result getAll() { final 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); } } ``` ### Code 状态码,用来判别接口返回的成功与失败 ```java package com.bdm.controller; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-11:39 */ public class Code { public static final int SAVE_OK = 20011; public static final int DELETE_OK = 20021; public static final int UPDATE_OK = 20031; public static final int GET_OK = 20041; public static final int SAVE_ERR = 20010; public static final int DELETE_ERR = 20020; public static final int UPDATE_ERR = 20030; public static final int GET_ERR = 20040; public static final int SYSTEM_ERR = 50001; public static final int BUSINESS_ERR = 50002; public static final int SYSTEM_UNKNOWN_ERR = 59999; } ``` ### ProjectExceptionAdvice 处理中央异常的关键类,全部的异常都会集中于此 ```java package com.bdm.controller; import com.bdm.exception.BusinessException; import com.bdm.exception.SystemException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-12:12 */ @RestControllerAdvice public class ProjectExceptionAdvice { @ExceptionHandler(SystemException.class) public Result doSystemException(SystemException ex){ // 记录日志 // 发送消息给运维 // 发送邮件给开发人员 System.out.println("系统异常"); return new Result(ex.getCode(), null, ex.getMessage()); } @ExceptionHandler(BusinessException.class) public Result doBusinessException(BusinessException ex){ System.out.println("业务异常"); 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, "系统繁忙,请稍后再试!"); } } ``` ### Result 返回给前端的统一格式 ```java package com.bdm.controller; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-10:17 */ public class Result { private Object data; private Integer code; private String msg; public Result() { } public Result( Integer code, Object data) { this.data = data; this.code = code; } public Result(Integer code, Object data, String msg) { this.data = data; this.code = code; this.msg = msg; } 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; } @Override public String toString() { return "Result{" + "data=" + data + ", code=" + code + ", msg='" + msg + '\'' + '}'; } } ``` ## dao数据库交互 ### BookDao 与数据库交互的sql语句 ```java package com.bdm.dao; import com.bdm.domain.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; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:45 */ public interface BookDao { @Insert("insert into tbl_book values(null, #{type}, #{name}, #{description})") int save(Book book); @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}") int update(Book book); @Delete("delete from tbl_book where id = #{id}") int delete(Integer id); @Select("select * from tbl_book where id = #{id}") Book getById(Integer id); @Select("select * from tbl_book") List<Book>getAll(); } ``` ## domain实体类 ### Book 实体类 ```java package com.bdm.domain; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:43 */ 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; } 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; } @Override public String toString() { return "Book{" + "id=" + id + ", type='" + type + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + '}'; } } ``` ## exception自定义异常 ### BusinessException 业务异常 ```java package com.bdm.exception; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-12:25 */ public class BusinessException extends RuntimeException{ private Integer code; public Integer getCode() { return 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; } } ``` ### SystemException 系统异常 ```java package com.bdm.exception; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-12:25 */ public class SystemException extends RuntimeException{ private Integer code; public Integer getCode() { return 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; } } ``` ## service业务相关 ### BookServiceImpl 接受数据库的数据,经过处理后再返回出去 ```java package com.bdm.service.impl; import com.bdm.controller.Code; import com.bdm.dao.BookDao; import com.bdm.domain.Book; import com.bdm.exception.BusinessException; import com.bdm.exception.SystemException; import com.bdm.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:46 */ @Service public class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; @Override public boolean save(Book book) { final int save = bookDao.save(book); return save > 0; } @Override public boolean update(Book book) { final int update = bookDao.update(book); return update > 0; } @Override public boolean deleteById(Integer id) { final int delete = bookDao.delete(id); return delete > 0; } @Override public Book getById(Integer id) { if(id < 1){ System.out.println("id = 1"); throw new BusinessException(Code.BUSINESS_ERR, "请不要恶意访问,否则将追究责任!"); } return bookDao.getById(id); } @Override public List<Book> getAll() { return bookDao.getAll(); } } ``` ### Bookservice 接口规范 ```java package com.bdm.service; import com.bdm.domain.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 org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @code Description * @code author 本当迷 * @code date 2022/8/1-7:46 */ @Transactional public interface BookService { /** * 保存 * @param book * @return */ boolean save(Book book); /** * 修改 * @param book * @return */ boolean update(Book book); /** * 删除 * @param id * @return */ boolean deleteById(Integer id); /** * 根据id查询 * @param id * @return */ Book getById(Integer id); /** * 查询全部 * @return */ List<Book> getAll(); } ``` 最后修改:2022 年 08 月 01 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果文章有用,请随意打赏。