IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> SSM8==纯注解SSM项目:实现单表CRUD、事务、自定义异常和统一异常处理、RESTFUL风格接口、统一返回值格式(状态码、内容、消息)、JSON传参、axios、vue.js、elementUI -> 正文阅读

[JavaScript知识库]SSM8==纯注解SSM项目:实现单表CRUD、事务、自定义异常和统一异常处理、RESTFUL风格接口、统一返回值格式(状态码、内容、消息)、JSON传参、axios、vue.js、elementUI

环境:IDEA2021+JDK8+MAVEN3.8+TOMCAT7插件

前端:axios、vue.js、elementUI

后端:见POM.XML相关依赖,主要有数据库MySQL5.7 ,数据源Druid,持久层狂框架mybatis,mybatis-spring、spring核心容器、spring事务、spring MVC、测试junit和spring-test

web服务器:tomcat7插件

======================================================================

重点:

????????前后端分离如何约定联调的协议?:其实就是约定好,什么操作传什么格式的结果给对方,我这根据约定传了个约定好的对象,对象中包含自定义的状态码、数据、简短的描述信息。

????????项目统一异常处理的用处?利用@RestControllerAdvice和@ExceptionHandler(自定义异常名.class)告知spring容器,IOC容器中涉及的所有bean有关的异常都给我抛到被@RestControllerAdvice注解的类里面来,我写好了@ExceptionHandler注解的方法会去集中处理,并在该类中返回一个信息给前端,该信息同样遵守联调协议。那么不管我这程序怎么运行,前端始终都能看到经过我包装后的易懂的信息,而不是什么NoSuchXXX搭配一堆英文。而且这个类还能接到我们自定义的异常类型。

? ? ? ? 还有config包中的6个配置类,注解简化了开发,但是简化了可读性,本来用XML配置能够一目了然的,简化成注解之后去哪找下一个类都不知道了。

//用AbstractAnnotationConfigDispatcherServletInitializer代替web.xml配置,tomcat启动时会首先调动该类,

@configration标注的就是主配置类,@EnableXXX代表通过这个配置类对应的IOC容器开放了什么功能,能做什么。过滤器、拦截器由MVC IOC容器管理。

?=======================================================================

效果:

?

========================================================================

接口设计:

访问地址:http://localhost/pages/books.html
模糊查询 GET http://localhost/books/getLike/凡人

其他:见BookController类

项目结构:

===================================================

建表

/*

Source Database       : ssm_db

*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tbl_book
-- ----------------------------
DROP TABLE IF EXISTS `tbl_book`;
CREATE TABLE `tbl_book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tbl_book
-- ----------------------------
INSERT INTO `tbl_book` VALUES ('2', '77', '77李世明999', '999');
INSERT INTO `tbl_book` VALUES ('3', '四川', '科学养猪', '养猪');
INSERT INTO `tbl_book` VALUES ('4', '成都', '凡人修仙传', '修仙');
INSERT INTO `tbl_book` VALUES ('5', '北京', '神墓', '传奇');
INSERT INTO `tbl_book` VALUES ('6', '科学', '天龙八部', '填了');
INSERT INTO `tbl_book` VALUES ('9', '1', '1', '1');
INSERT INTO `tbl_book` VALUES ('11', '2', '88凡人77', '9');

?pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ldj</groupId>
    <artifactId>springmvc_11_page</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!-- 连接MySQL数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <!-- ORM框架简化CRUD操作-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!--进一步简化mybatis操作并整合进spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!-- spring framework 的core container(包含IOC和DI的基础)和右上角的web(引入springMVC组件才能使用@RestController和 @ResquesMapping)基于servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <!--事务交由spring管理,除了数据源、核心容器外,spring事务是基于JDBC的,所以还需要JDBC数据源-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <!-- 简化前后端传参,实现JSON字符串和Java对象互转-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!--spring整合junit测试,我们不用再手动获取IOC容器,再取出bean来测试,直接写两个注解搞定-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>80</port>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

JdbcConfig
package com.ldj.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;

//SpringConfig配置类的一部分,作用是配置数据源,并配置依赖于JDBC的事务管理器
public class JdbcConfig {
    @Value("${jdbc.driver}")    //@Value("${key}")从SpringConfig类上注解PropertySource对应的文件根据key读取value
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    //    事务2、配置事务管理器PlatformTransactionManager
    //1.事务三大接口
    //PlatformTransactionManager 事务管理器
    //TransactionDefinition 事务的一些基础信息,如超时时间、隔离级别、传播属性等
    //TransactionStatus 事务的一些状态信息,如是否一个新的事务、是否已被标记为回滚
    @Bean
    //IOC容器再生成bean之前会先确认参数对应的bean是否已经生成了,没生成就先去生成参数对应的bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}

MyBatisConfig
package com.ldj.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

//SpringConfig配置类的一部分,作用是配置mybatis,并指定ORM中的M O R
public class MyBatisConfig {

    //配置数据源中字段对应的O
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.ldj.domain");
        return factoryBean;
    }

    //配置O和M之间的R
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.ldj.dao");
        return msc;
    }

}
SpringConfig
package com.ldj.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;

@Configuration  //表名这是一个IOC容器的配置类
@ComponentScan({"com.ldj.service"}) //只扫描service中定义的bean,因为其他的的已经在JdbcConfig和MyBatisConfig中指定了
@PropertySource("classpath:jdbc.properties")    //指定数据源信息存放的文件地址
@Import({JdbcConfig.class, MyBatisConfig.class})    //指向子配置类,子配置类的所有东西都属于SpringConfig
@EnableTransactionManagement        //事务1开启注解式事务
public class SpringConfig {
}
SpringMvcConfig
package com.ldj.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration   //表明这是一个IOC容器的配置类
@ComponentScan({"com.ldj.controller", "com.ldj.config"})  //扫描controller中定义的bean?"com.ldj.config"
@EnableWebMvc   //!!!
/**
 * @EnableWebMvc!!表明这是一个MVC的IOC容器的配置类。
 * // 因为归MVC的IOC容器管理的bean在controller和config都有所以都要用ComponentScan配置扫描。
 * // 告知spring我开启了MVC相关的注解,如@controller,@requestMapping,@restController, @PostMapping,@RequestBody @PathVariable
 */
public class SpringMvcConfig {
}
SpringMvcSupport
package com.ldj.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

//MVC容器的另一个配置类,不写在SpringMvcConfig中是为了解耦。
/**
 * 使用标准接口WebMvcConfigurer简化开发(注意:侵入式较强),但是就值需要一个MVC配置类
 * @Configuration
 * @ComponentScan({"com.ldj.controller"})
 * @EnableWebMvc
 * //实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
 * public class SpringMvcConfig implements WebMvcConfigurer {
 *     @Autowired
 *     private ProjectInterceptor projectInterceptor;
 *
 *     @Override
 *     public void addInterceptors(InterceptorRegistry registry) {
 *         //配置多拦截器
 *         registry.addInterceptor(projectInterceptor)
 *             .addPathPatterns("/books","/books/*");
 *     }
 * }
 *
 */

//WebMvcConfigurationSupport可以再此类中配置过滤器(静态资源)和拦截器(controller类中的方法)
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    //    过滤器 指定静态资源的存放路径
    @Override
    protected 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
//    protected void addInterceptors(InterceptorRegistry registry) {
//        //配置拦截器
//        registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*");
//    }

    /**
     * 跨域访问配置接口
     * @param registry
     */
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOrigins("*")
//                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                .allowCredentials(true)
//                .allowedHeaders("*")
//                .maxAge(3600);
//    }
}
ServletConfig
package com.ldj.config;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

//用AbstractAnnotationConfigDispatcherServletInitializer代替web.xml配置,tomcat启动时会首先调动该类,
// 并通过该类连接到普通spring IOC容器(存service及其往下的bean)和MVC IOC容器(存着controller对应的bean)
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[]{"/"};
    }

    //后端往前端传递乱码处理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}
BookController
package com.ldj.controller;

import com.ldj.domain.Book;
import com.ldj.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        System.out.println("收到一条添加请求:===" + 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 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);
    }

    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败,请重试!";
        return new Result(code, bookList, msg);
    }

    @GetMapping("/getLike/{bookName}")
    public Result getById(@PathVariable String bookName) {
        try {
            bookName = new String(bookName.getBytes("ISO-8859-1"), "utf8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("想要查找的书名" + bookName);
        List<Book> books = bookService.getByName(bookName);
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? "" : "数据查询失败,请重试!";
        return new Result(code, books, msg);
    }
}
Code
package com.ldj.controller;

//前后端交互的状态码。在controller和advice中包装返回值成Result对象根据执行情况选用
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 SYSTEM_TIMEOUT_ERR = 50002;
    public static final Integer SYSTEM_UNKNOW_ERR = 59999;

    public static final Integer BUSINESS_ERR = 60002;



}
ProjectExceptionAdvice
package com.ldj.controller;

import com.ldj.exception.BusinessException;
import com.ldj.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//统一项目的异常处理!
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器。
// 所有RestController注解的对应的类出了异常,最终将异常抛到这个类,并根据不同异常执行不同的方法
@RestControllerAdvice
public class ProjectExceptionAdvice {
    //处理系统异常,要手动去抛
    //@ExceptionHandler用于设置当前处理器类对应的异常类型
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    //处理业务相关的异常,包含正常业务操作和用户乱操作。要手动去抛
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex) {
        System.out.println("产生了一个业务操作导致的异常");
        System.out.println(ex.getMessage());
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(Code.SYSTEM_UNKNOW_ERR, null, "系统繁忙,请稍后再试!");
    }
}

Result

package com.ldj.controller;

//返回值包装类。所有返回值,均包装成该类的对象,并通过jackson自动转成JSON字符串传给前端
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;
    }
}
BookDao
package com.ldj.dao;

import com.ldj.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;

public interface BookDao {

    //    @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
    @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();

    @Select("select * from tbl_book where name like #{bookName} ")
    List<Book> getByName(String bookName);
}
Book
package com.ldj.domain;

public class Book {
    private Integer id;
    private String type;
    private String name;
    private String 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;
    }
}
BusinessException
package com.ldj.exception;

//业务异常类。在我们认为因业务操作要抛出异常的代码块中使用try catch或者throw抛出该异常,如密码校验、验证码检查等service中
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;
    }

}
SystemException
package com.ldj.exception;

//系统异常类。在我们认为因系统异常可能抛出异常的代码块中使用try catch或者throw抛出该异常
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;
    }

}
BookService
package com.ldj.service;

import com.ldj.domain.Book;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@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();

    List<Book> getByName(String bookName);
}
BookServiceImpl
package com.ldj.service.impl;

import com.ldj.controller.Code;
import com.ldj.dao.BookDao;
import com.ldj.domain.Book;
import com.ldj.exception.BusinessException;
import com.ldj.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {
        return bookDao.save(book) > 0;
    }

    public boolean update(Book book) {
        return bookDao.update(book) > 0;
    }

    public boolean delete(Integer id) {
        return bookDao.delete(id) > 0;
    }

    public Book getById(Integer id) {
        if (id == 1) {
            System.out.println("id=1不能编辑");
            throw new BusinessException(Code.BUSINESS_ERR, "请不要使用你的技术挑战我的耐性!");
        }
//        //将可能出现的异常进行包装,转换成自定义异常
//        try{
//            int i = 1/0;
//        }catch (Exception e){
//            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
//        }
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }

    public List<Book> getByName(String bookName) {
        bookName = "%" + bookName + "%";
        return bookDao.getByName(bookName);
    }
}

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=1234

books.html

<!DOCTYPE html>

<html>

<head>

    <!-- 页面meta -->

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>单表CRUD</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="getByBookName()" 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: {
                queryString: ""
            },
            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) => {
                    console.log("后端返回的数据为:===" + res.data)
                    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.name);
                    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.做删除业务
                    axios.delete("/books/" + row.id).then((res) => {
                        if (res.data.code == 20021) {
                            this.$message.success("删除成功");
                        } else {
                            this.$message.error("删除失败");
                        }
                    }).finally(() => {
                        this.getAll();
                    });
                }).catch(() => {
                    //3.取消删除
                    this.$message.info("取消删除操作");
                });
            },
            getByBookName() {
                console.log("想要查询的书名称:" + this.pagination.queryString)
                axios.get("/books/getLike/" + this.pagination.queryString)
                    .then((res) => {
                        console.log(res.data)
                        this.dataList = res.data.data;
                    })
            }
        }
    })

</script>

</html>

前端代码过长只贴了页面。而且前后端是通过JSON交互,只需要使用POSTMAN直接测试controller接口即可验证成功,然后上elementUI官网拷贝一个表格改改就行了。获知直接利用axios发送请求consle.log一下即可。

=====================================================================

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-11-12 19:30:07  更:2021-11-12 19:32:19 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 4:48:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码