记录一下最近整理的spring boot项目
项目地址:https://gitee.com/xl0917/spring-boot
1.选择Spring Initializr 一直点击next,直到创建完成
2.创建spring boot子模块,创建无任何模板的maven项目
3.项目结构
- commone——公共类及工具类存放处,可在该项目中引入其他工具jar包
- entity——实体类层
- dao——数据持久层
- api——service接口,配置double及注册中心可供rpc消费端调用
- service——业务逻辑
- webapp——web项目url请求入口
4.pom.xml文件
- 父类pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <modules> <module>backstage-common</module> <module>backstage-dao</module> <module>backstage-entiy</module> <module>backstage-api</module> <module>backstage-service</module> <module>backstage-webapp</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.xulong</groupId> <artifactId>com.xulong.backstage</artifactId> <version>0.0.1-SNAPSHOT</version> <name>backstage</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> </project>
- common层pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>com.xulong.backstage</artifactId> <groupId>com.xulong</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>backstage-common</artifactId> </project>
- entity层pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>com.xulong.backstage</artifactId> <groupId>com.xulong</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>backstage-entiy</artifactId> <dependencies> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </build> </project>
- dao层pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>com.xulong.backstage</artifactId> <groupId>com.xulong</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>backstage-dao</artifactId> <dependencies> <dependency> <groupId>com.xulong</groupId> <artifactId>backstage-entiy</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-typehandlers-jsr310</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </build> </project>
- api层pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>com.xulong.backstage</artifactId> <groupId>com.xulong</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>backstage-api</artifactId> <dependencies> <dependency> <groupId>com.xulong</groupId> <artifactId>backstage-entiy</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.xulong</groupId> <artifactId>backstage-common</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
- service层pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>com.xulong.backstage</artifactId> <groupId>com.xulong</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>backstage-service</artifactId> <dependencies> <dependency> <groupId>com.xulong</groupId> <artifactId>backstage-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.xulong</groupId> <artifactId>backstage-dao</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> </dependencies> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </build> </project>
- webapp层pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>com.xulong.backstage</artifactId> <groupId>com.xulong</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.xulong</groupId> <artifactId>backstage-webapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.xulong</groupId> <artifactId>backstage-service</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!--<exclusions>--> <!--<exclusion>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-tomcat</artifactId>--> <!--</exclusion>--> <!--</exclusions>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> </exclusion> </exclusions> <scope>test</scope> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <version>1.5.6.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!--<dependency>--> <!--<groupId>org.apache.tomcat</groupId>--> <!--<artifactId>tomcat-juli</artifactId>--> <!--<version>${tomcat.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.tomcat.embed</groupId>--> <!--<artifactId>tomcat-embed-jasper</artifactId>--> <!--</dependency>--> </dependencies> <build> <finalName>backstage-webapp</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.xulong.backstage.BackstageApplication</mainClass> <executable>true</executable> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> <version>2.5</version> </plugin> </plugins> </pluginManagement> </build> </project>
5.配置文件application.properties
#数据库链接配置 spring.datasource.url=jdbc:mysql://**.**.***.***:3306/backstage?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password= server.port=8080 mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper*.xml mybatis.configuration.log-prefix=com.xulong.backstage.dao #静态资源 #表示所有的访问都经过静态资源路径 spring.mvc.static-path-pattern=/static/** #在这里表示配置静态资源根路径 spring.resources.static-locations=classpath:/static/ #mvc跳转路径 Thymeleaf.prefix=classpath:/templates/ #热部署生效 spring.devtools.restart.enabled=true #静态文件热部署 spring.thymeleaf.cache=false #显示sql语句 logging.level.com.xulong.backstage.dao.mapper=debug #pagehelper分页插件配置 pagehelper.helper-dialect=mysql pagehelper.offset-as-page-num=true pagehelper.row-bounds-with-count=true pagehelper.page-size-zero=false pagehelper.reasonable=false pagehelper.support-methods-arguments=true pagehelper.params=pageNum=page;pageSize=size;count=countSql;
6.mybatis.generator插件配置
- generatorConfig.xml配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <properties resource="META-INF/mybatis/generator.properties"/> <!-- 指定数据连接驱动jar地址 --> <classPathEntry location="D:softwaremvn_repomysqlmysql-connector-java5.1.44mysql-connector-java-5.1.44.jar" /> <context id="MySQLTables" targetRuntime="MyBatis3"> <property name="javaFileEncoding" value="UTF-8"/> <property name="addGWTInterface" value="false"/> <property name="suppressJavaInterface" value="false"/> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <!--<plugin type="org.META-INF.mybatis.mapper.generator.plugins.GuavaStyleToStringPlugin"/>--> <!-- 去掉生成出来的代码的注解 --> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <!-- 数据库连接url、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetProject="../${module.domain}/src/main/java" targetPackage="${package.domain}"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> <property name="constructorBased" value="false"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置 --> <sqlMapGenerator targetProject="../${module.dao}/src/main/resources" targetPackage="mybatis/mapper"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator targetProject="../${module.dao}/src/main/java" targetPackage="${package.mapper}" type="XMLMAPPER"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <table tableName="role_info" domainObjectName="RoleInfo" enableSelectByExample="false" enableCountByExample="false" enableDeleteByExample="false" enableUpdateByExample="false"> <property name="useActualColumnNames" value="false"/> <property name="selectAllOrderByClause" value="role_code DESC"/> <!--<generatedKey column="stock_code" sqlStatement="MySql" identity="true"/>--> </table> </context> </generatorConfiguration>
- 引入文件generator.properties配置
jdbc.driverClass = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://**.**.***.***:3306/backstage?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false jdbc.username = root jdbc.password = module.domain = backstage-entiy module.dao = backstage-dao package.mapper = com.xulong.backstage.dao.mapper package.domain = com.xulong.backstage.entity driverPath = D: epository4mysqlmysql-connector-java5.1.44mysql-connector-java-5.1.44.jar jdk.use_jdk8_time = true
7.shiro框架配置
- java类方式配置
package com.xulong.backstage; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import java.util.LinkedHashMap; /** * @author xulong * shiro 安全框架配置 */ @Configuration public class ShiroConfiguration { //==============Shiro================ /** * 配置SecurityManager对象(Shiro核心) * @param userUserRealm * @return */ @Bean("securityManager") public DefaultWebSecurityManager newDefaultWebSecurityManager(ShiroUserRealm userUserRealm){ DefaultWebSecurityManager sManager = new DefaultWebSecurityManager(); sManager.setRealm(userUserRealm); return sManager; } @Bean("shiroFilter") public ShiroFilterFactoryBean newShiroFilterFactory( @Autowired SecurityManager securityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager); //未登录跳转的url bean.setLoginUrl("/login.html"); LinkedHashMap<String,String> fcMap = new LinkedHashMap<>(); fcMap.put("/login.html", "anon"); fcMap.put("/validateLogin.html","anon"); fcMap.put("/test","anon"); //退出url fcMap.put("/logout.html", "logout"); //放开静态文件权限 fcMap.put("/static/**","anon"); fcMap.put("/**", "authc"); //必须授权才能访问 authc bean.setFilterChainDefinitionMap(fcMap); //登录成功跳转的url bean.setSuccessUrl("/index.html"); return bean; } /** * 配置shiro生命周期管理器 * @return */ @Bean("lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor newLifecycleBeanPostProcessor(){ return new LifecycleBeanPostProcessor(); } /** * 配置shiro注解应用 * */ @DependsOn(value="lifecycleBeanPostProcessor") @Bean public DefaultAdvisorAutoProxyCreator newDefaultAdvisorAutoProxyCreator(){ return new DefaultAdvisorAutoProxyCreator(); } @Bean public AuthorizationAttributeSourceAdvisor newAuthorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor bean= new AuthorizationAttributeSourceAdvisor(); bean.setSecurityManager(securityManager); return bean; } }
- 登录验证类
package com.xulong.backstage; import com.xulong.backstage.common.constants.DictCodeConstants; import com.xulong.backstage.dao.mapper.UserMapper; import com.xulong.backstage.entity.User; import org.apache.shiro.authc.*; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author xulong * shiro 验证登录等类 */ @Service public class ShiroUserRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //1.获取客户端提交的用户信息 UsernamePasswordToken upToken = (UsernamePasswordToken)token; String username = upToken.getUsername(); upToken.getPassword(); User user = userMapper.findUserByUserCode(username); if(user == null){ throw new AuthenticationException("用户名或密码不正确!"); } if(DictCodeConstants.DICT_100002_1.equals(user.getUserStatus())){ throw new AuthenticationException("账户已被冻结,请联系管理员!"); } if(DictCodeConstants.DICT_100002_2.equals(user.getUserStatus())){ throw new AuthenticationException("账户已被禁用,请联系管理员!"); } SimpleAuthenticationInfo simple = new SimpleAuthenticationInfo( user, //传入对象后,后续可以在shiro中获取登录用户的对象信息 user.getPassword(), getName()); return simple;//返回给认证管理器 } /** * 此方法用于获取用户权限信息----执行权限操作 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) { return null; } /** * 设置凭证匹配器 */ @Override public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//密码验证是否成功方法,比如密码错误有其它操作或者有自己的校验要求 CustomCredentialsMatcher cMatcher = new CustomCredentialsMatcher(); super.setCredentialsMatcher(cMatcher); } } - 密码验证类
package com.xulong.backstage; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; import java.util.Objects; public class CustomCredentialsMatcher extends SimpleCredentialsMatcher { @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { UsernamePasswordToken utoken=(UsernamePasswordToken) token; String dbPassword = (String) info.getCredentials(); String inPassword = new String(utoken.getPassword()); boolean fals = Objects.equals(dbPassword, inPassword); if(fals == false){ //更改当前用户登录错误次数,当错误次数大于3冻结当前用户 throw new AuthenticationException("用户名或密码不正确!"); } return fals; } }
8.thymeleaf部分使用
- 例如:当数据库存储时间格式为20190401092416,在网页中想显示为2091-04-01 09:24:16,但是thtmeleaf未提供方法转换,需要我们写一个转换类
- DateUtil类写一个格式转换方法
package com.xulong.backstage.common.util; import java.text.SimpleDateFormat; import java.util.Date; /** * @author xulong * @date 2019/03/26 */ public class DateUtil { /** 模式 :yyyyMMddHHmmss */ public static final String YYYYMMDD_HHMMSS = "yyyyMMddHHmmss"; /** 模式 :yyyyMMdd */ public static final String YYYYMMDD = "yyyyMMdd"; /** 模式 :yyyyMM */ public static final String YYYYMM = "yyyyMM"; /** 模式 :HHmmss */ public static final String HHMMSS = "HHmmss"; /** 模式 :HHmm */ public static final String HHMM = "HHmm"; public static final String FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_DAY = "yyyy-MM-dd"; /** * 获取当前日期的数字格式 * 如20190326 * @return */ public static Long getNowDate(){ Date date = new Date(); return Long.valueOf(date2String(date,YYYYMMDD)); } /** * 获取当前时间的数字格式 * 如20190326141225 * @return */ public static Long getNowDateTime(){ Date date = new Date(); return Long.valueOf(date2String(date,YYYYMMDD_HHMMSS)); } /** * longFormat:(long类型的日期转化为格式化日期字符串,如20160717122121转化为2016-07-17 12:21:21) * @param srcLong long类型的日期如20160717122121 * @param pattern 格式化日期字符串如2016-07-17 12:21:21 * @return */ public static String longFormat(Long srcLong,String pattern){ if (srcLong == null) { return ""; } if (srcLong == 0) { return "0"; } Date date = string2Date(String.valueOf(srcLong)); return date2String(date,pattern); } /** * intFormat:(long类型的日期转化为格式化日期字符串,如20160717转化为2016-07-17) * * @param src Integer 类型的日期如20160717122121 * @param pattern 格式化日期字符串如2016-07-17 12:21:21 * @return * @throws * @since DateUtils.java Ver 1.0 */ public static String intFormat(Integer src, String pattern) { if (src == null) { return ""; } if (src == 0) { return "0"; } Date date = string2Date(String.valueOf(src)); return date2String(date, pattern); } /** * 方法说明:日期类型按照指定格式转成字符串. * * @param date * @param pattern * @return */ public static String date2String(Date date, String pattern) { if (null == date) { date = new Date(); } if (pattern.length() == 0 || pattern == null) { pattern = FORMAT_YMDHMS; } try { return getDateFormat(pattern).format(date); } catch (Exception e) { throw new RuntimeException("日期转换异常"); } } /** * 方法说明:字符串转日期类型. * * @param date * @return */ public static Date string2Date(String date) { try { if (date.length() == 8) { return getDateFormat(YYYYMMDD).parse(date); } else if (date.length() == 14) { return getDateFormat(YYYYMMDD_HHMMSS).parse(date); } else if (date.length() == 6) { return getDateFormat(HHMMSS).parse(date); } else { return null; } } catch (Exception e) { throw new RuntimeException("日期转换异常"); } } /** * 获取指定日期指定格式的日期字符串 * @return */ private static String getDate(String pattern,Date date){ SimpleDateFormat format = getDateFormat(pattern); return format.format(date); } /** * 获取指定模式pattern的SimpleDateFormat对象 * @param str * @return */ private static SimpleDateFormat getDateFormat(String str){ return new SimpleDateFormat(str); } }
- 在控制层封装DateUtil对象
@RequestMapping("/index.html") public String index(Model model){ model.addAttribute("dateUtil",new DateUtil()); Long date = 20160824121425L; model.addAttribute("date",date); return "index"; }
- html页面中书写方式
<div class="row" style="text-align:center;font-size: 60px;color: #00aced;margin-top:10%"> 欢迎来到后台管理页面<br> <span th:text="${dateUtil.longFormat(da,'YYYY-MM-dd HH:mm:ss')}"></span> </div>
- 页面显示的内容