SpringMVC——SSM整合

68 阅读4分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情

流程分析

(1) 创建工程

  • 创建一个Maven的web工程

  • pom.xml添加SSM需要的依赖jar包

  • 编写Web项目的入口配置类,实现AbstractAnnotationConfigDispatcherServletInitializer重写以下方法

    • getRootConfigClasses() :返回Spring的配置类->需要==SpringConfig==配置类
    • getServletConfigClasses() :返回SpringMVC的配置类->需要==SpringMvcConfig==配置类
    • getServletMappings() : 设置SpringMVC请求拦截路径规则
    • getServletFilters() :设置过滤器,解决POST请求中文乱码问题

(2)SSM整合[==重点是各个配置的编写==]

  • SpringConfig

    • 标识该类为配置类 @Configuration

    • 扫描Service所在的包 @ComponentScan

    • 在Service层要管理事务 @EnableTransactionManagement

    • 读取外部的properties配置文件 @PropertySource

    • 整合Mybatis需要引入Mybatis相关配置类 @Import

      • 第三方数据源配置类 JdbcConfig

        • 构建DataSource数据源,DruidDataSouroce,需要注入数据库连接四要素, @Bean @Value
        • 构建平台事务管理器,DataSourceTransactionManager,@Bean
      • Mybatis配置类 MybatisConfig

        • 构建SqlSessionFactoryBean并设置别名扫描与数据源,@Bean
        • 构建MapperScannerConfigurer并设置DAO层的包扫描
  • SpringMvcConfig

    • 标识该类为配置类 @Configuration
    • 扫描Controller所在的包 @ComponentScan
    • 开启SpringMVC注解支持 @EnableWebMvc

(3)功能模块[与具体的业务模块有关]

  • 创建数据库表

  • 根据数据库表创建对应的模型类

  • 通过Dao层完成数据库表的增删改查(接口+自动代理)

  • 编写Service层[Service接口+实现类]

    • @Service

    • @Transactional

    • 整合Junit对业务层进行单元测试

      • @RunWith
      • @ContextConfiguration
      • @Test
  • 编写Controller层

    • 接收请求 @RequestMapping @GetMapping @PostMapping @PutMapping @DeleteMapping

    • 接收数据 简单、POJO、嵌套POJO、集合、数组、JSON数据类型

      • @RequestParam
      • @PathVariable
      • @RequestBody
    • 转发业务层

      • @Autowired
    • 响应结果

      • @ResponseBody

步骤1:创建Maven的web项目

步骤2:添加依赖

<modelVersion>4.0.0</modelVersion>

<groupId>com.itheima</groupId>
<artifactId>springmvc_08_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.10.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.10.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
  </dependency>

  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
  </dependency>

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

  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</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>

步骤3:创建项目包结构

image.png

  • config目录存放的是相关的配置类
  • controller编写的是Controller类
  • dao存放的是Dao接口,因为使用的是Mapper接口代理方式,所以没有实现类包
  • service存的是Service接口,impl存放的是Service实现类
  • resources:存入的是配置文件,如Jdbc.properties
  • webapp:目录可以存放静态资源
  • test/java:存放的是测试类

步骤4:创建SpringConfig配置类

@Configuration
@ComponentScan({"com.miles.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

步骤5:创建JdbcConfig配置类

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

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

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

步骤6:创建MybatisConfig配置类

public class MybatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setTypeAliasesPackage("com.miles.domain");
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;

    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.miles.dao");
        return mapperScannerConfigurer;
    }
}

步骤7:创建jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false
jdbc.username=root
jdbc.password=123456

步骤8:创建SpringMVC配置类

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

}

步骤9:创建Web项目入口配置类

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[]{"/"};
    }
}

功能模块开发

需求:对表tbl_book进行新增、修改、删除、根据ID查询和查询所有

步骤1:创建数据库及表

步骤2:编写模型类

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

步骤3:编写Dao接口

public interface BookDao {
    @Insert("insert into tbl_book VALUES (null,#{type},#{name},#{description})")
    public void save(Book book);
    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public void update(Book book);
    @Delete("delete from tbl_book where id = #{id}")
    public void delete(Integer id);
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
    @Select("select * from tbl_book")
    public List<Book> getAll();
}

步骤4:编写Service接口和实现类

@Transactional
public interface BookService {
    /**
     * 保存
     * @param book
     * @return
     */
    public boolean save(Book book);

    public boolean update(Book book);

    public boolean delete(Integer id);

    public Book getById(Integer id);

    public List<Book> getAll();
}
Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    public boolean save(Book book) {
        bookDao.save(book);

        return true;
    }

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

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

    public Book getById(Integer id) {
        Book book = bookDao.getById(id);
        return book;
    }

    public List<Book> getAll() {
        List<Book> bookList = bookDao.getAll();

        return bookList;
    }
}

步骤5:编写Contorller类

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

    @PostMapping
    public boolean save(@RequestBody Book book) {
        return  bookService.save(book);

    }

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);

    }
   @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
       return bookService.delete(id);

    }
    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        return book;
    }
   @GetMapping
    public List<Book> getAll() {
        List<Book> bookList = bookService.getAll();

        return bookList;
    }
}

单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class ServiceTest {
    @Autowired
    private BookService bookService;


   @Test
    public void Test1(){
       Book book = bookService.getById(1);
       System.out.println(book);

   }
    @Test
    public void Test2(){
        List<Book> books = bookService.getAll();
        System.out.println(books);

    }
}

PostMan测试

image.png