SpringMVC-Day2

[复制链接]
发表于 2024-12-1 12:05:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
基于RESRful页面数据交互
1.制作SpringMVC控制器,并通过PostMan测试接口功能
  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4.    @PostMapping
  5.    public String save(@RequestBody Book book){
  6.        System.out.prinln("book save ==>" + book);
  7.        return "{'module':'book save success'}";
  8.    }
  9.    @GetMapping
  10.    public List<Book> getAll(){
  11.       System.out.println("book getAll is runing ...");
  12.       List<Book> bookList = new ArrayList<Book>();
  13.       Book book1 = new Book();
  14.       book1.setType("计算机");
  15.       book1.setName("SpringMVC入门教程")
  16.       book1.setDescription("小试牛刀")
  17.       bookList.add(book1);
  18.       //模拟数据...
  19.       return bookList;
  20.    }
  21. }
复制代码
2.设置对静态资源的访问放行
  1. //放行非springmvc的请求
  2. @Configuration
  3. public class SpringMvcSupport extends WebMvcConfigurationSupport {
  4.    @Override
  5.    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  6.        // 当访问/pages/???时,走/pages目录下的内容
  7.        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
  8.    }
  9. }
复制代码
3.前端页面通过异步提交访问后台控制器
  1. //添加
  2. saveBook(){
  3.    axios.post("/books",this.formData).then((res)=>{
  4.    
  5.    });
  6. },
  7. ​
  8. //主页列表查询
  9. getAll(){
  10.   axios.get("/books").then((res)=>{
  11.       this.dataList = res.data;
  12.   });
  13. };
复制代码
5.SSM整合

1.整合配置

JdbcConfig
  1. public class JdbcConfig {
  2.    @Value("${jdbc.driver}")
  3.    private String driver;
  4.    @Value("${jdbc.url}")
  5.    private String url;
  6.    @Value("${jdbc.username}")
  7.    private String username;
  8.    @Value("${jdbc.password}")
  9.    private String password;
  10.    @Bean
  11.    public DataSource dataSource() {
  12.        DruidDataSource dataSource = new DruidDataSource();
  13.        dataSource.setDriverClassName(driver);
  14.        dataSource.setUrl(url);
  15.        dataSource.setUsername(username);
  16.        dataSource.setPassword(password);
  17.        return dataSource;
  18.    }
  19. }
复制代码
MybatisConfig
  1. public class MybatisConfig {
  2.    @Bean
  3.    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
  4.        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  5.        factoryBean.setDataSource(dataSource);
  6.        factoryBean.setTypeAliasesPackage("com.zkw.domain");
  7.        return factoryBean;
  8.    }
  9. ​
  10.    @Bean
  11.    public MapperScannerConfigurer mapperScannerConfigurer(){
  12.        MapperScannerConfigurer msc = new MapperScannerConfigurer();
  13.        msc.setBasePackage("com.zkw.dao");
  14.        return msc;
  15.    }
  16. }
复制代码
ServletConfig
  1. public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
  2.    @Override
  3.    protected Class<?>[] getRootConfigClasses() {
  4.        return new Class[]{SpringConfig.class};
  5.    }
  6. ​
  7.    @Override
  8.    protected Class<?>[] getServletConfigClasses() {
  9.        return new Class[]{SpringMvcConfig.class};
  10.    }
  11. ​
  12.    @Override
  13.    protected String[] getServletMappings() {
  14.        return new String[]{"/"};
  15.    }
  16. }
复制代码
SpringConfig
  1. @Configuration
  2. @ComponentScan({"com.zkw.service"})
  3. @PropertySource("jdbc.properties")
  4. @Import({JdbcConfig.class, MybatisConfig.class})
  5. public class SpringConfig {
  6. }
复制代码
SpringMvcConfig
  1. @Configuration
  2. @ComponentScan("com.zkw.controller")
  3. @EnableWebMvc
  4. public class SpringMvcConfig {
  5. }
复制代码
2.功能模块开发

BookController
  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4.    @Autowired
  5.    private BookService bookService;
  6.    @PostMapping
  7.    public boolean save(@RequestBody Book book) {
  8.        return bookService.save(book);
  9.    }
  10.    @DeleteMapping("/{id}")
  11.    public boolean delete(@PathVariable Integer id) {
  12.        return bookService.delete(id);
  13.    }
  14.    @PutMapping
  15.    public boolean update(@RequestBody Book book) {
  16.        return bookService.update(book);
  17.    }
  18.    @GetMapping("/{id}")
  19.    public Book getById(@PathVariable Integer id) {
  20.        return bookService.getById(id);
  21.    }
  22.    @GetMapping
  23.    public List<Book> getAll() {
  24.        return bookService.getAll();
  25.    }
  26. ​
  27. }
复制代码
BookService
  1. public interface BookService {
  2.    public boolean save(Book book);
  3.    public boolean delete(Integer id);
  4.    public boolean update(Book book);
  5.    public Book getById(Integer id);
  6.    public List<Book> getAll();
  7. }
复制代码
BookServiceImpl
  1. @Service
  2. public class BookServiceImpl implements BookService {
  3.    @Autowired
  4.    private BookDao bookDao;
  5.    @Override
  6.    public boolean save(Book book) {
  7.        bookDao.save(book);
  8.        return true;
  9.    }
  10. ​
  11.    @Override
  12.    public boolean delete(Integer id) {
  13.        bookDao.delete(id);
  14.        return true;
  15.    }
  16. ​
  17.    @Override
  18.    public boolean update(Book book) {
  19.        bookDao.update(book);
  20.        return true;
  21.    }
  22. ​
  23.    @Override
  24.    public Book getById(Integer id) {
  25.        return bookDao.getById(id);
  26.    }
  27. ​
  28.    @Override
  29.    public List<Book> getAll() {
  30.        return bookDao.getAll();
  31.    }
  32. }
复制代码
BookDao
  1. public interface BookDao {
  2.    @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
  3.    public void save(Book book);
  4.    @Update("update tbl_book set type=#{type},name=#{name},description=#{description} where id=#{id}")
  5.    public void update(Book book);
  6.    @Delete("delete from tbl_book where id = #{id}")
  7.    public void delete(Integer id);
  8.    @Select("select * from tbl_book where id = #{id}")
  9.    public Book getById(Integer id);
  10.    @Select("select * from tbl_book")
  11.    public List<Book> getAll();
  12. }
复制代码
Book
  1. public class Book {
  2.    private Integer id;
  3.    private String type;
  4.    private String name;
  5.    private String description;
  6. ​
  7.    @Override
  8.    public String toString() {
  9.        return "Book{" +
  10.                "id=" + id +
  11.                ", type='" + type + '\'' +
  12.                ", name='" + name + '\'' +
  13.                ", description='" + description + '\'' +
  14.                '}';
  15.    }
  16. ​
  17.    public Integer getId() {
  18.        return id;
  19.    }
  20. ​
  21.    public void setId(Integer id) {
  22.        this.id = id;
  23.    }
  24. ​
  25.    public String getType() {
  26.        return type;
  27.    }
  28. ​
  29.    public void setType(String type) {
  30.        this.type = type;
  31.    }
  32. ​
  33.    public String getName() {
  34.        return name;
  35.    }
  36. ​
  37.    public void setName(String name) {
  38.        this.name = name;
  39.    }
  40. ​
  41.    public String getDescription() {
  42.        return description;
  43.    }
  44. ​
  45.    public void setDescription(String description) {
  46.        this.description = description;
  47.    }
  48. }
复制代码
变乱处理
  1. @Bean
  2.    public PlatformTransactionManager transactionManager(DataSource dataSource){
  3.        DataSourceTransactionManager ds = new DataSourceTransactionManager();
  4.        ds.setDataSource(dataSource);
  5.        return ds;
  6.    }
复制代码
3.接口测试

BookServiceTest
  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class)
  3. public class BookServiceTest {
  4.    @Autowired
  5.    private BookService bookService;
  6.    @Test
  7.    public void testGetById(){
  8.        Book book =bookService.getById(1);
  9.        System.out.println(book);
  10.    }
  11.    @Test
  12.    public void testGetAll(){
  13.        List<Book> all =bookService.getAll();
  14.        System.out.println(all);
  15.    }
  16. }
复制代码
再用PostMan去测试增删改查功能是否成功
6.体现层和前端数据传输协议

设置统一数据返回结果类
  1. public class Result {
  2.   private Object data;
  3.   private Integer code;
  4.   private String msg;
  5. }
复制代码
通过code可以得知,是增删改查何种利用,最后的数字,1代表成功,0代表失败


  • 20031 -> 增删改
  • 20041 -> 查询
编写Code
  1. public class Code {
  2.    public static final Integer SAVE_OK = 20011;
  3.    public static final Integer DELETE_OK = 20021;
  4.    public static final Integer UPDATE_OK = 20031;
  5.    public static final Integer GET_OK = 20041;
  6.    public static final Integer SAVE_ERR = 20010;
  7.    public static final Integer DELETE_ERR = 20020;
  8.    public static final Integer UPDATE_ERR = 20030;
  9.    public static final Integer GET_ERR = 20040;
  10. }
复制代码
修改BookController
  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4.    @Autowired
  5.    private BookService bookService;
  6.    @PostMapping
  7.    public Result save(@RequestBody Book book) {
  8.        boolean flag = bookService.save(book);
  9.        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
  10.    }
  11.    @DeleteMapping("/{id}")
  12.    public Result delete(@PathVariable Integer id) {
  13.        boolean flag = bookService.delete(id);
  14.        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
  15.    }
  16.    @PutMapping
  17.    public Result update(@RequestBody Book book) {
  18.        boolean flag = bookService.update(book);
  19.        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
  20.    }
  21.    @GetMapping("/{id}")
  22.    public Result getById(@PathVariable Integer id) {
  23.        Book book = bookService.getById(id);
  24.        Integer code = book != null ? Code.GET_OK:Code.GET_ERR;
  25.        String msg = book != null ? "":"数据查询失败 请重试";
  26.        return new Result(code,book,msg);
  27.    }
  28.    @GetMapping
  29.    public Result getAll() {
  30.        List<Book> bookList = bookService.getAll();
  31.        Integer code = bookList != null? Code.GET_OK:Code.GET_ERR;
  32.        String msg = bookList !=null ? "":"数据查询失败 请重试";
  33.        return new Result(code,bookList,msg);
  34.    }
  35. ​
  36. }
复制代码
7.异常处理器

由于各个层级均会出现异常,以是将全部的异常均抛出到体现层处理
  1. @RestControllerAdvice
  2. public class ProjectExceptionAdvice {
  3.    @ExceptionHandler(Exception.class)
  4.    public Result doException(Exception e){
  5.        System.out.println("已发现异常");
  6.        return new Result(666,null,"已发现异常");
  7.    }
  8. }
复制代码
通过@RestControllerAdvice声明其为一个异常处理器
再通过@ExceptionHandler来界说处理哪一种异常
8.项目异常处理方案



  • 业务异常(BusinessException)

    • 发送对应消息转达给用户,提醒规范利用

  • 系统异常(SystemException)

    • 发送固定信息转达给用户,安抚用户
    • 发送特定消息给运维人员,提醒维护
    • 记录日志日志

  • 其他异常(Exception)

    • 发送固定消息转达给客户,安抚客户
    • 发送特定消息给编程人员,提醒维护(纳入预期范围)
    • 记录日志日志

  1. @RestControllerAdvice
  2. public class ProjectExceptionAdvice {
  3.    @ExceptionHandler(SystemException.class)
  4.    public Result doSystemException(SystemException e){
  5.        //记录日志日志
  6.        //发送消息给运维
  7.        //发送邮件给开发人员
  8.        return new Result(e.getCode(),null,e.getMessage());
  9.    }
  10. ​
  11.    @ExceptionHandler(BusinessException.class)
  12.    public Result doBusinessException(BusinessException e){
  13.        //记录日志
  14.        //发送消息给运维
  15.        //发送邮件给开发人员,ex对象发给开发人员
  16.        return new Result(e.getCode(),null,e.getMessage());
  17.    }
  18. ​
  19.    @ExceptionHandler(Exception.class)
  20.    public Result doException(Exception e){
  21.        System.out.println("已发现异常");
  22.        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试");
  23.    }
  24. }
复制代码
要根据对应的异常,设定相应的异常编码
自界说项目级系统异常
  1. public class SystemException extends RuntimeException{
  2.    private Integer code;
  3. ​
  4.    public Integer getCode() {
  5.        return code;
  6.    }
  7. ​
  8.    public void setCode(Integer code) {
  9.        this.code = code;
  10.    }
  11. ​
  12.    public SystemException(Integer code, String message) {
  13.        super(message);
  14.        this.code = code;
  15.    }
  16. ​
  17.    public SystemException(Integer code, String message, Throwable cause) {
  18.        super(message, cause);
  19.        this.code = code;
  20.    }
  21. }
复制代码
9.前后台协议联调

  1. method: {
  2.    //列表功能
  3.    getAll() {
  4.        //发送ajax请求
  5.        axios.get("/books").then((res)=>{
  6.            this.dataList = res.data.data;
  7.        });
  8.     },
  9.     //重置表单
  10.     resetForm(){
  11.         this.formData = {};
  12.     },
  13.     //添加
  14.     handleAdd(){
  15.        //发送ajax请求
  16.        axios.post("/books",this.formData).then((res)=>{
  17.            //如果操作成功,关闭弹层,显示数据
  18.            if(res.data.code == 20011){
  19.                this.dialogFormVisible = false;
  20.                this.$message.success("添加成功");
  21.            }else if(res.data.code == 20010){
  22.                this.$message.error("添加失败");
  23.            }else{
  24.                this.$message.error("res.data.msg");
  25.            }
  26.        }).finally()=>{
  27.            this.getAll();
  28.        });
  29.     },
  30.     //弹出编辑窗口
  31.     handleUpdate(row){
  32.         //console.log(row); //row.id 查询条件
  33.         //查询数据,根据id
  34.         if(res.data.code == 20041){
  35.             //展示弹层,加载数据
  36.             this.formData = res.data.data;
  37.             this.diagloFormVisible4Edit = true;
  38.            }else{
  39.                this.$message.error("res.data.msg");
  40.            }
  41.         });
  42.     },
  43.     //编辑
  44.     handleEdit(){
  45.        //发送ajax请求
  46.        axios.pup("/books",this.formData).then((res)=>{
  47.            //如果操作成功,关闭弹层,显示数据
  48.            if(res.data.code == 20031){
  49.                this.dialogFormVisible4Edit = false;
  50.                this.$message.success("修改成功");
  51.            }else if(res.data.code == 20030){
  52.                this.$message.error("修改失败");
  53.            }else{
  54.                this.$message.error("res.data.msg");
  55.            }
  56.        }).finally()=>{
  57.            this.getAll();
  58.        });
  59.     },
  60.     // 删除
  61.     handleDelete(row) {
  62.         //1.弹出提示框
  63.         this.$confirm("此操作永久删除当前数据,是否继续?","提示",{
  64.             type:'info'
  65.         }).then((=>{
  66.             //2.做删除业务
  67.             axios.delete("/books/"+row.id).then((res)=>{
  68.                 if(res.data.code == 20021){
  69.                      this.$message.success("删除成功")
  70.                 }else{
  71.                      this.$message.error("删除失败");
  72.                 }
  73.             });          
  74.         }).catch(()=>{
  75.             //3.取消删除操作
  76.             this.$message.info("取消删除操作");
  77.         }).finally(()=>{
  78.             this.getAll();
  79.         });
  80.        
  81.       }
  82.    }
  83. })
复制代码
10.拦截器

拦截器概念:是一种动态拦截方法调用的机制,再SpringMVC中动态拦截控制器方法的执行
作用:在指定的方法调用前后执行预先设定的代码;阻止原始方法的执行
拦截器与过滤器区别:

  • 归属差别:Filter属于Servlet技术,Interecptor属于SpringMVC技术
  • 拦截内容差别:Filter对全部访问进行增强,Interecptor仅针对SpringMVC的访问进行增强
拦截器入门案例:
1.声明拦截器的bean,并实现HandlerInterceptor接口
  1. @Component
  2. public class ProjectInterceptor implements HandlerInterceptor {
  3.    @Override
  4.    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  5.        System.out.println("preHandle...");
  6.        return true; //false可终止原始操作
  7.    }
  8. ​
  9.    @Override
  10.    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  11.        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
  12.    }
  13. ​
  14.    @Override
  15.    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  16.        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
  17.    }
  18. }
复制代码
2.界说配置类,继续WebMvcConfigurationSupport,实现addInterceptor方法
  1. @Configuration
  2. public class SpringMvcSupport extends WebMvcConfigurationSupport {
  3.    @Autowired
  4.    private ProjectInterceptor projectInterceptor;
  5.    @Override
  6.    protected void addInterceptors(InterceptorRegistry registry) {
  7.        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
  8.    }
  9. }
复制代码
拦截器配置
拦截器可以配多个,形成拦截链


  • preHandle:与配置次序相同,肯定运行
  • postHandle:与配置次序相反,大概不运行
  • afterCompletion:与配置次序相反,大概不运行

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表