SSM整合(注解版)

1、环境搭建


1.1、添加数据

create database if not exists ssm_db;

use ssm_db;

create table if not exists tb_book
(
    id          int auto_increment,
    type        varchar(50)  comment '图书类别',
    name        varchar(100) comment '图书名称',
    description varchar(255) comment '图书描述',
    primary key (id)
);


INSERT INTO ssm_db.tb_book (`type`,name,description) VALUES
	 ('计算机理论','Spring实战 第五版','Spring入门经典教程,深入理解Spring原理技术内幕'),
	 ('计算机理论','Spring 5核心原理与30个类手写实践','十年沉淀之作,手写Spring精华思想'),
	 ('计算机理论','Spring 5设计模式','深入Spring源码刨析Spring源码中蕴含的10大设计模式'),
	 ('计算机理论','Spring MVC+Mybatis开发从入门到项目实战','全方位解析面向Web应用的轻量级框架,带你 成为Spring MVC开发高手'),
	 ('计算机理论','轻量级Java Web企业应用实战','源码级刨析 Spring框架,适合已掌握Java基础的读者'),
	 ('计算机理论','Java核心技术 卷Ⅰ 基础知识(原书 第11版)','Core Java第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新'),
	 ('计算机理论','深入理解Java虚拟机','5个纬度全面刨析JVM,大厂面试知识点全覆盖'),
	 ('计算机理论','Java编程思想(第4版)','Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉'),
	 ('计算机理论','零基础学Java(全彩版)','零基础自学编程的入门图书,由浅入深,详解Java语言 的编程思想和核心技术'),
	 ('计算机类','SpringBoot','Java程序员必备技能'),
	 ('计算机类','SpringCloud','微服务大势所趋'),
	 ('计算机类','Spring Security','安全框架');

1.2、导入相关依赖

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.8</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.18</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.3.18</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.18</version>
    </dependency>

    <!-- json转换 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.2.2</version>
    </dependency>

    <!-- lombok 简化bean-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
    </dependency>

    <!-- Spring5和Thymeleaf整合包 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency>

    <!--文件上传-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>

    <!-- 分页插件 -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

<!-- 配置tomcat插件 -->
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <!-- 端口号 -->
                <port>80</port>
                <!-- 访问路径 -->
                <path>/</path>
            </configuration>
        </plugin>
    </plugins>
</build>

2、开发流程


2.1、编写实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    
    
    private Integer id;
    private String type;
    private String name;
    private String description;
}

2.2、编写通用结果返回类

2.2.1、结果类(便于给前端返回数据)

/**
 * 封装返回结果
 */
@Data
public class Result implements Serializable{
    
    
    private boolean flag;   //执行结果,true为执行成功 false为执行失败
    private String message; //返回结果信息,主要用于页面提示信息
    private Object data;    //返回数据

    public Result(boolean flag, String message) {
    
    
        super();
        this.flag = flag;
        this.message = message;
    }

    public Result(boolean flag, String message, Object data) {
    
    
        this.flag = flag;
        this.message = message;
        this.data = data;
    }
}

2.2.2、分页查询条件

/**
 * 封装查询条件
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class QueryPageBean implements Serializable{
    
    
    private Integer currentPage;    //页码
    private Integer pageSize;   //每页记录数
    private String condition;   //查询条件
}

2.2.3、分页结果封装对象

/**
 * 封装查询条件
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class QueryPageBean implements Serializable{
    
    
    private Integer currentPage;    //页码
    private Integer pageSize;   //每页记录数
    private String condition;   //查询条件
}

2.2.4、消息常量类

/**
 * 消息常量
 */
public class MessageConstant {
    
    
    public static final String QUERY_BOOK_SUCCESS = "查询图书成功";
    public static final String QUERY_BOOK_FAIL = "查询图书失败";
    public static final String DELETE_BOOK_SUCCESS = "删除图书成功";
    public static final String DELETE_BOOK_FAIL = "删除图书失败";
    public static final String ADD_BOOK_SUCCESS = "添加图书成功";
    public static final String ADD_BOOK_FAIL = "添加图书失败";
    public static final String UPDATE_BOOK_SUCCESS = "修改图书成功";
    public static final String UPDATE_BOOK_FAIL = "修改图书失败";
}

2.3、编写BookMapper接口(Dao层)

public interface BookMapper {
    
    
    @Select("select id, type, name, description from ssm_db.tb_book")
    List<Book> findAll();

    @Select("select id, type, name, description from ssm_db.tb_book where id = #{id}")
    Book findById(Integer id);

    // @Insert("insert into ssm_db.tb_book values (null,#{type},#{name},#{description})")
    @Insert("insert into ssm_db.tb_book(type, name, description) values (#{type},#{name},#{description})")
    void save(Book book);

    @Update("update ssm_db.tb_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    void update(Book book);

    @Delete("delete from ssm_db.tb_book where id = #{id}")
    void delete(Integer id);

    Page<Book> queryPageByCondition(@Param("condition") String condition);
}

2.4、编写BookMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.mapper.BookMapper">
    <select id="queryPageByCondition" parameterType="string" resultType="book">
        select * from ssm_db.tb_book
        <where>
            <if test="condition!=null and condition.length>0">name like concat('%', #{condition},'%')</if>
        </where>
    </select>
</mapper>

注:BookMapper.xml文件必须要和BookMapper接口在同包下(自动绑定映射规则)

2.5、创建jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
jdbc.initialSize=10
jdbc.maxActive=20

2.6、编写BookService接口(Service层)

public interface BookService {
    
    
    /**
     * 查询全部
     *
     * @return
     */
    List<Book> findAll();

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    Book findById(Integer id);

    /**
     * 保存
     *
     * @param book
     * @return
     */
    void save(Book book);

    /**
     * 修改
     *
     * @param book
     * @return
     */
    void update(Book book);

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    void delete(Integer id);

    /**
     * 分页查询图书信息
     * @param queryPageBean
     * @return 
     */
    PageResult queryPage(QueryPageBean queryPageBean);
}

2.7、编写BookServiceImpl实现类

@Service
@Transactional
public class BookServiceImpl implements BookService {
    
    
    @Autowired
    private BookMapper bookMapper;

    @Override
    public List<Book> findAll() {
    
    
        return bookMapper.findAll();
    }

    @Override
    public Book findById(Integer id) {
    
    
        return bookMapper.findById(id);
    }

    @Override
    public void save(Book book) {
    
    
        bookMapper.save(book);
    }

    @Override
    public void update(Book book) {
    
    
        bookMapper.update(book);
    }

    @Override
    public void delete(Integer id) {
    
    
        bookMapper.delete(id);
    }

    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
    
    
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String condition = queryPageBean.getCondition();

        // 使用mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        Page<Book> page = bookMapper.queryPageByCondition(condition);
        long total = page.getTotal();
        List<Book> rows = page.getResult();
        return new PageResult(total, rows);
    }
}

2.8、编写JDBCConfig配置类

/**
 * @author MrZhang
 * @description  数据库连接信息
 * @create 2022-04-25 15:42
 */
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;
    @Value("${jdbc.initialSize}")
    private int initialSize;
    @Value("${jdbc.maxActive}")
    private int maxActive;

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

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
    
    
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        return transactionManager;
    }
}

2.9、编写MybatisConfig配置类

/**
 * @author MrZhang
 * @description  整合mybatis数据源
 * @create 2022-04-25 15:45
 */
public class MybatisConfig {
    
    
    /**
     * 获取SqlSessionFactoryBean
     * @param dataSource
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
    
    
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.zhang.domain");

        //设置分页的拦截器
        PageInterceptor pageInterceptor = new PageInterceptor();
        //创建插件需要的参数集合
        Properties properties = new Properties();
        //配置数据库方言 为oracle
        properties.setProperty("helperDialect", "mysql");
        //配置分页的合理化数据
        properties.setProperty("reasonable", "true");
        pageInterceptor.setProperties(properties);
        //将拦截器设置到sqlSessionFactory中
        factoryBean.setPlugins(new Interceptor[] {
    
    pageInterceptor});

        return factoryBean;
    }

    /**
     * mapper扫描包
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
    
    
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.zhang.mapper");
        return msc;
    }
}

2.10、编写SpringConfig配置类

/**
 * @author MrZhang
 * @description  关于Spring的配置
 * @create 2022-04-25 15:44
 */
@Configuration
@ComponentScan({
    
     "com.zhang.service"})
@PropertySource("classpath:jdbc.properties")
@Import({
    
    JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
    
    
}

2.11、编写MVCConfig配置类

/**
 * @author MrZhang
 * @description  关于SpringMVC的配置
 * @create 2022-04-20 10:42
 */
/*
    代替SpringMvc的配置文件
    1、扫描组件  2、视图解析器     3、view-controller   4、default-servlet-handler
    5、mvc注解驱动   6、文件上传解析器   7、异常处理  8、拦截器
 */
// 将当前类表示为一个配置类
@Configurable
// 1、扫描组件
@ComponentScan("com.zhang.controller")
// 5、mvc注解驱动
@EnableWebMvc
public class MVCConfig implements WebMvcConfigurer {
    
    
    // 2、配置生成模板解析器
    @Bean
    public ITemplateResolver templateResolver() {
    
    
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        // ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过 WebApplicationContext 的方法获得
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(
            webApplicationContext.getServletContext());
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }

    // 生成模板引擎并为模板引擎注入模板解析器
    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
    
    
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

    // 生成视图解析器并未解析器注入模板引擎
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
    
    
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }

    // 4、default-servlet-handler 使用默认的servlet处理静态资源
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    
    
        configurer.enable();
    }

    // 6、文件上传解析器
    @Bean
    public MultipartResolver multipartResolver() {
    
    
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(104857600);
        multipartResolver.setMaxInMemorySize(4096);
        multipartResolver.setDefaultEncoding("UTF-8");
        return multipartResolver;
    }

    // 7、异常处理
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
    
    
        SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
        Properties prop = new Properties();
        prop.setProperty("java.lang.ArithmeticException", "error");
        exceptionResolver.setExceptionMappings(prop);
        exceptionResolver.setExceptionAttribute("exception");
        resolvers.add(exceptionResolver);
    }

    // 8、拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    

    }
}

注:所有配置文件可根据需求进行配置

2.12、web容器初始化

/**
 * @author MrZhang
 * @description  web工程的初始化类,用来代替web.xml
 * @create 2022-05-18 10:20
 */
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    

    /**
     * 指定spring的配置类
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
    
    
        return new Class[]{
    
    SpringConfig.class};
    }


    /**
     * 指定SpringMVC的配置类
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
    
    
        return new Class[]{
    
    MVCConfig.class};
    }

    /**
     * 指定DispatcherServlet的映射规则,即url-pattern
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
    
    
        return new String[]{
    
    "/"};
    }

    /**
     * 注册过滤器
     *
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
    
    
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceRequestEncoding(true);
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        return new Filter[]{
    
    encodingFilter, hiddenHttpMethodFilter};
    }
}

3、前端页面


前端采用element-ui进行页面展示

<!DOCTYPE html>

<html>

    <head>

        <!-- 页面meta -->

        <meta charset="utf-8">

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

        <title>图书管理</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.condition" style="width: 200px;"
                                  class="filter-item"></el-input>

                        <el-button @click="queryPage()" 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 class="pagination-container">
                        <el-pagination
                                       class="pagiantion"
                                       @current-change="handleCurrentChange"
                                       :current-page="pagination.currentPage"
                                       :page-size="pagination.pageSize"
                                       layout="total, prev, pager, next, jumper"
                                       :total="pagination.total">
                        </el-pagination>
                    </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: {
      
         // 分页相关属性
                    currentPage: 1,
                    pageSize: 5,
                    total: 100,
                    condition: null,
                },
                dataList: [],//当前页要展示的列表数据
                formData: {
      
      },//表单数据
                dialogFormVisible: false,//控制表单是否可见
                dialogFormVisible4Edit: false,//编辑表单是否可见
                rules: {
      
      //校验规则
                    type: [{
      
      required: true, message: '图书类别为必填项', trigger: 'blur'}],
                    name: [{
      
      required: true, message: '图书名称为必填项', trigger: 'blur'}]
                }
            },

            //钩子函数,VUE对象初始化完成后自动执行
            created() {
      
      
                this.queryPage();
            },

            methods: {
      
      
                //列表
                queryPage() {
      
      
                    // 组装分页请求相关数据
                    let param = {
      
      
                        currentPage: this.pagination.currentPage,
                        pageSize: this.pagination.pageSize,
                        condition: this.pagination.condition,
                    }
                    // 发送ajax请求,获取图书信息
                    axios.post("/book/queryPage", param).then((res) => {
      
      
                        this.dataList = res.data.rows;
                        this.pagination.total = res.data.total;
                    });
                },

                //弹出添加窗口
                handleCreate() {
      
      
                    // 每次弹出新增窗口,就清空文本框中的数据
                    this.resetForm();
                    // 让表单显示
                    this.dialogFormVisible = true;
                },

                //重置表单
                resetForm() {
      
      
                    this.formData = {
      
      };
                },

                //添加
                handleAdd() {
      
      
                    // 表单校验
                    this.$refs['dataAddForm'].validate((valid) => {
      
      
                        if (valid) {
      
           // 表单校验成功
                            // 发送ajax请求,进行添加操作
                            axios.post("/book", this.formData).then((res) => {
      
      
                                if (res.data.flag) {
      
      
                                    // 关闭弹层
                                    this.dialogFormVisible = false;
                                    this.$message.success(res.data.message);
                                } else {
      
      
                                    this.$message.error(res.data.message);
                                }
                            }).finally((res) => {
      
      
                                this.queryPage();
                            });
                        } else {
      
           // 表单校验失败
                            this.$message.error("表单校验失败!");
                        }
                    });
                },

                //弹出编辑窗口
                handleUpdate(row) {
      
      
                    // 先根据id查询数据    row.id  查询条件
                    // console.log(row);
                    // 发送ajax请求,根据id查询图书信息
                    axios.get("/book/" + row.id).then((res) => {
      
      
                        // 将查询到的数据赋值给表单数据
                        if (res.data.flag) {
      
      
                            this.formData = res.data.data;
                        } else {
      
      
                            this.$message.error(res.data.message);
                        }
                    });
                    this.dialogFormVisible4Edit = true;
                },

                //编辑
                handleEdit() {
      
      
                    // 表单校验
                    this.$refs['dataEditForm'].validate((valid) => {
      
      
                        if (valid) {
      
      
                            // 发送ajax请求,进行修改操作
                            axios.put('/book', this.formData).then((res) => {
      
      
                                if (res.data.flag) {
      
      
                                    // 关闭弹层
                                    this.dialogFormVisible4Edit = false;
                                    this.$message.success(res.data.message);
                                } else {
      
      
                                    this.$message.error(res.data.message);
                                }
                            }).finally(() => {
      
      
                                // 重新进行查询操作
                                this.queryPage();
                            });
                        } else {
      
      
                            this.$message.error('表单校验失败!');
                        }
                    });
                },

                // 删除
                handleDelete(row) {
      
      
                    // console.log(row.id);
                    // 提示用户
                    this.$confirm('此操作将永久删除, 是否继续?', '提示', {
      
      
                        type: 'warning'
                    }).then(() => {
      
      
                        // 发送ajax请求,删除图书
                        axios.delete("/book/" + row.id).then((res) => {
      
      
                            if (res.data.flag) {
      
      
                                this.$message.success(res.data.message);
                            } else {
      
      
                                this.$message.error(res.data.message);
                            }
                        }).finally(() => {
      
      
                            // 重新进行查询操作
                            this.queryPage();
                        });
                    }).catch(() => {
      
      
                        // 给出用户提示
                        this.$message.info("用户取消操作");
                    });
                },

                // 传递当前页码并重新进行分页查询
                handleCurrentChange(currentPage) {
      
      
                    // console.log(currentPage);
                    this.pagination.currentPage = currentPage;
                    this.queryPage();
                }
            }
        })
    </script>

</html>

4、编写controller层


@RestController
@RequestMapping("/book")
public class BookController {
    
    
    @Autowired
    private BookService bookService;

    /**
     * 分页查询图书信息
     *
     * @return
     */
    @PostMapping("/queryPage")
    public PageResult queryPage(@RequestBody QueryPageBean queryPageBean) {
    
    
        return bookService.queryPage(queryPageBean);
    }

    /**
     * 修改图书
     *
     * @param book
     * @return
     */
    @PutMapping
    public Result modify(@RequestBody Book book) {
    
    
        try {
    
    
            bookService.update(book);
            return new Result(true, MessageConstant.UPDATE_BOOK_SUCCESS);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return new Result(false, MessageConstant.UPDATE_BOOK_FAIL);
        }
    }

    /**
     * 根据id查询图书
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result queryById(@PathVariable Integer id) {
    
    
        try {
    
    
            Book book = bookService.findById(id);
            return new Result(true, MessageConstant.QUERY_BOOK_SUCCESS, book);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_BOOK_FAIL);
        }
    }

    /**
     * 添加图书
     *
     * @param book
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Book book) {
    
    
        try {
    
    
            bookService.save(book);
            return new Result(true, MessageConstant.ADD_BOOK_SUCCESS);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_BOOK_FAIL);
        }
    }

    /**
     * 根据id删除图书
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
    
    
        try {
    
    
            bookService.delete(id);
            return new Result(true, MessageConstant.DELETE_BOOK_SUCCESS);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_BOOK_FAIL);
        }
    }


    /**
     * 查询全部图书
     *
     * @return
     */
    @GetMapping("queryAll")
    public Result query() {
    
    
        try {
    
    
            List<Book> books = bookService.findAll();
            return new Result(true, MessageConstant.QUERY_BOOK_SUCCESS, books);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_BOOK_FAIL);
        }
    }
}

至此,SSM注解版整合完毕!

猜你喜欢

转载自blog.csdn.net/zhang_0202/article/details/124846705