电子商务网站设计的基本流程,望京SOHO网站建设,基层建设论文查询官方网站,产品盘网站建设最近在回顾和总结一些技术#xff0c;想到了把之前比较火的 SSM 框架重新搭建出来#xff0c;作为一个小结#xff0c;同时也希望本文章写出来能对大家有一些帮助和启发#xff0c;因本人水平有限#xff0c;难免可能会有一些不对之处#xff0c;欢迎各位大神拍砖指教想到了把之前比较火的 SSM 框架重新搭建出来作为一个小结同时也希望本文章写出来能对大家有一些帮助和启发因本人水平有限难免可能会有一些不对之处欢迎各位大神拍砖指教共同进步。本文章示例使用 IntelliJ IDEA 来开发JDK 使用 11 版本其余各框架和技术基本上使用了文章撰写当时的最新版本。好的下面直接进入正题。打开 IntelliJ IDEAFile New Project Maven选中“Create from archetype”然后再选中“org.apache.maven.archetypes:maven-archetype-webapp”Next输入项目的“GroupId”、“ArtifactId”和VersionNext指定“Maven home directory”等配置Next修改Project NameFinish打开项目添加一些必要的目录最终项目框架目录图如下修改pom.xml文件指定各依赖和插件的版本等信息UTF-81111115.2.3.RELEASE4.131.18.103.3.12.3.291.1.213.18.0.191.24.0.12.3.32.9.23.92.10.21.3.1.Final2.13.01.7.303.1.03.1.03.8.13.0.0-M43.2.33.0.0-M13.0.0-M1在标签里面管理各依赖的版本号org.springframeworkspring-context${spring.version}org.springframeworkspring-context-support${spring.version}org.springframeworkspring-beans${spring.version}org.springframeworkspring-jdbc${spring.version}org.springframeworkspring-aop${spring.version}org.springframeworkspring-aspects${spring.version}org.springframeworkspring-webmvc${spring.version}org.springframeworkspring-test${spring.version}testjunitjunit${junit.version}testorg.projectlomboklombok${lombok.version}providedcom.baomidoumybatis-plus${mybatis-plus.version}com.baomidoumybatis-plus-generator${mybatis-plus.version}testtrueorg.freemarkerfreemarker${freemarker.version}testtruecom.alibabadruid${druid.version}com.github.jsqlparserjsqlparser${jsqlparser.version}mysqlmysql-connector-java${mysql-connector.version}javax.servlet.jsp.jstljstl-api${jstl-api.version}javax.servletjavax.servlet-api${servlet-api.version}providedjavax.servlet.jspjavax.servlet.jsp-api${jsp-api.version}providedio.springfoxspringfox-swagger2${springfox-swagger.version}io.springfoxspringfox-swagger-ui${springfox-swagger.version}org.apache.commonscommons-lang3${commons-lang3.version}com.fasterxml.jackson.corejackson-databind${jackson.version}com.fasterxml.jackson.corejackson-annotations${jackson.version}compileorg.mapstructmapstruct${mapstruct.version}org.slf4jslf4j-api${slf4j.version}org.apache.logging.log4jlog4j-slf4j-impl${log4j.version}添加项目依赖org.springframeworkspring-context-supportorg.springframeworkspring-jdbcorg.springframeworkspring-aspectsorg.springframeworkspring-webmvcorg.springframeworkspring-testjunitjunitorg.projectlomboklombokcom.baomidoumybatis-pluscom.baomidoumybatis-plus-generatororg.freemarkerfreemarkercom.alibabadruidmysqlmysql-connector-javajavax.servlet.jsp.jstljstl-apijavax.servletjavax.servlet-apijavax.servlet.jspjavax.servlet.jsp-apiio.springfoxspringfox-swagger2io.springfoxspringfox-swagger-uiorg.apache.commonscommons-lang3com.fasterxml.jackson.corejackson-databindorg.mapstructmapstructorg.apache.logging.log4jlog4j-slf4j-impl管理ssmorg.apache.maven.pluginsmaven-clean-plugin${clean.plugin.version}org.apache.maven.pluginsmaven-resources-plugin${resources.plugin.version}${project.build.sourceEncoding}org.apache.maven.pluginsmaven-compiler-plugin${compiler.plugin.version}${maven.compiler.source}${maven.compiler.target}${project.build.sourceEncoding}org.projectlomboklombok${lombok.version}org.mapstructmapstruct-processor${mapstruct.version}-Amapstruct.defaultComponentModelspring-Amapstruct.unmappedTargetPolicyIGNOREorg.apache.maven.pluginsmaven-surefire-plugin${surefire.plugin.version}org.apache.maven.pluginsmaven-war-plugin${war.plugin.version}org.apache.maven.pluginsmaven-install-plugin${install.plugin.version}org.apache.maven.pluginsmaven-deploy-plugin${deploy.plugin.version}依赖配置好之后开始整合。先整合Log4j2日志在项目classpath目录(src/main/resources)下创建log4j2.xml文件添加Log4j2日志配置再整合 Spring 和 Mybatis本次还整合了 Mybatis Plus 开源框架新建 src/main/resources/mybatis/mybatis-config.xml 文件/pPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd新建 src/main/resources/properties/jdbc.properties 文件配置数据源连接信息jdbc.driver-class-namecom.mysql.cj.jdbc.Driverjdbc.urljdbc:mysql://127.0.0.1:3306/ssm?useUnicodetrueuseSSLfalsecharacterEncodingutf8serverTimezoneGMT%2B8jdbc.usernamerootjdbc.passwordroot新建 src/main/resources/spring/applicationContext-dao.xml 文件配置 Druid 数据源SqlSessionFactory 会话工厂Mybatis 的 Mapper 接口扫描等信息xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdcom.example.ssm.service.*com.example.ssm.mapper.*classcom.baomidou.mybatisplus.extension.plugins.PaginationInterceptor/classcom.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor/新建 src/main/resources/spring/applicationContext-tx.xml 文件配置事务xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxmlns:txhttp://www.springframework.org/schema/txxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd配置 Mybatis Plus 自动生成 Controller、Service 和 Mapper 文件// 自动代码生成器AutoGenerator autoGenerator new AutoGenerator();// 全局配置GlobalConfig globalConfig new GlobalConfig();String projectPath System.getProperty(user.dir);globalConfig.setOutputDir(projectPath /src/main/java);globalConfig.setAuthor(calvinit);globalConfig.setOpen(false);globalConfig.setFileOverride(true);autoGenerator.setGlobalConfig(globalConfig);// 数据源配置DataSourceConfig dataSourceConfig new DataSourceConfig();dataSourceConfig.setDbType(DbType.MYSQL);dataSourceConfig.setUrl(jdbc:mysql://127.0.0.1:3306/ssm?useUnicodetrueuseSSLfalsecharacterEncodingutf8serverTimezoneGMT%2B8);// dataSourceConfig.setSchemaName(public);dataSourceConfig.setDriverName(com.mysql.cj.jdbc.Driver);dataSourceConfig.setUsername(root);dataSourceConfig.setPassword(root);autoGenerator.setDataSource(dataSourceConfig);// 包配置PackageConfig packageConfig new PackageConfig();packageConfig.setParent(com.example.ssm);autoGenerator.setPackageInfo(packageConfig);// 自定义配置InjectionConfig injectionConfig new InjectionConfig() {Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarkerString templatePath /templates/mapper.xml.ftl;// 自定义输出配置List focList new ArrayList();// 自定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {Overridepublic String outputFile(TableInfo tableInfo) {tableInfo.setImportPackages(com.baomidou.mybatisplus.annotation.TableName);tableInfo.setConvert(true);// 自定义输出文件名return projectPath /src/main/resources/mapper/ tableInfo.getEntityName() Mapper StringPool.DOT_XML;}});injectionConfig.setFileOutConfigList(focList);autoGenerator.setCfg(injectionConfig);// 配置模板TemplateConfig templateConfig new TemplateConfig();// 配置自定义输出模板// templateConfig.setEntity(ConstVal.TEMPLATE_ENTITY_JAVA);// templateConfig.setService(ConstVal.TEMPLATE_SERVICE);// templateConfig.setController(ConstVal.TEMPLATE_CONTROLLER);templateConfig.setXml(null);autoGenerator.setTemplate(templateConfig);// 策略配置StrategyConfig strategy new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);// strategy.setSuperEntityClass(com.example.ssm.entity.BaseEntity);strategy.setEntityLombokModel(true);strategy.setEntityColumnConstant(true);strategy.setRestControllerStyle(true);// strategy.setSuperControllerClass(com.example.ssm.controller.BaseController);strategy.setInclude(t_user, t_group, t_user_group_relation);// strategy.setSuperEntityColumns(id);strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix(packageConfig.getModuleName() _);strategy.setEntityTableFieldAnnotationEnable(true);autoGenerator.setStrategy(strategy);autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());autoGenerator.execute();然后整合 Spring 和 Spring MVC其中对日期类型返回json作了自定义格式化处理import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializerProvider;import com.fasterxml.jackson.databind.module.SimpleModule;import java.io.IOException;import java.text.SimpleDateFormat;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.format.DateTimeFormatter;/*** Jackson ObjectMapper 工厂类*/public class ObjectMapperFactory {public static ObjectMapper getMapper() {ObjectMapper objectMapper new ObjectMapper();objectMapper.setDateFormat(new SimpleDateFormat(yyyy-MM-dd HH:mm:ss));SimpleModule module new SimpleModule();module.addSerializer(LocalDate.class, new LocalDateSerializer());module.addSerializer(LocalTime.class, new LocalTimeSerializer());module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());objectMapper.registerModule(module);return objectMapper;}static class LocalDateSerializer extends JsonSerializer {private static final DateTimeFormatter DATE_FORMATTER DateTimeFormatter.ofPattern(yyyy-MM-dd);/*** {inheritDoc}*/Overridepublic void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException {jgen.writeString(DATE_FORMATTER.format(value));}}static class LocalDateTimeSerializer extends JsonSerializer {private static final DateTimeFormatter DATE_TIME_FORMATTER DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss);/*** {inheritDoc}*/Overridepublic void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException {jgen.writeString(DATE_TIME_FORMATTER.format(value));}}static class LocalTimeSerializer extends JsonSerializer {private static final DateTimeFormatter TIME_FORMATTER DateTimeFormatter.ofPattern(HH:mm:ss);/*** {inheritDoc}*/Overridepublic void serialize(LocalTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException {jgen.writeString(TIME_FORMATTER.format(value));}}}还集成了 Swgger UI 方便接口调试import org.springframework.context.annotation.Bean;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;EnableSwagger2public class Swagger2Configuration {Bean(docket)public Docket createDocket() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(com.example.ssm.controller)).paths(PathSelectors.any()).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {Contact contact new Contact(calvinit, https://gitee.com/calvinit/ssm-demo, );return new ApiInfoBuilder().title(SSM框架搭建Demo).description(SSM框架搭建Demo仅供猿友们学习交流之用请勿用于商业用途).contact(contact).version(1.0-RELEASE).build();}}新建 src/main/resources/spring/spring-mvc.xml 文件xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxmlns:mvchttp://www.springframework.org/schema/mvcxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdapplication/json;charsetUTF-8同时整合了MapStruct方便 Entity、DTO 和 VO 等之间的转换使用示例import com.example.ssm.entity.User;import com.example.ssm.vo.UserVo;import org.mapstruct.InheritInverseConfiguration;import org.mapstruct.Mapper;import org.mapstruct.Mapping;import org.mapstruct.Mappings;import java.util.List;Mapperpublic interface UserVoConverter {Mappings({Mapping(source id, target userId),Mapping(source name, target userName),Mapping(target createDt, dateFormat yyyy-MM-dd HH:mm:ss),Mapping(target lastUpdateDt, dateFormat yyyy-MM-dd HH:mm:ss)})UserVo entityToVo(User user);List batchEntityToVo(List userList);InheritInverseConfigurationUser voToEntity(UserVo userVo);List batchVoToEntity(List userVoList);}新建 src/main/resources/spring/applicationContext-common.xml 文件配置 MapStruct 的 bean 被 Spring 管理xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd修改 web.xml 文件xmlnshttp://xmlns.jcp.org/xml/ns/javaeexsi:schemaLocationhttp://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsdidWebApp_ID version4.0ssmcontextConfigLocationclasspath:spring/applicationContext-*.xmllog4jConfigLocationclasspath:log4j2.xmlcharacterEncodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingUTF-8characterEncodingFilter/*druidWebStatFiltercom.alibaba.druid.support.http.WebStatFilterexclusions*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*profileEnabletruedruidWebStatFilter/*org.springframework.web.context.ContextLoaderListenerdispatcherServletorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclasspath:spring/spring-mvc.xml1dispatcherServlet/druidStatViewcom.alibaba.druid.support.http.StatViewServletallow127.0.0.1loginUsernameuserloginPasswordpasswordresetEnabletruedruidStatView/druid/*index.jsp修改 index.jsp 文件ssmHello World!打开 Swagger UI至此框架基本整合完毕下面写一个测试 Contoller 测试 Spring 和 Spring MVC 整合结果package com.example.ssm.controller;import com.google.common.collect.Maps;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import springfox.documentation.annotations.ApiIgnore;import java.util.Map;Api(tags 首页控制器)ControllerRequestMappingpublic class IndexController {ApiIgnoreApiOperation(value 首页)GetMappingpublic String index() {return index;}ApiOperation(value 返回纯字符串)GetMapping(/hello)ResponseBodypublic String hello() {return Hello World!;}ApiOperation(value 测试日期 json 返回)GetMapping(/date/test)ResponseBodypublic Map testDate() {Map map Maps.newHashMap();map.put(java.util.Date, new java.util.Date());map.put(java.sql.Date, new java.sql.Date(System.currentTimeMillis()));map.put(java.time.LocalDate, java.time.LocalDate.now());map.put(java.time.LocalTime, java.time.LocalTime.now());map.put(java.time.LocalDateTime, java.time.LocalDateTime.now());return map;}}右上角“Add Configuration”添加 Tomcat 配置将项目部署信息配置好然后我们启动 Tomcat打开 http://localhost:8080/ssm如果正常应该显示如下界面点击界面上的超链接进入 Swagger UI 的界面。再测试一下 Spring 和 Mybatis 整合是否完成package com.example.ssm.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.metadata.OrderItem;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.example.ssm.converter.UserVoConverter;import com.example.ssm.entity.User;import com.example.ssm.service.IUserService;import com.example.ssm.vo.PageVo;import com.example.ssm.vo.UserVo;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiParam;import org.springframework.web.bind.annotation.*;import java.util.List;ApiRestControllerRequestMapping(/users)public class UserController {private IUserService userService;private UserVoConverter userVoConverter;public UserController(IUserService userService, UserVoConverter userVoConverter) {this.userService userService;this.userVoConverter userVoConverter;}ApiOperation(value 分页查询用户列表)GetMapping(/page)ResponseBodypublic PageVo page(ApiParam(value 当前页, required true, defaultValue 1, example 1)RequestParam(pageNum) int pageNum,ApiParam(value 页面大小, required true, defaultValue 10, example 10)RequestParam(value pageSize, defaultValue 10) int pageSize) {Page page new Page();page.setSize(pageSize);page.setCurrent(pageNum);page.addOrder(OrderItem.asc(User.CREATE_DT), OrderItem.asc(User.LAST_UPDATE_DT));IPage userPage userService.selectPage(page);List userList userPage.getRecords();List userVoList userVoConverter.batchEntityToVo(userList);return PageVo.builder().pageNum(userPage.getCurrent()).pageSize(userPage.getSize()).pageTotal(userPage.getPages()).rowTotal(userPage.getTotal()).rowList(userVoList).build();}ApiOperation(value 查询某个用户)GetMapping(/{id})ResponseBodypublic User page(ApiParam(value 用户Id, required true, example 1)PathVariable(value id) int id) {return userService.selectByPrimaryKey(id);}ApiOperation(value 获取所有00后用户列表)GetMapping(/00/list)ResponseBodypublic List list00() {LambdaQueryWrapper userLambdaQueryWrapper Wrappers.lambdaQuery();userLambdaQueryWrapper.ge(User::getBirthday, 2000-01-01);return userService.list(userLambdaQueryWrapper);}}在 Swagger UI 的界面里面测试接口返回正确另外Druid 的监控信息页面链接为http://localhost:8080/ssm/druid/index.html访问白名单、账号和密码在 web.xml 文件中配置。至此SSM 框架集成完毕测试通过因篇幅关系一些代码并没有在此文章中展现可到我的Gitee上看完整框架代码。