SSM - 整合

本文最后更新于:5 个月前

SSM框架 - 整合

SSM整合

整合配置

https://www.bilibili.com/video/BV1Fi4y1S7ix/?p=59

整合MyBatis

https://opn90.top/2023/01/27/SSM/#Spring%E6%95%B4%E5%90%88MyBatis

整合SpringMvc

https://opn90.top/2023/02/08/SSM-SpringMVC/#SpringMVC%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B

创建模块

新建-Maven-maven-archetype-webapp

添加目录-在main下-java,resources

导入坐标

3个spring坐标,3个spring整合mybatis坐标,druid数据源,junit,servletweb容器,jackson

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

创建包层次结构

config - 配置文件

controller - 表现层 控制器

dao - 数据层接口

与数据库交互的代码,自动代理,无需实现类

domain - 存放实体类

service - 业务层接口

service.impl - 业务层实现类

(test - 测试)

配置类


  • config
JdbcConfig
import javax.sql.DataSource;

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;
    }
}
MyBatisConfig
import javax.sql.DataSource;    

public class MyBatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.opn.domain");
        return factoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.opn.dao");
        return msc;
    }
}
ServletConfig/ServletContainersInitConfig
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[]{"/"};
    }

    //乱码处理
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}
SpringConfig
@Configuration
@ComponentScan({"com.opn.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
SpringMvcConfig
@Configuration
@ComponentScan("com.opn.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
resources - jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/...?useSSL=false
jdbc.username=root
jdbc.password=...

功能模块

表 - 实体类 - dao - service - controller

forssm - tb_user

username password money

实体类

public class User {
    private String username;
    private String password;
    private Integer money;
    
    get/set/tostring...
    (fn + alt + insert)

}

dao

public interface UserDao {

    @Insert("insert into tb_user values(#{username},#{password},#{money})")
    public int save(User user);

    @Update("update tb_user set username=#{username},password=#{password},money=#{money} where username=#{username}")
    public int update(User user);

    @Delete("delete from tb_user where username = #{username}")
    public int delete(String username);

    //表里没设id...先用username
    @Select("select * from tb_user where username= #{username}")
    public User getById(String username);

    @Select("select * from tb_user")
    public List<User> getAll();
}

service

业务层接口

@Transactional
public interface UserService {

    /* 需要添加相应的文档注释 */

    public boolean save(User user);

    public boolean update(User user);

    public boolean delete(String username);

    public User getById(String username);

    public List<User> getAll();
}

业务层实现类

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public boolean save(User user) {
        return userDao.save(user)>0;
    }

    public boolean update(User user) {
        return userDao.update(user)>0;
    }

    public boolean delete(String username) {
        return userDao.delete(username)>0;
    }

    public User getById(String username) {
        return userDao.getById(username);
    }

    public List<User> getAll() {
        return userDao.getAll();
    }
}

自动装配时报错,修改报错类型设置

@Autowired
private UserDao userDao;    

controller

表现层

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(@RequestBody User user) {
        Boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR , flag);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        Boolean flag = userService.update(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR , flag);
    }

    @DeleteMapping("/{username}")
    public Result delete(@PathVariable String username) {
        Boolean flag = userService.delete(username);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR , flag);
    }

    @GetMapping("/{username}")
    public Result getById(@PathVariable String username) {
        User user = userService.getById(username);
        Integer code = user != null ? Code.GET_OK:Code.GET_ERR;
        String msg = user != null ? "查询成功":"查询失败";
        return new Result(code,user,msg);
    }

    @GetMapping
    public Result getAll() {
        List<User> userlist = userService.getAll();
        Integer code = userlist != null ? Code.GET_OK:Code.GET_ERR;
        String msg = userlist != null ? "查询成功":"查询失败";
        return new Result(code,userlist,msg);
    }
}

接口测试

  • 业务层实现类测试

UserServiceTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testgetAll(){
        List<User> user = userService.getAll();
        System.out.println(user);
    }
}
  • 表现层实现类测试

编辑配置 - 添加Tomcat本地服务器 - 部署标记工件(+ war)- 应用确定

postman

事务处理

SpringConfig中添加注解

@EnableTransactionManagement

JdbcConfig

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

业务层接口

@Transactional

静态资源访问

com.opn.config.SpringMvcSupport

@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/");
    }
}

在SpringMvcConfig中添加路径

@ComponentScan({"com.opn.controller","com.opn.config"})

前后端数据交互

Result类,Code类,静态资源访问类

静态界面

https://opn90.top/2023/02/08/SSM-SpringMVC/#SSM%E6%95%B4%E5%90%88-%E5%89%8D%E5%90%8E%E5%8F%B0%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92

拦截器

com.opn.interceptor

ProjectInterceptor配置类

@Configuration
public class ProjectInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

com.opn.config

SpringMvcSupport/就是静态资源访问通过的类 中添加 addInterceptors 方法

配置具体的拦截路径

@Autowired
private ProjectInterceptor projectInterceptor;

@Override
protected void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(projectInterceptor).addPathPatterns("/users");
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!