Commit a51fbed5 by zhoujinghao

加入jwt相关代码

1 parent 783a34bc
...@@ -9,8 +9,8 @@ eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka ...@@ -9,8 +9,8 @@ eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.instance.statusPageUrl = http://127.0.0.1:8001/swagger-ui.html eureka.instance.statusPageUrl = http://127.0.0.1:8001/swagger-ui.html
eureka.instance.prefer-ip-address = true eureka.instance.prefer-ip-address = true
eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port} eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port}
spring.datasource.url=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.url=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=123456 spring.datasource.password=Moxi123#
spring.datasource.username=root spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml mybatis.mapper-locations=classpath:mapper/*.xml
\ No newline at end of file \ No newline at end of file
...@@ -89,13 +89,18 @@ ...@@ -89,13 +89,18 @@
<dependency> <dependency>
<groupId>io.jsonwebtoken</groupId> <groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId> <artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency> </dependency>
<!--JWT(Json Web Token)登录支持-->
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt -->
<dependency> <dependency>
<groupId>org.springframework.security</groupId> <groupId>com.auth0</groupId>
<artifactId>spring-security-jwt</artifactId> <artifactId>java-jwt</artifactId>
<version>1.0.10.RELEASE</version> <version>3.2.0</version>
<exclusions>
<exclusion>
<artifactId>bcprov-jdk15on</artifactId>
<groupId>org.bouncycastle</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.security.oauth.boot</groupId> <groupId>org.springframework.security.oauth.boot</groupId>
......
package org.nafmii.auth;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Header;
import com.auth0.jwt.interfaces.Payload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.nafmii.entity.AppUser;
import org.nafmii.exception.JwtException;
import org.nafmii.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtils {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String SUBJECT = "congge";
public static final long EXPIRITION = 1000 * 24 * 60 * 60 * 7;
public static final String APPSECRET_KEY = "congge_secret";
private static final String ROLE_CLAIMS = "rol";
public static String generateJsonWebToken(AppUser user) {
if (user.getId() == null || user.getUserName() == null ) {
return null;
}
Map<String,Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, "rol");
String token = Jwts
.builder()
.setSubject(SUBJECT)
.setClaims(map)
.claim("id", user.getId())
.claim("name", user.getUserName())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
.signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
return token;
}
/**
     * 生成token
     * @param username
     * @param role
     * @return
     */
public static String createToken(String username,String role) {
Map<String,Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, role);
String token = Jwts
.builder()
.setSubject(username)
.setClaims(map)
.claim("username",username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
.signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
return token;
}
public static Claims checkJWT(String token) {
try {
final Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
     * 获取用户名
     * @param token
     * @return
     */
public static String getUsername(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.get("username").toString();
}
/**
     * 获取用户角色
     * @param token
     * @return
     */
public static String getUserRole(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.get("rol").toString();
}
/**
   * 是否过期
   * @param token
   * @return
   */
public static boolean isExpiration(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.getExpiration().before(new Date());
}
public static void main(String[] args) {
String name = "acong";
String role = "rol";
String token = createToken(name,role);
System.out.println(token);
Claims claims = checkJWT(token);
System.out.println(claims.get("username"));
System.out.println(getUsername(token));
System.out.println(getUserRole(token));
System.out.println(isExpiration(token));
}
/**
     * eyJhbGciOiJIUzI1NiJ9.
     * eyJzdWIiOiJjb25nZ2UiLCJpZCI6IjExMDExIiwibmFtZSI6Im51b3dlaXNpa2kiLCJpbWciOiJ3d3cudW9rby5jb20vMS5wbmciLCJpYXQiOjE1NTQ5OTI1NzksImV4cCI6MTU1NTU5NzM3OX0.
     * 6DJ9En-UBcTiMRldZeevJq3e1NxJgOWryUyim4_-tEE
     * 
     * @param args
     */
/*public static void main(String[] args) {
        Users user = new Users();
        user.setId("11011");
        user.setUserName("nuoweisiki");
        user.setFaceImage("www.uoko.com/1.png");
        String token = generateJsonWebToken(user);
        System.out.println(token);
        Claims claims = checkJWT(token);
        if (claims != null) {
            String id = claims.get("id").toString();
            String name = claims.get("name").toString();
            String img = claims.get("img").toString();
            
            String rol = claims.get("rol").toString();
            System.out.println("id:" + id);
            System.out.println("name:" + name);
            System.out.println("img:" + img);
            
            System.out.println("rol:" + rol);
            
            
            
        }
    }*/
}
package org.nafmii.controller;
import org.nafmii.result.Result;
import org.nafmii.service.UserService;
import org.nafmii.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:10
* @ClassName:
* @version:
* @remark:
*/
@RestController
@RequestMapping("/auth")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
@ResponseBody
public Result<UserVO> login (){
Result<UserVO> login = userService.login();
return login;
}
}
package org.nafmii.entity;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class AppUser implements Serializable {
private Long id;
@ApiModelProperty(value = "昵称")
private String userName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
private String phone;
@ApiModelProperty(value = "出生日期")
private String birthday;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "头像图片地址")
private String headPicture;
@ApiModelProperty(value = "国籍")
private String nationality;
@ApiModelProperty(value = "单位全称")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
private String isEnable;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHeadPicture() {
return headPicture;
}
public void setHeadPicture(String headPicture) {
this.headPicture = headPicture;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getFigerprintFalg() {
return figerprintFalg;
}
public void setFigerprintFalg(String figerprintFalg) {
this.figerprintFalg = figerprintFalg;
}
public String getFaceidFalg() {
return faceidFalg;
}
public void setFaceidFalg(String faceidFalg) {
this.faceidFalg = faceidFalg;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getIsEnable() {
return isEnable;
}
public void setIsEnable(String isEnable) {
this.isEnable = isEnable;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userName=").append(userName);
sb.append(", loginPwd=").append(loginPwd);
sb.append(", realName=").append(realName);
sb.append(", phone=").append(phone);
sb.append(", birthday=").append(birthday);
sb.append(", email=").append(email);
sb.append(", headPicture=").append(headPicture);
sb.append(", nationality=").append(nationality);
sb.append(", unitName=").append(unitName);
sb.append(", openId=").append(openId);
sb.append(", figerprintFalg=").append(figerprintFalg);
sb.append(", faceidFalg=").append(faceidFalg);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", isEnable=").append(isEnable);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.entity;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class CenterRole implements Serializable {
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "角色名称")
private String rName;
@ApiModelProperty(value = "创建时间")
private Date creatTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1禁用")
private String isEnable;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public Date getCreatTime() {
return creatTime;
}
public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getIsEnable() {
return isEnable;
}
public void setIsEnable(String isEnable) {
this.isEnable = isEnable;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", rName=").append(rName);
sb.append(", creatTime=").append(creatTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", isEnable=").append(isEnable);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.service;
import org.nafmii.result.Result;
import org.nafmii.vo.UserVO;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:20
* @ClassName:
* @version:
* @remark:
*/
public interface UserService {
Result<UserVO> login();
}
package org.nafmii.service.impl;
import org.nafmii.auth.JwtUtils;
import org.nafmii.result.Result;
import org.nafmii.service.UserService;
import org.nafmii.vo.UserAndRoleVo;
import org.nafmii.vo.UserVO;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:20
* @ClassName:
* @version:
* @remark:
*/
@Service
public class UserServiceImpl implements UserService {
@Override
public Result<UserVO> login() {
Result result = new Result();
//假设验证数据通过
UserVO userVO = new UserVO();
userVO.setPassword("zzz");
userVO.setUserName("zzz");
List<UserAndRoleVo> roleList =new ArrayList<>();
UserAndRoleVo roleVo = new UserAndRoleVo();
roleVo.setRole("a");
roleVo.setRole("b");
roleList.add(roleVo);
userVO.setAuthorities(roleList);
StringBuilder sbf = new StringBuilder();
for (UserAndRoleVo role:roleList
) {
sbf=sbf.append(role.getRole()+",");
}
//处理字符串
String sRole = sbf.toString();
String substring = sRole.substring(0, sRole.lastIndexOf(","));
String token = JwtUtils.createToken(userVO.getUserName(),substring);
userVO.setToken(token);
result.setData(userVO);
return result;
}
}
package org.nafmii.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.entity.CenterRole;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 9:06
* @ClassName:
* @version:
* @remark:
*/
@Data
public class UserAndRoleVo {
private Long id;
private String userName;
private String password;
@ApiModelProperty("角色名称")
private String Role;
}
package org.nafmii.vo;
import lombok.Data;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:22
* @ClassName:
* @version:
* @remark:
*/
@Data
public class UserVO {
private String userName;
private String password;
private String token;//角色集合
private List<UserAndRoleVo> authorities;
}
...@@ -9,8 +9,8 @@ eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka ...@@ -9,8 +9,8 @@ eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.instance.statusPageUrl = http://127.0.0.1:8002/swagger-ui.html eureka.instance.statusPageUrl = http://127.0.0.1:8002/swagger-ui.html
eureka.instance.prefer-ip-address = true eureka.instance.prefer-ip-address = true
eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port} eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port}
spring.datasource.url=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.url=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=123456 spring.datasource.password=Moxi123#
spring.datasource.username=root spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml mybatis.mapper-locations=classpath:mapper/*.xml
\ No newline at end of file \ No newline at end of file
package org.nafmii.exception;
public class JwtException extends RuntimeException {
public JwtException() {
super();
}
public JwtException(String message) {
super(message);
}
public JwtException(String message, Throwable cause) {
super(message, cause);
}
public JwtException(Throwable cause) {
super(cause);
}
protected JwtException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
...@@ -12,7 +12,7 @@ public class Result<T> { ...@@ -12,7 +12,7 @@ public class Result<T> {
private Long code; private Long code;
private String message; private String message;
private T data; private T data;
public Result(){};
public Result(Long code, String message, T data) { public Result(Long code, String message, T data) {
this.code = code; this.code = code;
this.message = message; this.message = message;
......
package org.nafmii.utils;
import org.nafmii.exception.JwtException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* Created by zhangzhenfang on 2018/5/16.
*/
public class DateUtils {
public static String DATE_PATTERN ="yyyy-MM-dd HH:mm:ss";
public static String SHORT_DATE_PATTERN ="yyyy-MM-dd";
public static String format(Date date){
DateFormat df=new SimpleDateFormat(DATE_PATTERN);
return df.format(date);
}
public static String formatShortDate(Date date){
DateFormat df=new SimpleDateFormat(SHORT_DATE_PATTERN);
return df.format(date);
}
/**
* 返回yyyy-MM-dd格式字符串时间
* @Author Lifp
* @Date 12:48 2020.9.16
* @Param [date]
* @return java.lang.String
**/
public static String formatShortDateStr(String date){
if (date.contains(" ") || date.contains(":")) {
date = date.substring(0, date.lastIndexOf("-") + 3);
}
return date;
}
public static String formatDate(Date date){
DateFormat df=new SimpleDateFormat(DATE_PATTERN);
return df.format(date);
}
public static Date nowDate() {
return new Date();
}
public static Date getDayBegin(Date date){
if(date==null){
return null;
}
Date todayBegin = org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DATE);
return todayBegin;
}
/**
* 指定日期的结束时间即第二天开始时间(条件查询应 date >= dayStart && date<dayEnd)
* @param date
* @return
*/
public static Date getDayEnd(Date date){
if(date==null){
return null;
}
Date todayBegin = org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DATE);
return org.apache.commons.lang3.time.DateUtils.addDays(todayBegin,1);
}
public static String toDateString(Date date, String formatStr) {
DateFormat df = getDateFormat(formatStr);
return df.format(date);
}
/**
* 获取DateFormat
*
* @param formatStr
* @return
*/
public static DateFormat getDateFormat(String formatStr) {
DateFormat df = dateFormatMap.get(formatStr);
if (df == null) {
df = new SimpleDateFormat(formatStr);
dateFormatMap.put(formatStr, df);
}
return df;
}
/**
* DateFormat缓存
*/
private static Map<String, DateFormat> dateFormatMap = new HashMap<>();
/**
* 将时间字符串转为LocalDateTime 格式
*/
public static LocalDateTime strToLocalDate(String timeStr) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
return LocalDateTime.parse(timeStr, fmt);
}
public static Date parseDate(String dateStr){
if(dateStr== null){
return null;
}
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, DATE_PATTERN);
} catch (ParseException e) {
throw new JwtException("date format error",e);
}
}
public static Date parseShortDate(String dateStr){
if(dateStr== null){
return null;
}
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, SHORT_DATE_PATTERN);
} catch (ParseException e) {
throw new JwtException("date format error",e);
}
}
public static Date parseDate(String dateStr,String... datePattern){
if(dateStr== null){
return null;
}
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, datePattern);
} catch (ParseException e) {
throw new JwtException("date format error",e);
}
}
// 判断两个日期是否为同一天
public static boolean isSameDay(Date date1, Date date2) {
if(date1 != null && date2 != null) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return isSameDay(cal1, cal2);
} else {
throw new IllegalArgumentException("The date must not be null");
}
}
// 判断两个日期是否为同一天
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if(cal1 != null && cal2 != null) {
return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
} else {
throw new IllegalArgumentException("The date must not be null");
}
}
// 判断给定的两个日期相差天数
public static int differentDays(Date date1,Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int day1= cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if(year1 != year2) { //不同年
int timeDistance = 0 ;
for(int i = year1 ; i < year2 ; i ++)
{
if(i%4==0 && i%100!=0 || i%400==0) { //闰年
timeDistance += 366;
}
else //不是闰年
{
timeDistance += 365;
}
}
return timeDistance + (day2-day1) ;
}
else //同年
{
System.out.println("判断day2 - day1 : " + (day2-day1));
return day2-day1;
}
}
// 判断给定的日期是否为一个月的第一天
public static boolean isFirstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar.get(Calendar.MONTH)+1);
return calendar.get(Calendar.DAY_OF_MONTH) == 1;
}
// 获取昨天的日期
public static Date getYesterdayStr(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, -24);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
// return getDayBegin(time);
return time;
}
// 获取时间段内的所有日期
public static List<Date> getRangeDate(Date start, Date end) {
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(start);
min.set(Calendar.HOUR_OF_DAY, 0);
min.set(Calendar.MINUTE, 0);
min.set(Calendar.SECOND, 0);
min.set(Calendar.MILLISECOND, 0);
max.setTime(end);
max.set(Calendar.HOUR_OF_DAY, -24);
max.set(Calendar.MINUTE, 0);
max.set(Calendar.SECOND, 0);
max.set(Calendar.MILLISECOND, 0);
List<Date> dateArrayList = new ArrayList<>();
Calendar current = min;
while (current.before(max) || current.equals(max)) {
dateArrayList.add(current.getTime());
current.add(Calendar.DAY_OF_MONTH, 1);
}
return dateArrayList;
}
/**
* zjh
* 返回日时分秒(重构)
* @param
* @return
*/
public static String secondToTime(Date endIsTopTime) {
long second =endIsTopTime.getTime()-System.currentTimeMillis();
if (second < 0) {
return "00:00:00";
}
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long hour = second % nd / nh; //获取相差的小时数
long min = second % nd % nh / nm; //获取相差的分钟数
long day = second / nd;
long secondResult = (second % (1000 * 60)) / 1000;
if (0 < day){
return day + "天 "+hour+":"+min+":"+secondResult;
}else {
return hour+":"+min+":"+secondResult;
}
}
/**
* 获取30天之前的日期 yyyy-mm-hh 格式
* @return
*/
public static String recentMonthDateStr() {
Date startDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), -30);
return DateUtils.formatShortDate(startDate);
}
/**
* 获取指定时间后一天的日期 yyyy-mm-hh 格式
* @return
*/
public static String getAfterDayStr(Date date) {
Date startDate = DateUtils.getDayEnd(date);
return DateUtils.formatShortDate(startDate);
}
/**
* 获取指定时间段的日期
* @return
*/
public static Date getSpecifyTime(String hour, String minute) {
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
time.set(Calendar.MINUTE, Integer.parseInt(minute));
time.set(Calendar.SECOND, 0);
// time.set(Calendar.MILLISECOND, 999);
return time.getTime();
}
public static List<String> getBetweenDate(String begin,String end){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<String> betweenList = new ArrayList<String>();
try{
Calendar startDay = Calendar.getInstance();
startDay.setTime(format.parse(begin));
startDay.add(Calendar.DATE, -1);
while(true){
startDay.add(Calendar.DATE, 1);
Date newDate = startDay.getTime();
String newend=format.format(newDate);
betweenList.add(newend);
if(end.equals(newend)){
break;
}
}
}catch (Exception e) {
e.printStackTrace();
}
return betweenList;
}
/**
* 根据当前日期获得所在周的日期区间(周一和周日日期)
* @Author Lifp
* @Date 14:54 2020.9.17
* @Param [date, whichDay(0-周一; 1-周日)]
* @return java.lang.String
**/
public static String getTimeInterval(Date date, Integer whichDay) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 返回结果
String timeRsp;
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
int cDate = Calendar.DATE;
// 获取周1日期
if (whichDay == 0) {
int firstDayOfWeek = cal.getFirstDayOfWeek();
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(cDate, cal.getFirstDayOfWeek() - day);
timeRsp = formatShortDate(cal.getTime());
} else if (whichDay == 1) {
// 获取周日日期
cal.add(cDate, 8-day);
timeRsp = formatShortDate(cal.getTime());
} else {
return "";
}
return timeRsp;
}
/**
* 获取19xx,20xx形式的年
*
* @param d
* @return
*/
public static int getYear(Date d) {
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.YEAR);
}
/**
* 获取某年到现在的所有年份
* @Author Lifp
* @Date 16:43 2020.9.17
* @Param [startYear]
* @return java.util.List<java.lang.String>
**/
public static List<String> getYears(int startYear) {
List<String> years = new ArrayList<>();
int endYear = getYear(new Date());
int local = endYear - startYear;
while (local > -1) {
years.add(String.valueOf(startYear++));
local--;
}
return years;
}
/**
* 返回手机号码
*/
public static int getNum(int start,int end) {
return (int)(Math.random()*(end-start+1)+start);
}
private static String[] telFirst="134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153".split(",");
private static String getTel() {
int index=getNum(0,telFirst.length-1);
String first=telFirst[index];
String second=String.valueOf(getNum(1,888)+10000).substring(1);
String third=String.valueOf(getNum(1,9100)+10000).substring(1);
return first+second+third;
}
public static void main(String[] args){
Date date = parseShortDate("2020-09-20");
System.out.println(getTimeInterval(date, 0));
System.out.println(getTimeInterval(date, 1));
System.out.println(getYear(new Date()));
}
}
package org.nafmii.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* Created by zhangzhenfang on 2018/6/5.
*/
public class JsonUtils {
private static final SerializeConfig config;
static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
};
public static String toJsonString(Object object) {
return JSON.toJSONString(object, config, features);
}
// public static String toJSONNoFeatures(Object object) {
// return JSON.toJSONString(object, config);
// }
public static Object parse(String text) {
return JSON.parse(text);
}
public static <T> T parse(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
}
...@@ -39,6 +39,15 @@ ...@@ -39,6 +39,15 @@
<groupId>org.mybatis</groupId> <groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId> <artifactId>mybatis</artifactId>
</dependency> </dependency>
<!--接口文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC jdbc.connectionURL=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.userId=root jdbc.userId=root
jdbc.password=123456
\ No newline at end of file \ No newline at end of file
jdbc.password=Moxi123#
\ No newline at end of file \ No newline at end of file
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
<javaClientGenerator type="XMLMAPPER" targetPackage="org.nafmii.nafmiimbg.mapper" <javaClientGenerator type="XMLMAPPER" targetPackage="org.nafmii.nafmiimbg.mapper"
targetProject="nafmii-mbg\src\main\java"/> targetProject="nafmii-mbg\src\main\java"/>
<!--生成全部表tableName设为%--> <!--生成全部表tableName设为%-->
<table tableName="%"> <table tableName="CENTER_ROLE">
<!--<generatedKey column="id" sqlStatement="MySql" identity="true"/>--> <!--<generatedKey column="id" sqlStatement="MySql" identity="true"/>-->
</table> </table>
</context> </context>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!