栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SSM整合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SSM整合

目录

准备数据库表

1.框架整合

1.1导坐标

1.2准备配置文件jdbc.properties

1.3配置类整合框架

1.4开启事务

2.业务层

2.1 pojo

         2.2 dao

2.3 service

2.4 业务层测试

3.表现层

3.1数据封装

3.2controller

3.3异常处理

4.前后台联合

4.1静态资源放行

4.2前后台联合


准备数据库表:
-- auto-generated definition
CREATE TABLE tbl_book
(
  id          INT AUTO_INCREMENT
    PRIMARY KEY,
  type        VARCHAr(20)  NULL,
  name        VARCHAr(50)  NULL,
  description VARCHAr(255) NULL
)
  ENGINE = InnoDB
  CHARSET = utf8;

1.框架整合

1.1导坐标
    

        
        
            org.springframework
            spring-webmvc
            5.2.10.RELEASE
        

        
            org.springframework
            spring-jdbc
            5.2.10.RELEASE
        

        
            org.springframework
            spring-test
            5.2.10.RELEASE
            test
        

        
        
            org.mybatis
            mybatis
            3.5.5
        

        
            org.mybatis
            mybatis-spring
            1.3.0
        

        
            mysql
            mysql-connector-java
            8.0.21
        

        
        
            com.alibaba
            druid
            1.1.10
        


        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        

        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.8
        

        
            junit
            junit
            4.12
            test
        

    

    
        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.1
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.6
                    1.6
                
            
        
    

1.2准备配置文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=1234

1.3配置类整合框架
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 druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }

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



public class MybatisConfig {

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

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




public class ServletCongif extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}



@Configuration
@ComponentScan("com.service")
@PropertySource("classpath:jdbc.properties")
//@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement//事务
public class SpringConfig {
}




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

}

1.4开启事务
@Transactional
public interface BookService {

    public boolean add(Book book);

    public boolean update(Book book);

    public boolean delete(Integer id);

    public Book getById(Integer id);

    public List getAll();
}

2.业务层

2.1 pojo
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String 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;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + ''' +
                ", name='" + name + ''' +
                ", description='" + description + ''' +
                '}';
    }
}

2.2 dao
public interface BookDao {

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

2.3service
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public boolean add(Book book) {
        int add = bookDao.add(book);
        return add > 0;
    }

    @Override
    public boolean update(Book book) {
        int update = bookDao.update(book);
        return update > 0;
    }

    @Override
    public boolean delete(Integer id) {
        int delete = bookDao.delete(id);
        return delete > 0;
    }

    @Override
    public Book getById(Integer id) {
         return bookDao.getById(id);
    }

    @Override
    public List getAll() {
         return bookDao.getAll();
    }
}

2.4业务层测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
    @Autowired
    private BookService bookService;

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

    @Test
    public void testGetAll(){
        List all = bookService.getAll();
        System.out.println(all);
    }
}

3.表现层

3.1数据封装
public class Result {
    private Integer code;
    private Object data;
    private String message;

    public Result() {
    }

    public Result(Integer code, Object data, String massage) {
        this.data = data;
        this.code = code;
        this.message = massage;
    }

    public Result(Integer code, Object data) {
        this.data = data;
        this.code = code;
    }

    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 getMessage() {
        return message;
    }

    public void setMessage(String massage) {
        this.message = massage;
    }
}



public class Code {
    public static final Integer ADD_OK = 20011;
    public static final Integer DELETE_0K = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;

    public static final Integer ADD_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20048;

}

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


    @PostMapping
    public Result add(@RequestBody Book book) {
        boolean flag = bookService.add(book);
        return new Result(flag ? Code.ADD_OK : Code.ADD_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_0K : 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 massage = book != null ? "" : "数据查询失败,请重试";
        return new Result(code, book, massage);
    }

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

3.3异常处理
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;
    }
}



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

}




@RestControllerAdvice
public class ProjectExceptionAdvice {

    //系统异常处理
    @ExceptionHandler(SystemException.class)//定义处理哪一种异常
    public Result doSystemException(SystemException ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员
        return new Result(ex.getCode(), null, ex.getMessage());
    }


    //业务异常处理
    @ExceptionHandler(BusinessException.class)//定义处理哪一种异常
    public Result doBusinessException(BusinessException ex) {
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    //其他异常处理
    @ExceptionHandler(Exception.class)//定义处理哪一种异常
    public Result doException(BusinessException ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员
        return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙,请稍后再试");
    }
}


public class Code {

    public static final Integer SYSTEM_ERR = 50001;
    public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
    public static final Integer SYSTEM_UNKNOWN_ERR = 59999;
    public static final Integer BUSINESS_ERR = 60002;
}
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public boolean add(Book book) {
        try {
            int add = bookDao.add(book);
            return add > 0;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
        }
    }

    @Override
    public boolean update(Book book) {
        try {
            int update = bookDao.update(book);
            return update > 0;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
        }
    }

    @Override
    public boolean delete(Integer id) {
        if (id <= 0) {
            throw new BusinessException(Code.BUSINESS_ERR, "无效的id");
        }
        try {
            int delete = bookDao.delete(id);
            return delete > 0;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
        }
    }

    @Override
    public Book getById(Integer id) {
        if (id <= 0) {
            throw new BusinessException(Code.BUSINESS_ERR, "无效的id");
        }
        try {
            return bookDao.getById(id);
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
        }
    }

    @Override
    public List getAll() {
        try {
            return bookDao.getAll();
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
        }
    }
}

4.前后台联合

4.1静态资源放行
//静态资源放行
@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/");
    }
}



@Configuration
@ComponentScan({"com.controller","com.config"})
@EnableWebMvc
public class SpringMvcConfig {

}

4.2前后台联合



    
    
    
    SpringMVC案例
    

    
    
    
    




    
        图书管理
    

    
        
            
                
                查询
                新建
            
            
            
                
                
                
                
                
                    
                
            

            
            
                
                    
                        
                            
                                
                                    
                                
                            
                            
                                
                                    
                                
                            
                        
                        
                            
                                
                                    
                                
                            
                        
                    
                    
                        取消
                        确定
                    
                
            

            
            
                
                    
                        
                            
                                
                                    
                                
                            
                            
                                
                                    
                                
                            
                        
                        
                            
                                
                                    
                                
                            
                        
                    
                    
                        取消
                        确定
                    
                
            
        
    











转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/951077.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号