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

【Java从零到架构师第③季】【38】分模块构建SSM项目

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

【Java从零到架构师第③季】【38】分模块构建SSM项目


持续学习&持续更新中…

守破离


【Java从零到架构师第③季】【38】分模块构建SSM项目

module—parentmodule—daomodule—servicemodule—web参考

module—parent

pom.xml:



    4.0.0

    programmer.lp.ssmdividing
    SSM_dividing_module
    1.0.0

    
    pom

    
    
        dao
        service
        web
    

    
        UTF-8
    

module—dao

dao层是数据访问层,是MyBatis干活的地方。

pom.xml:



    4.0.0

    
        SSM_dividing_module
        programmer.lp.ssmdividing
        1.0.0
    

    dao

    
        
            mysql
            mysql-connector-java
            5.1.49
        
        
            com.alibaba
            druid
            1.2.8
        
        
            org.mybatis
            mybatis
            3.5.7
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.13.0
        
        
            org.springframework
            spring-jdbc
            5.2.8.RELEASE
        
        
            org.mybatis
            mybatis-spring
            2.0.6
        
        
            org.springframework
            spring-context
            5.2.8.RELEASE
        
        
            ch.qos.logback
            logback-classic
            1.2.7
        
        
            junit
            junit
            4.13.2
            test
        
    

db.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_mybatis?useSSL=false
jdbc.username=root
jdbc.password=root

mybatis.typeAliasesPackage=programmer.lp.domain
mybatis.mapperScanPackage=programmer.lp.dao
mybatis.configLocation=mybatis-config.xml

mybatis-config.xml:




    
        
    

Converter:

public class DateConverter implements Converter {
    private Set formats;
    public void setFormats(Set formats) {
        this.formats = formats;
    }
    @Override
    public Date convert(String dateStr) {
        if (null == formats || formats.isEmpty()) return null;
        for (String format : formats) {
            try {
                return new SimpleDateFormat(format).parse(dateStr);
            } catch (Exception e) {
                System.out.println("不支持:<" + format + ">格式!");
            }
        }
        return null;
    }
}

Dao:

public interface SkillDao {
    @Insert("INSERT INTO skill(name, level) VALUES(#{name}, #{level})")
    @SelectKey(statement = "SELECT LAST_INSERT_ID()",
            keyProperty = "id",
            keyColumn = "id",
            before = false,
            resultType = Integer.class)
    boolean insert(Skill skill);

    @Delete(("DELETE FROM skill WHERe id = #{id}"))
    boolean delete(Integer id);

    @Update("UPDATE skill SET name = #{name}, level = #{level} WHERe id = #{id}")
    boolean update(Skill skill);

    @Select("SELECT id, created_time, name, level FROM skill WHERe id = #{id}")
    Skill get(Integer id);

    @Select("SELECT id, created_time, name, level FROM skill")
    List list();
}

DaoConfiguration:

@PropertySource("classpath:db.properties")
@MapperScan("${mybatis.mapperScanPackage}")
public class DaoConfiguration {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Value("${mybatis.typeAliasesPackage}")
    private String typeAliasesPackage;
    @Value("${mybatis.configLocation}")
    private String configLocation;

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

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        Resource location = new ClassPathResource(configLocation);
        sqlSessionFactoryBean.setConfigLocation(location);
        return sqlSessionFactoryBean;
    }

    @Bean
    public DateConverter dateConverter() {
        DateConverter dateConverter = new DateConverter();
        Set set = new linkedHashSet<>();
        set.add("yyyy-MM-dd");
        set.add("yyyy/MM/dd");
        set.add("yyyy年MM月dd日");
        dateConverter.setFormats(set);
        return dateConverter;
    }
}

module—service

service层是业务层,一般需要Spring的事务管理。

pom.xml:



    4.0.0

    
        SSM_dividing_module
        programmer.lp.ssmdividing
        1.0.0
    

    service

    
        
            programmer.lp.ssmdividing
            dao
            1.0.0
        
        
            org.aspectj
            aspectjweaver
            1.9.6
        
        
            org.aspectj
            aspectjrt
            1.9.6
        
    


ServiceConfiguration:

@EnableTransactionManagement
@ComponentScan("programmer.lp.service")
public class ServiceConfiguration {

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

}

SkillService:

@Service
@Transactional
public class SkillServiceImpl implements SkillService {
    @Autowired
    private SkillDao dao;

    @Override
    public boolean remove(Integer id) {
        return dao.delete(id);
    }

    @Override
    public boolean save(Skill skill) {
        final Integer skillId = skill.getId();
        if (skillId == null || skillId < 1) {
            boolean result = dao.insert(skill);
            System.out.println(skill.getId());
            return result;
        }
        return dao.update(skill);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Skill get(Integer id) {
        return dao.get(id);
    }

    @Transactional(readonly = true)
    @Override
    public List list() {
        return dao.list();
    }
}
module—web

web层就是controller层(相当于servlet),是SpringMVC干活的地方。



    4.0.0

    
        SSM_dividing_module
        programmer.lp.ssmdividing
        1.0.0
    

    web

    war

    
        
            programmer.lp.ssmdividing
            service
            1.0.0
        
        
            org.springframework
            spring-webmvc
            5.2.8.RELEASE
        
        
            javax.servlet.jsp
            javax.servlet.jsp-api
            2.3.3
            provided
        
        
            javax.servlet
            javax.servlet-api
            4.0.1
            provided
        
        
            jstl
            jstl
            1.2
        
        
            taglibs
            standard
            1.1.2
        
        
            commons-fileupload
            commons-fileupload
            1.4
        
    

WebConfiguration:

@EnableWebMvc
@ComponentScan("programmer.lp.controller")
public class WebConfiguration implements WebMvcConfigurer {
    @Autowired
    private DateConverter dateConverter;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(dateConverter);
    }
    
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }

    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }

    @Override
    public void configureMessageConverters(List> converters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setDefaultCharset(StandardCharsets.UTF_8);
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        jacksonConverter.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(stringConverter);
        converters.add(jacksonConverter);
    }
}

Controller:


@Controller
@RequestMapping("/skill")
public class SkillController {
    @Autowired
    private SkillService service;

    @PostMapping("/remove")
    @ResponseBody
    public String remove(Integer id) {
        return service.remove(id) ? "删除成功" : "删除失败";
    }

    @PostMapping("/save")
    @ResponseBody
    public String save(Skill skill) {
        return service.save(skill) ? "保存成功" : "保存失败";
    }

    @GetMapping("/get")
    @ResponseBody
    public Skill get(Integer id) {
        return service.get(id);
    }

    @GetMapping("/list")
    @ResponseBody
    public List list() {
        return service.list();
    }
}

Initializer:

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{DaoConfiguration.class, ServiceConfiguration.class};
    }

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

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

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        FilterRegistration.Dynamic encodingFilter =
                servletContext.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
        encodingFilter.setInitParameter("encoding", "UTF-8");
        encodingFilter.addMappingForUrlPatterns(null, false, "/*");
    }
}
参考

小码哥-李明杰: Java从0到架构师③进阶互联网架构师.


本文完,感谢您的关注支持!


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

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

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