login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登入 - 後臺</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="../layuiadmin/layui/css/layui.css" media="all">
<link rel="stylesheet" href="../layuiadmin/style/admin.css" media="all">
<link rel="stylesheet" href="../layuiadmin/style/login.css" media="all">
<link rel="shortcut icon" href="favicon.ico">
<style>
body {
margin: 10px;
}
#canvas {
float: right;
display: inline-block;
border: 1px solid #ccc;
border-radius: 5px;
cursor: pointer;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
</head>
<body >
<div class="layadmin-user-login layadmin-user-display-show layui-form" id="LAY-user-login" style="display: none;" lay-filter="layuiadmin-form">
<div class="layadmin-user-login-main">
<div class="layadmin-user-login-box <div class="layadmin-user-login-box layadmin-user-login-header">
<h2>SD</h2>
<p>後臺</p>
</div>
<div class="layadmin-user-login-box layadmin-user-login-body layui-form">
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-username" for="account"></label>
<input type="text" name="account" id="account" lay-verify="required" placeholder="用戶名" class="layui-input">
</div>
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-password"
for="password"></label>
<input type="password" name="password" id="password" lay-verify="required"
placeholder="密碼" class="layui-input">
</div>
<!--<div class="layui-form-item">
<div class="layui-row">
<div class="layui-col-xs7">
<label class="layadmin-user-login-icon layui-icon layui-icon-vercode"
for="LAY-user-login-vercode"></label>
<input type="text" name="vercode" id="LAY-user-login-vercode" lay-verify="required" placeholder="圖形驗證碼" class="layui-input">
</div>
<div class="layui-col-xs5">
<canvas id="canvas" width="100" height="43"></canvas>
<!–<div style="margin-left: 10px;">
<img src="../layuiadmin/images/login/captcha.gif" class="layadmin-user-login-codeimg" id="LAY-user-get-vercode">
</div>–>
</div>
</div>
</div>-->
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit lay-filter="formsubmit">立即提交</button>
</div>
</div>
</div>
</div>
<script src="../layuiadmin/layui/layui.js"></script>
<script>
layui.config({
base: '../layuiadmin/' //靜態資源所在路徑
}).extend({
index: 'lib/index' //主入口模塊
}).use(['index', 'login'], function () {
layui.login.init();
});
</script>
</body>
</html>
/**
@Name:登錄
@Author:阿平
@Site:
@License:LPPL
*/
var $;
layui.define(['table', 'form', 'sd', 'layedit', 'upload'], function (exports) {
var table = layui.table
, sd = layui.sd
, form = layui.form
, layedit = layui.layedit
, upload = layui.upload;
$ = layui.$;
var api = {
login: 'back/account/login',
};
form.on('submit(formsubmit)', function(data){
// layer.msg(JSON.stringify(data.field));
var data =data.field;
sd.ajax.request(api.login, {account:data.account,password:data.password}, function (res) {
if (res.code=='0') {
window.location.href="../views/index.html";
} else {
sd.msg.error(res.msg);
}
});
});
//供外部調用,定義在call下
var call = {};
//列表頁初始化
call.init = function () {
};
//對外暴露
exports('login', call);
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>平臺</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="../layuiadmin/layui/css/layui.css" media="all">
<link rel="stylesheet" href="../layuiadmin/style/admin.css" media="all">
<link rel="shortcut icon" href="favicon.ico">
<script>
/^http(s*):\/\//.test(location.href) || alert('請先部署到 localhost 下再訪問');
</script>
</head>
<body class="layui-layout-body">
<div id="LAY_app">
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<!-- 頭部區域 -->
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item layadmin-flexible" lay-unselect>
<a href="javascript:;" layadmin-event="flexible" title="側邊伸縮">
<i class="layui-icon layui-icon-shrink-right" id="LAY_app_flexible"></i>
</a>
</li>
<li class="layui-nav-item layui-hide-xs" lay-unselect>
<a href="http://www.layui.com/admin/" target="_blank" title="前臺">
<i class="layui-icon layui-icon-website"></i>
</a>
</li>
<li class="layui-nav-item" lay-unselect>
<a href="javascript:;" layadmin-event="refresh" title="刷新">
<i class="layui-icon layui-icon-refresh-3"></i>
</a>
</li>
<li class="layui-nav-item layui-hide-xs" lay-unselect>
<input type="text" placeholder="搜索..." autocomplete="off" class="layui-input layui-input-search"
layadmin-event="serach" lay-action="template/search.html?keywords=">
</li>
</ul>
<ul class="layui-nav layui-layout-right" lay-filter="layadmin-layout-right">
<li class="layui-nav-item" lay-unselect>
<a lay-href="app/message/index.html" layadmin-event="message" lay-text="消息中心">
<i class="layui-icon layui-icon-notice"></i>
<!-- 如果有新消息,則顯示小圓點 -->
<span class="layui-badge-dot"></span>
</a>
</li>
<li class="layui-nav-item layui-hide-xs" lay-unselect>
<a href="javascript:;" layadmin-event="theme">
<i class="layui-icon layui-icon-theme"></i>
</a>
</li>
<li class="layui-nav-item layui-hide-xs" lay-unselect>
<a href="javascript:;" layadmin-event="note">
<i class="layui-icon layui-icon-note"></i>
</a>
</li>
<li class="layui-nav-item layui-hide-xs" lay-unselect>
<a href="javascript:;" layadmin-event="fullscreen">
<i class="layui-icon layui-icon-screen-full"></i>
</a>
</li>
<li class="layui-nav-item" lay-unselect>
<a href="javascript:;">
<cite id="account"></cite>
</a>
<dl class="layui-nav-child">
<dd><a lay-href="javascript:;" class="edit">修改密碼</a></dd>
<hr>
<dd class="logout" style="text-align: center;"><a>退出</a></dd>
</dl>
</li>
<!-- <li class="layui-nav-item layui-hide-xs" lay-unselect>
<a href="javascript:;" layadmin-event="about"><i
class="layui-icon layui-icon-more-vertical"></i></a>
</li>
<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-unselect>
<a href="javascript:;" layadmin-event="more"><i class="layui-icon layui-icon-more-vertical"></i></a>
</li>-->
</ul>
</div>
<!-- 側邊菜單 -->
<div class="layui-side layui-side-menu">
<div class="layui-side-scroll">
<div class="layui-logo" >
<span>後臺</span>
</div>
<ul class="layui-nav layui-nav-tree" lay-shrink="all" id="LAY-system-side-menu"
lay-filter="layadmin-system-side-menu">
<li data-name="home" class="layui-nav-item layui-nav-itemed">
<a href="javascript:;" lay-tips="主頁" lay-direction="1">
<i class="layui-icon layui-icon-home"></i>
<cite>內容管理</cite>
</a>
<dl class="layui-nav-child">
<dd data-name="console">
<a lay-href="information/views.html">新聞資訊</a>
</dd>
</dl>
</li>
<li data-name="home" class="layui-nav-item">
<a href="javascript:;" lay-tips="遊戲管理" lay-direction="1">
<i class="layui-icon layui-icon-home"></i>
<cite>遊戲管理</cite>
</a>
<dl class="layui-nav-child">
<dd data-name="console">
<a lay-href="game/gameno.html">開封盤</a>
</dd>
<dd data-name="console">
<a lay-href="game/kanban.html">開獎看板</a>
</dd>
</dl>
</li>
<li data-name="home" class="layui-nav-item">
<a href="javascript:;" lay-tips="反饋明細" lay-direction="1">
<i class="layui-icon layui-icon-home"></i>
<cite>反饋明細</cite>
</a>
<dl class="layui-nav-child">
<dd data-name="console">
<a lay-href="fed/fed.html">反饋明細</a>
</dd>
</dl>
</li>
</ul>
</div>
</div>
<!-- 頁面標籤 -->
<div class="layadmin-pagetabs" id="LAY_app_tabs">
<div class="layui-icon layadmin-tabs-control layui-icon-prev" layadmin-event="leftPage"></div>
<div class="layui-icon layadmin-tabs-control layui-icon-next" layadmin-event="rightPage"></div>
<div class="layui-icon layadmin-tabs-control layui-icon-down">
<ul class="layui-nav layadmin-tabs-select" lay-filter="layadmin-pagetabs-nav">
<li class="layui-nav-item" lay-unselect>
<a href="javascript:;"></a>
<dl class="layui-nav-child layui-anim-fadein">
<dd layadmin-event="closeThisTabs"><a href="javascript:;">關閉當前標籤頁</a></dd>
<dd layadmin-event="closeOtherTabs"><a href="javascript:;">關閉其它標籤頁</a></dd
<dd layadmin-event="closeAllTabs"><a href="javascript:;">關閉全部標籤頁</a></dd>
</dl>
</li>
</ul>
</div>
<div class="layui-tab" lay-unauto lay-allowClose="true" lay-filter="layadmin-layout-tabs">
<ul class="layui-tab-title" id="LAY_app_tabsheader">
<li lay-id="report/financial.html" lay-attr="home/console.html" class="layui-this"><i
class="layui-icon layui-icon-home"></i></li>
</ul>
</div>
</div>
<!-- 主體內容 -->
<div class="layui-body" id="LAY_app_body">
<div class="layadmin-tabsbody-item layui-show">
<iframe src="information/views.html" frameborder="0" class="layadmin-iframe"></iframe>
</div>
</div>
<!-- 輔助元素,一般用於移動設備下遮罩 -->
<div class="layadmin-body-shade" layadmin-event="shade"></div>
</div>
</div>
<script src="../layuiadmin/layui/layui.js"></script>
<script>
layui.config({
base: '../layuiadmin/' //靜態資源所在路徑
}).extend({
index: 'lib/index' //主入口模塊
}).use(['index', 'indexs'], function () {
layui.indexs.init();
});
</script>
</body>
</html>
/**
@Name:登錄
@Author:阿平
@Site:
@License:LPPL
*/
var $;
layui.define(['table', 'form', 'sd', 'layedit', 'upload'], function (exports) {
var table = layui.table
, sd = layui.sd
, form = layui.form
, layedit = layui.layedit
, upload = layui.upload;
$ = layui.$;
var api = {
getaccount: 'back/account/getaccount',
alive: 'back/account/alive',
removecookie: 'back/account/removecookie',
setpassword: 'back/account/setpassword',
};
/*獲取cookie的值*/
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
function removeCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()+";
/**
* 獲取登錄人賬號
*/
function getLoginAccount() {
sd.ajax.request(api.getaccount, {}, function (res) {
if (res.code == '0') {
var account = res.data;
//$("#account").html("");
$("#account").html(account);
} else {
sd.msg.error(res.msg);
}
});
}
$(document).on('click', '.logout', function () {
layer.confirm('確定退出登錄嗎?', function (index) {
sd.ajax.request(api.removecookie, {}, function (res) {
if (res.code == '0') {
removeCookie("token");
location.href = "login.html";
} else {
sd.msg.error(res.msg);
}
});
})
});
/**
* 實時加載登錄狀態
*/
function alive() {
var token = getCookie("token");
if (token == null || token === undefined || token == "") {
location.href = "login.html";
} else {
sd.ajax.request(api.alive, {}, function (res) {
var data = res;
if (res.data == null || res.data === undefined || res.data == "") {
removeCookie("token");
location.href = "login.html";
return;
}
var sear = new RegExp('login.html');
if (!sear.test(data)) {
setTimeout(function () {
alive();
}, 5000);
} else {
removeCookie("token");
location.href = "login.html";
}
});
}
}
/**
* 修改密碼
*/
$(document).on('click', '.edit', function () {
layer.open({
type: 2
, title: '修改密碼'
, content: '../views/account/password.html'
, maxmin: false
, btn: ['確定', '取消']
, yes: function (index, layero) {
var iframeWindow = window['layui-layer-iframe' + index]
, submitID = 'btn-submit'
, submit = layero.find('iframe').contents().find('#' + submitID);
//監聽提交
iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
$(this).attr("disabled", "disabled");
var field = data.field; //獲取提交的字段
field.content = iframeWindow.layui.layedit.getContent(field.fdindex);
sd.ajax.request(api.setpassword, {
account: field.account,
olapassword: field.olapassword,
newpassword: field.password
}, function (res) {
if (res.code == '0') {
layer.alert("密碼修改成功,請重新登錄", function () {
sd.ajax.request(api.removecookie, {}, function (res) {
if (res.code == 0) {
location.href = "login.html";
} else {
layer.alert(response.msg);
}
})
// parent.layer.close(index); //執行關閉
});
} else {
sd.msg.error(res.msg);
}
});
});
submit.trigger('click');
}
});
})
/* 自定義驗證規則 */
form.verify({
//密碼驗證
pass: [/(.+){4,12}$/, '密碼必須4到12位']
, repass: function (value) {
if (value !== $('#password').val()) {
return '兩次密碼輸入不一致';
}
}
});
//供外部調用,定義在call下
var call = {};
//列表頁初始化
call.init = function () {
getLoginAccount();
alive();
};
//編輯頁初始化
call.initEdit = function () {
sd.ajax.request(api.getaccount, {}, function (res) {
if (res.code == '0') {
var account = res.data;
$("#account").val(account);
} else {
sd.msg.error(res.msg);
}
});
};
//對外暴露
exports('indexs', call);
});
後臺:
controller
import com.alibaba.fastjson.JSON;
import com.sd.lottery.common.enums.ResponseCode;
import com.sd.lottery.common.model.ResponseModel;
import com.sd.lottery.dataservice.redis.RedisUtil;
import com.sd.lottery.dataservice.pojo.AccountPojo;
import com.sd.lottery.manageservice.service.AccountService;
import com.sd.lottery.manageservice.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping(value = "/back/account/")
public class AccountController {
@Autowired
private AccountService accountService;
@Autowired
private LoginService loginService;
/**
* 用戶登錄接口
*
* @param account:賬號
* @param password:密碼
* @return 是否登錄成功
*/
@RequestMapping(value = "login")
public String login(@RequestParam String account, @RequestParam String password) {
ResponseModel<Integer, Object> responseModel = accountService.login(account, password);
return responseModel.toString();
}
/**
* 修改密碼
*
* @param account:賬號
* @param olapassword:舊密碼
* @param newpassword:新密碼
* @return 密碼是否修改成功
*/
@RequestMapping(value = "setpassword")
public String setPassword(@RequestParam String account, @RequestParam String olapassword, @RequestParam String newpassword) {
ResponseModel<Integer, Object> responseModel = accountService.setPassword(account, olapassword, newpassword);
/**
* 移除cookie
*
* @return cookie是否移除成功
*/
@RequestMapping("removecookie")
public String removeCookie(HttpServletResponse response, HttpServletRequest request) {
ResponseModel<Integer, Object> responseModel = new ResponseModel<>();
try {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
// 立即銷燬cookie
if ("token".equals(cookie.getName())) {
RedisUtil.hdel("kj_login", cookie.getValue());
/* cookie.setValue(null);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
responseModel.setCode(ResponseCode.SUCCESS.getCode());
} catch (Exception ex) {
responseModel.setCode(ResponseCode.FAILED.getCode())
.setMsg("內部錯誤");
}
return responseModel.toString();
}
@RequestMapping(value = "getaccountpojo")
public static AccountPojo getLoginAccountPojo(String token) {
String activity_login = RedisUtil.getMapField("kj_login", token);
return JSON.parseObject(activity_login, AccountPojo.class)
}
/**
* 獲取登錄人的賬號
*
* @return 登錄人賬號
*/
@RequestMapping(value = "getaccount")
public String getLoginAccount() {
ResponseModel<Integer, String> responseModel = new ResponseModel<>();
responseModel.setCode(ResponseCode.SUCCESS.getCode())
.setData(loginService.getAccount());
return responseModel.toString();
}
/**
* 實時刷新登錄狀態
*
* @return 是否還在線
*/
@RequestMapping(value = "alive")
public ResponseModel alive() {
ResponseModel responseModel=new ResponseModel();
responseModel.setData(loginService.getAccount());
return responseModel;
}
}
AccountService
import com.sd.lottery.common.model.ResponseModel;
public interface AccountService {
/**
* 用戶登錄接口
*
* @param account:賬號
* @param password:密碼
* @return 是否登錄成功
*/
ResponseModel<Integer,Object> login(String account, String password);
/**
* 修改密碼
*
* @param account:賬號
* @param olapassword:舊密碼
* @param newpassword:新密碼
* @return 密碼是否修改成功
*/
ResponseModel<Integer,Object> setPassword(String account, String olapassword, String newpassword);
}
AccountServiceImpl
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.sd.lottery.common.enums.ResponseCode;
import com.sd.lottery.common.model.ResponseModel;
import com.sd.lottery.dataservice.redis.RedisUtil;
import com.sd.lottery.common.utils.CookieHelper;
import com.sd.lottery.common.utils.MD5Helper;
import com.sd.lottery.dataservice.mapper.AccountMapper;
import com.sd.lottery.dataservice.pojo.AccountPojo;
import com.sd.lottery.dataservice.pojo.AccountPojo;
import com.sd.lottery.manageservice.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
@Service
public class AccountServiceImpl implements AccountService {
/**
* 返回提示信息 code:狀態碼 msg:錯誤提示信息 exception:異常信息
*/
private Integer code;
private String msg;
private Exception exception;
@Autowired
private HttpServletResponse response;
@Autowired
private HttpServletRequest request;
@Autowired
private AccountMapper accountMapper;
private final static Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);
/**
* 用戶登錄接口
*
* @param account:賬號
* @param password:密碼
* @return 是否登錄成功
*/
@Override
public ResponseModel<Integer, Object> login(String account, String password) {
if (Strings.isNullOrEmpty(account)) {
code = ResponseCode.FAILED.getCode();
msg = "請輸入賬號";
} else if (Strings.isNullOrEmpty(password)) {
code = ResponseCode.FAILED.getCode();
msg = "請輸入密碼";
} else {
try {
account=account.trim();
password=password.trim();
ResponseModel<Integer, AccountPojo> model = get(account);
if (model.getCode().equals(ResponseCode.SUCCESS.getCode())) {
AccountPojo accountPojo = model.getData();
//判斷賬號是否存在
if (accountPojo == null) {
code = ResponseCode.FAILED.getCode();
msg = "賬號不存在";
} else {
// String a= MD5Helper.encrypt(password);
if (accountPojo.getPassword().equals(MD5Helper.encrypt(password))) {
//登錄成功
//把登錄人信息保存進入redis
String loginAccountKey = UUID.randomUUID().toString().replace("-", "");
RedisUtil.addMap("kj_login", loginAccountKey, JSON.toJSONString(accountPojo.setPassword("")));
CookieHelper.set("token", loginAccountKey, request, response);
code = ResponseCode.SUCCESS.getCode();
msg = "登錄成功";
} else {
code = model.getCode();
msg = model.getMsg();
exception = model.getException();
}
} catch (Exception e) {
code = ResponseCode.INNER_ERROR.getCode();
msg = "內部錯誤";
exception = e;
}
}
ResponseModel<Integer, Object> responseModel = new ResponseModel<>();
responseModel.setCode(code)
.setMsg(msg)
.setException(exception);
return responseModel;
}
/**
* 根據賬號獲取用戶信息
*
* @param account:用戶賬號
* @return 用戶信息對象
*/
public ResponseModel<Integer, AccountPojo> get(String account) {
ResponseModel<Integer, AccountPojo> responseModel = new ResponseModel<>();
try {
AccountPojo accountPojo = accountMapper.selectOne(new AccountPojo().setAccount(account.trim()));
responseModel.setCode(ResponseCode.SUCCESS.getCode())
.setData(accountPojo);
} catch (Exception e) {
responseModel.setCode(ResponseCode.INNER_ERROR.getCode())
.setMsg("內部錯誤")
.setException(e);
}
return responseModel;
}
/**
* 修改密碼
*
* @param account:賬號
* @param olapassword:舊密碼
* @param newpassword:新密碼
* @return 密碼是否修改成功
*/
@Override
public ResponseModel<Integer, Object> setPassword(String account, String olapassword, String newpassword) {
if (Strings.isNullOrEmpty(account)
|| Strings.isNullOrEmpty(olapassword)
|| Strings.isNullOrEmpty(newpassword)
) {
code = ResponseCode.FAILED.getCode();
msg = "參數錯誤";
} else {
try {
/*
1、查詢出用戶信息
*/
AccountPojo accountPojo = get(account).getData();
/*
2、判斷舊密碼是否正確
*/
if (!accountPojo.getPassword().equalsIgnoreCase(MD5Helper.encrypt(olapassword))) {
code = ResponseCode.FAILED.getCode();
msg = "舊密碼錯誤";
} else {
accountPojo.setPassword(MD5Helper.encrypt(newpassword));
if (accountMapper.updateByPrimaryKeySelective(accountPojo) == 1) {
code = ResponseCode.SUCCESS.getCode();
msg = "密碼修改成功";
}
}
} catch (Exception e) {
code = ResponseCode.INNER_ERROR.getCode();
msg = "內部錯誤";
exception = e;
}
}
ResponseModel<Integer, Object> responseModel = new ResponseModel<>();
responseModel.setCode(code)
.setMsg(msg)
.setException(exception);
return responseModel;
}
}
LoginService
public interface LoginService {
/**
* 獲取登錄人的賬號
*
* @return 登錄人賬號
*/
String getAccount();
}
LoginServiceInpl
import com.alibaba.fastjson.JSON;
import com.sd.lottery.dataservice.redis.RedisUtil;
import com.sd.lottery.common.utils.CookieHelper;
import com.sd.lottery.dataservice.pojo.AccountPojo;
import com.sd.lottery.manageservice.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
@Service
public class LoginServiceInpl implements LoginService {
@Autowired
private HttpServletRequest request;
/**
* 日誌
*/
private final static Logger logger = LoggerFactory.getLogger(LoginServiceInpl.class);
/**
* 獲取登錄人的賬號
*
* @return 登錄人賬號
*/
@Override
public String getAccount() {
AccountPojo pojo = get();
return pojo == null ? "" : pojo.getAccount();
}
/**
* 獲取登錄人的一整條信息
*
* @return 登錄人的信息
*/
private AccountPojo get() {
String token = CookieHelper.getVal("token", request);
String kj_login = RedisUtil.getMapField("kj_login", token);
return JSON.parseObject(kj_login, AccountPojo.class);
}
}
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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.sd</groupId>
<artifactId>kaijiang</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.sd.kaijiang</groupId>
<artifactId>manageservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>manageservice</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!--swagg2依賴組件-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!--pageHelp-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!--熱部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sd.kaijiang</groupId>
<artifactId>dataservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>
LoginInfoHelper
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.sd.lottery.dataservice.redis.RedisUtil;
import com.sd.lottery.common.utils.CookieHelper;
import com.sd.lottery.common.utils.MD5Helper;
import com.sd.lottery.manageservice.controller.back.AccountController;
import com.sd.lottery.dataservice.pojo.AccountPojo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
public class LoginInfoHelper {
public static Boolean checkLoginInfo(HttpServletRequest request, HttpServletResponse response) {
String token = CookieHelper.getVal("token", request);
Long id;
String account = "";
String name = "";
Long acttime = null;
if (!Strings.isNullOrEmpty(token)) {
AccountPojo pojo = AccountController.getLoginAccountPojo(token);
// AccountPojo pojo = new AccountPojo();
if (pojo == null) {
return false;
}
account = pojo.getAccount();
name = pojo.getName();
acttime = (new Date().getTime());
id = pojo.getId();
Map<String, AccountPojo> accountPojoMap = RedisUtil.mget("kj_login", AccountPojo.class);
for (Object obj : accountPojoMap.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
String value = (String) entry.getValue();
AccountPojo sitePojo = JSON.parseObject(value, AccountPojo.class);
if (sitePojo.getId().equals(id)
&& sitePojo.getAccount().equalsIgnoreCase(account)
&& sitePojo.getName().equalsIgnoreCase(name)) {
String key = (String) entry.getKey();
if (!key.equalsIgnoreCase(token)) {
RedisUtil.hdel("kj_login", key);
}
}
}
}
if (Strings.isNullOrEmpty(account)
|| Strings.isNullOrEmpty(name)
|| Strings.isNullOrEmpty(token)
|| acttime == null
) {
return false;
} else try {
Long t = Long.parseLong(acttime.toString());
if (t < new Date().getTime() - 30 * 60000) {
return false;
} else if (!Strings.isNullOrEmpty(token)) {
// updateLoginInfo(account, name, response);
return true;
} else {
return false;
}
} catch (Exception ex) {
return false;
}
}
/*public static void updateLoginInfo(String user, String name, HttpServletResponse response) {
if (!Strings.isNullOrEmpty(user) && !Strings.isNullOrEmpty(name)) {
Long acttime = new Date().getTime();
CookieHelper.set("user", user.trim(), response);
CookieHelper.set("name", name.trim(), response);
CookieHelper.set("acttime", acttime.toString(), response);
CookieHelper.set("token", createToken(user, name, acttime)
}
}*/
private static String createToken(String user, String name, Long acttime) {
String str = String.format("%s_%s_%d", user.trim().toLowerCase(), name.trim().toLowerCase(), acttime);
return MD5Helper.encrypt(str);
}
}
FileHelper
import com.google.common.base.Strings;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
/**
* 文件工具類
*/
public class FileHelper {
/**
* @param file
* @param filePath
* @return
* @throws Exception
*/
public static String getupload(org.springframework.web.multipart.MultipartFile file, String filePath, String formalfilePath) throws Exception {
//a.jpg--->.jpg
String ertName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//獲取文件格式
String fileName = UUID.randomUUID().toString() + ertName;//uuid創建文件
try {
File dir = new File(filePath);
File dirformal = new File(formalfilePath);
if (!dir.exists()) {
//創建文件夾
if (!dir.mkdirs()) {
return "";
}
}
if (!dirformal.exists()) {
//創建文件夾
if (!dirformal.mkdirs()) {
return "";
}
}
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath + fileName)));//把文件寫入磁盤
} catch (IOException e) {
e.printStackTrace();
}
return fileName;//返回名稱
}
/**
* tu'ai'n
* 圖片/文件 上傳
*
* @param file 上傳對象
* @param uploadDir 文件上傳目錄
* @return 操作結果
*/
public static String uploadFile(MultipartFile file, String uploadDir) {
String fileName;
try {
File dir = new File(uploadDir);
//判斷文件夾是否存在
if (!dir.exists()) {
//創建文件夾
if (!dir.mkdirs()) {
return "";
}
}
fileName = executeUpload(uploadDir, file);
} catch (Exception e) {
fileName = "";
e.getStackTrace();
}
return fileName;
}
/**
* 提取上傳方法爲公共方法
*
* @param uploadDir:上傳文件目錄
* @param file:上傳對象
* @return 文件名
*/
private static String executeUpload(String uploadDir, MultipartFile file) {
String fileName = "";
if (Strings.isNullOrEmpty(uploadDir) || file == null) {
fileName = "";
} else {
try {
if (file.getOriginalFilename() != null) {
//文件後綴名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//上傳文件名
fileName = UUID.randomUUID() + suffix;
//服務器端保存的文件對象
File serverFile = new File(uploadDir + fileName);
//將上傳的文件寫入到服務器端文件內
file.transferTo(serverFile);
}
} catch (Exception e) {
fileName = "";
e.getStackTrace();
}
}
return fileName;
}
/**
* 文件 移動
*
* @param tempFile:移動對象
* @param descFile:移動之後的對象
* @return 文件是否移動成功
*/
public static boolean renameTo(String tempFile, String descFile) {
Boolean isCopyFile = true;
try {
//文件路徑model(比如:apk的路徑,ipa的路徑)
if (!tempFile.equalsIgnoreCase("") && !descFile.equalsIgnoreCase("")) {
File dest = new File(descFile);
File file = new File(tempFile);
//判斷移動的兩個路徑是否是一樣的
if (dest.getPath().equals(file.getPath())) {
return true;
}
//如果這個文件已存在的話就刪除(desc)copy的位置,並且顯示
if (dest.exists()) {
return true;
// dest.delete();
}
//copy文件 file 複製到dest
return file.renameTo(dest);
}
} catch (Exception ex) {
isCopyFile = false;
ex.printStackTrace();
}
return isCopyFile;
}
}
AESDecryptHelper
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* AES 加密、解密
*/
public class AESDecryptHelper {
/**
* AES加密
* @param value
* @return
* @throws Exception
*/
public static String AESEncrypt(String value,String key){
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
byte[] raw = key.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
String base64 = new BASE64Encoder().encode(encrypted);// 此處使用BASE64做轉碼
return URLEncoder.encode(base64, "UTF-8");//URL加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}
return "";
}
/**
* AES加密 不進行URLEncoder
* @param value
* @return
* @throws Exception
*/
public static String AESUNURLEncrypt(String value,String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
byte[] raw = key.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
return new BASE64Encoder().encode(encrypted);// 此處使用BASE64做轉碼
}
/**
* AES 解密
* @param value
* @return
* @throws Exception
*/
public static String AESDecrypt(String value,String key,boolean isDecodeURL) throws Exception {
try {
byte[] raw = key.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
if(isDecodeURL) value = URLDecoder.decode(value, "UTF-8");
byte[] encrypted1 = new BASE64Decoder().decodeBuff
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "UTF-8");
return originalString;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
CookieHelper
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Cookie 工具類
*
* @author test
*
*/
public class CookieHelper {
/**
* 設置COOKIE
*/
public static void set(String cookieKey, String val, HttpServletRequest request,
HttpServletResponse response) {
Cookie cookie = new Cookie(cookieKey, val);
//String url = NetHelper.getHostForwarded(request);
//url = NetHelper.getMainDomain(url);
//cookie.setDomain(url);
cookie.setMaxAge(-1);
cookie.setPath("/");
response.addCookie(cookie);
}
/**
* 獲取COOKIE對象
*
* @param cookieKey
* @param request
* @return
*/
public static Cookie get(String cookieKey, HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().toLowerCase()
.equals(cookieKey.toLowerCase())) {
return cookie;
}
}
}
return null;
}
/**
* 獲取COOKIE值
*
* @param cookieKey
* @param request
* @return
*/
public static String getVal(String cookieKey, HttpServletRequest request) {
Cookie cookie = get(cookieKey, request);
if (cookie != null) {
return cookie.getValue();
} else {
return null;
}
}
/**
* 移除COOKIE
*
* @param cookieKey
* @param request
* @param response
*/
public static void remove(String cookieKey, HttpServletRequest request,
HttpServletResponse response) {
Cookie cookie = get(cookieKey, request);
if (cookie != null) {
cookie.setValue(null);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
DateHelper
import com.sd.lottery.common.enums.EnumDate;
import com.sd.lottery.common.enums.EnumDateType;
import com.sd.lottery.common.model.DateModel;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateHelper {
/**
* 當前時間
*
* @return
*/
public static Date now() {
/*TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
TimeZone.setDefault(tz);*/
Date date = new Date();
return date;
}
/**
* 獲取時間範圍
*
* @param d 參考時間
* @param type 類型 1:昨天、2:今天 3:本週 4:本月 5:上月
* @return
*/
public static DateModel getTimeRange(Date d, EnumDate type) {
Date minDate = null;
Date maxDate = null;
switch (type) {
case TODAY://昨天
d = add(d, -1, EnumDateType.DAY);
minDate = format(d, "yyyy-MM-dd 00:00:00", "yyyy-MM-dd HH:mm:ss");
maxDate = format(d, "yyyy-MM-dd 23:59:59", "yyyy-MM-dd HH:mm:ss");
break;
case WEEK://本週
minDate = getTimesWeekmorning(d);
maxDate = add(minDate, 6, EnumDateType.DAY);
maxDate = format(maxDate, "yyyy-MM-dd 23:59:59", "yyyy-MM-dd HH:mm:ss");
break;
case MONTH://本月
minDate = format(d, "yyyy-MM-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
maxDate = add(minDate, 1, EnumDateType.MONTH);
maxDate = add(maxDate, -1, EnumDateType.DAY);
maxDate = format(maxDate, "yyyy-MM-dd 23:59:59", "yyyy-MM-dd HH:mm:ss");
break;
case PREVMONTH://上月
d = add(d, -1, EnumDateType.MONTH);
minDate = format(d, "yyyy-MM-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
maxDate = add(minDate, 1, EnumDateType.MONTH);
maxDate = add(maxDate, -1, EnumDateType.DAY);
maxDate = format(maxDate, "yyyy-MM-dd 23:59:59", "yyyy-MM-dd HH:mm:ss");
break;
case PREVWEEK://上週
minDate = getTimesWeekmorning(d);
minDate = add(minDate, -7, EnumDateType.DAY);
maxDate = add(minDate, 6, EnumDateType.DAY);
maxDate = format(maxDate, "yyyy-MM-dd 23:59:59", "yyyy-MM-dd HH:mm:ss");
break;
case SEVENDAY:
maxDate = format(d, "yyyy-MM-dd 23:59:59", "yyyy-MM-dd HH:mm:ss");
d = add(d, -7, EnumDateType.DAY);
minDate = format(d, "yyyy-MM-dd 00:00:00", "yyyy-MM-dd HH:mm:ss");
break;
default:
break;
}
DateModel model = new DateModel();
model.setMintime(minDate);
model.setMaxtime(maxDate);
return model;
}
/**
* 日期增加
*
* @param time --當前日期
* @param v --變化值
* @param t --變化類型 D: 天 M:月 Y:年 h:時, MI: 分鐘 n:秒
* @return
*/
public static Date add(Date time, Integer v, EnumDateType t) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(time);
switch (t) {
case DAY:
calendar.add(Calendar.DATE, v);
break;
case MONTH:
calendar.add(Calendar.MONTH, v);
break;
case YEAR:
calendar.add(Calendar.DAY_OF_YEAR, v);
break;
case MINUTE:
calendar.add(Calendar.MINUTE, v);
break;
case SECOND:
calendar.add(Calendar.SECOND, v);
break;
case HOUR:
calendar.add(Calendar.HOUR_OF_DAY, v);
break;
case WEEK:
calendar.add(Calendar.DAY_OF_WEEK, v);
break;
default:
break;
}
return calendar.getTime();
}
/**
* 計算D1 與 D2 比較 相差的秒數
*
* @param d1
* @param d2
* @return
*/
public static Long diffSecond(Date d1, Date d2) {
if (d1 == null || d2 == null) {
return null;
}
long a = d1.getTime();
long b = d2.getTime();
long c = (b - a) / 1000;
return c;
}
/**
* 相差天數
*
* @param d1
* @param d2
* @return
*/
public static Integer diffDay(Date d1, Date d2) {
if (d1 == null || d2 == null) {
return null;
}
long a = d1.getTime();
long b = d2.getTime();
Long c = (b - a) / 1000 / 3600 / 24;
return c.intValue();
}
/**
* 時間格式化
*
* @param time
* @param formatString
* @return
*/
public static String formatDate(Date time, String formatString) {
if (time == null) {
return "";
}
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
return dateFormat.format(time);
}
/**
* 時間比較
*
* @param hours1
* @param minute1
* @param hours2
* @param minute2
* @return 1:時間 1大 2:時間1 小 0:相等
*/
public static int compare(int hours1, int minute1, int hours2, int minute2) {
Calendar calendar = new GregorianCalendar();
calendar.set(2017, 1, 1, hours1, minute1, 0);
Date d1 = calendar.getTime();
calendar.set(2017, 1, 1, hours2, minute2, 0);
Date d2 = calendar.getTime();
if (d1.getTime() == d2.getTime()) {
return 0;
} else if (d1.getTime() > d2.getTime()) {
return 1;
} else {
return 2;
}
}
/**
* 字符串轉日期
*
* @param pattern
* @param dateStr
* @return
*/
public static Date stringToDate(String pattern, String dateStr) {
if (dateStr == null || dateStr == "") {
return null;
}
Date date = null;
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
date = format.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
return date;
}
/**
* 獲取年份
*
* @param d
* @return
*/
public static Integer getYear(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
Integer year = cal.get(Calendar.YEAR);
return year;
}
/**
* 獲取月份
*
* @param d
* @return
*/
public static Integer getMonth(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
Integer month = cal.get(Calendar.MONTH) + 1;
return month;
}
/**
* 獲取日
*
* @param d
* @return
*/
public static Integer getDay(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
Integer day = cal.get(Calendar.DAY_OF_MONTH);
return day;
}
/**
* 獲取周幾
*
* @param d
* @return
*/
public static String getWeek(Date d) {
String week = "";
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int cweek = cal.get(Calendar.DAY_OF_WEEK);
switch (cweek) {
case 1:
week = "日";
break;
case 2:
week = "一";
break;
case 3:
week = "二";
break;
case 4:
week = "三";
break;
case 5:
week = "四";
break;
case 6:
week = "五";
break;
case 7:
week = "六";
break;
}
return "星期" + week;
}
/**
* 格式化
*
* @param date
* @param formatStr
* @return
*/
public static Date format(Date date, String formatStr, String formatDate) {
if (formatDate == null) {
formatDate = formatStr;
}
String dateStr = DateHelper.formatDate(date, formatStr);
return stringToDate(formatDate, dateStr);
}
public static Date format(Date date, String formatStr) {
return format(date, formatStr, null);
}
/**
* 日期轉字符串
*
* @param date
* @param pattern
* @return
*/
public static String dateToString(Date date, String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
String str = formatter.format(date);
return str;
}
/**
* 時間戳轉時間
*
* @param s
* @return
*/
public static Date stampToDate(String s) {
if (s == null || s.equals("")) {
return null;
}
long lt = new Long(s);
Date date = new Date(lt);
return date;
}
/**
* 獲取指定時間所在周的週一
*
* @param d
* @return
*/
private static Date getTimesWeekmorning(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
// 獲得當前日期是一個星期的第幾天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 設置一個星期的第一天,按中國的習慣一個星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 獲得當前日期是一個星期的第幾天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根據日曆的規則,給當前日期減去星期幾與一個星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
return cal.getTime();
}
/**
* 獲取從今天開始往前數30天的每一天時間
* @return
*/
public static List Calendar (){
Calendar begin = Calendar.getInstance();// 得到一個Calendar的實例
begin.setTime(new Date()); // 設置時間爲當前時間
begin.add(Calendar.MONTH, -1);// 月份減1
begin.add(Calendar.DATE, +1);// 日期加1
Date result = begin.getTime();
Calendar end = Calendar.getInstance();
Long startTime = begin.getTimeInMillis();
Long endTime = end.getTimeInMillis();
Long oneDay = 1000 * 60 * 60 * 24l;// 一天的時間轉化爲ms
List dates = new ArrayList<>();
Long time = startTime;
int i = 0;
while (time <= endTime) {
Date d = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
dates.add(i, df.format(d));
i++;
time += oneDay;
}
return dates;
}
}
/**
- 農曆公曆互轉
- @author test
*/
LunarSolarConverter
import com.sd.lottery.common.model.Lunar;
import com.sd.lottery.common.model.Solar;
import java.util.Date;
/**
* 農曆公曆互轉
* @author test
*
*/
public class LunarSolarConverter {
/*
* |----4位閏月|-------------13位1爲30天,0爲29天|
*/
private static int[] lunar_month_days = { 1887, 0x1694, 0x16aa, 0x4ad5, 0xab6, 0xc4b7, 0x4ae, 0xa56, 0xb52a, 0x1d2a,
0xd54, 0x75aa, 0x156a, 0x1096d, 0x95c, 0x14ae, 0xaa4d, 0x1a4c, 0x1b2a, 0x8d55, 0xad4, 0x135a, 0x495d, 0x95c,
0xd49b, 0x149a, 0x1a4a, 0xbaa5, 0x16a8, 0x1ad4, 0x52da, 0x12b6, 0xe937, 0x92e, 0x1496, 0xb64b, 0xd4a, 0xda8,
0x95b5, 0x56c, 0x12ae, 0x492f, 0x92e, 0xcc96, 0x1a94, 0x1d4a, 0xada9, 0xb5a, 0x56c, 0x726e, 0x125c, 0xf92d,
0x192a, 0x1a94, 0xdb4a, 0x16aa, 0xad4, 0x955b, 0x4ba, 0x125a, 0x592b, 0x152a, 0xf695, 0xd94, 0x16aa, 0xaab5,
0x9b4, 0x14b6, 0x6a57, 0xa56, 0x1152a, 0x1d2a, 0xd54, 0xd5aa, 0x156a, 0x96c, 0x94ae, 0x14ae, 0xa4c, 0x7d26,
0x1b2a, 0xeb55, 0xad4, 0x12da, 0xa95d, 0x95a, 0x149a, 0x9a4d, 0x1a4a, 0x11aa5, 0x16a8, 0x16d4, 0xd2da,
0x12b6, 0x936, 0x9497, 0x1496, 0x1564b, 0xd4a, 0xda8, 0xd5b4, 0x156c, 0x12ae, 0xa92f, 0x92e, 0xc96, 0x6d4a,
0x1d4a, 0x10d65, 0xb58, 0x156c, 0xb26d, 0x125c, 0x192c, 0x9a95, 0x1a94, 0x1b4a, 0x4b55, 0xad4, 0xf55b,
0x4ba, 0x125a, 0xb92b, 0x152a, 0x1694, 0x96aa, 0x15aa, 0x12ab5, 0x974, 0x14b6, 0xca57, 0xa56, 0x1526,
0x8e95, 0xd54, 0x15aa, 0x49b5, 0x96c, 0xd4ae, 0x149c, 0x1a4c, 0xbd26, 0x1aa6, 0xb54, 0x6d6a, 0x12da,
0x1695d, 0x95a, 0x149a, 0xda4b, 0x1a4a, 0x1aa4, 0xbb54, 0x16b4, 0xada, 0x495b, 0x936, 0xf497, 0x1496,
0x154a, 0xb6a5, 0xda4, 0x15b4, 0x6ab6, 0x126e, 0x1092f, 0x92e, 0xc96, 0xcd4a, 0x1d4a, 0xd64, 0x956c, 0x155c,
0x125c, 0x792e, 0x192c, 0xfa95, 0x1a94, 0x1b4a, 0xab55, 0xad4, 0x14da, 0x8a5d, 0xa5a, 0x1152b, 0x152a,
0x1694, 0xd6aa, 0x15aa, 0xab4, 0x94ba, 0x14b6, 0xa56, 0x7527, 0xd26, 0xee53, 0xd54, 0x15aa, 0xa9b5, 0x96c,
0x14ae, 0x8a4e, 0x1a4c, 0x11d26, 0x1aa4, 0x1b54, 0xcd6a, 0xada, 0x95c, 0x949d, 0x149a, 0x1a2a, 0x5b25,
0x1aa4, 0xfb52, 0x16b4, 0xaba, 0xa95b, 0x936, 0x1496, 0x9a4b, 0x154a, 0x136a5, 0xda4, 0x15ac };
private static int[] solar_1_1 = { 1887, 0xec04c, 0xec23f, 0xec435, 0xec649, 0xec83e, 0xeca51, 0xecc46, 0xece3a,
0xed04d, 0xed242, 0xed436, 0xed64a, 0xed83f, 0xeda53, 0xedc48, 0xede3d, 0xee050, 0xee244, 0xee439, 0xee64d,
0xee842, 0xeea36, 0xeec4a, 0xeee3e, 0xef052, 0xef246, 0xef43a, 0xef64e, 0xef843, 0xefa37, 0xefc4b, 0xefe41,
0xf0054, 0xf0248, 0xf043c, 0xf0650, 0xf0845, 0xf0a38, 0xf0c4d, 0xf0e42, 0xf1037, 0xf124a, 0xf143e, 0xf1651,
0xf1846, 0xf1a3a, 0xf1c4e, 0xf1e44, 0xf2038, 0xf224b, 0xf243f, 0xf2653, 0xf2848, 0xf2a3b, 0xf2c4f, 0xf2e45,
0xf3039, 0xf324d, 0xf3442, 0xf3636, 0xf384a, 0xf3a3d, 0xf3c51, 0xf3e46, 0xf403b, 0xf424e, 0xf4443, 0xf4638,
0xf484c, 0xf4a3f, 0xf4c52, 0xf4e48, 0xf503c, 0xf524f, 0xf5445, 0xf5639, 0xf584d, 0xf5a42, 0xf5c35, 0xf5e49,
0xf603e, 0xf6251, 0xf6446, 0xf663b, 0xf684f, 0xf6a43, 0xf6c37, 0xf6e4b, 0xf703f, 0xf7252, 0xf7447, 0xf763c,
0xf7850, 0xf7a45, 0xf7c39, 0xf7e4d, 0xf8042, 0xf8254, 0xf8449, 0xf863d, 0xf8851, 0xf8a46, 0xf8c3b, 0xf8e4f,
0xf9044, 0xf9237, 0xf944a, 0xf963f, 0xf9853, 0xf9a47, 0xf9c3c, 0xf9e50, 0xfa045, 0xfa238, 0xfa44c, 0xfa641,
0xfa836, 0xfaa49, 0xfac3d, 0xfae52, 0xfb047, 0xfb23a, 0xfb44e, 0xfb643, 0xfb837, 0xfba4a, 0xfbc3f, 0xfbe53,
0xfc048, 0xfc23c, 0xfc450, 0xfc645, 0xfc839, 0xfca4c, 0xfcc41, 0xfce36, 0xfd04a, 0xfd23d, 0xfd451, 0xfd646,
0xfd83a, 0xfda4d, 0xfdc43, 0xfde37, 0xfe04b, 0xfe23f, 0xfe453, 0xfe648, 0xfe83c, 0xfea4f, 0xfec44, 0xfee38,
0xff04c, 0xff241, 0xff436, 0xff64a, 0xff83e, 0xffa51, 0xffc46, 0xffe3a, 0x10004e, 0x100242, 0x100437,
0x10064b, 0x100841, 0x100a53, 0x100c48, 0x100e3c, 0x10104f, 0x101244, 0x101438, 0x10164c, 0x101842,
0x101a35, 0x101c49, 0x101e3d, 0x102051, 0x102245, 0x10243a, 0x10264e, 0x102843, 0x102a37, 0x102c4b,
0x102e3f, 0x103053, 0x103247, 0x10343b, 0x10364f, 0x103845, 0x103a38, 0x103c4c, 0x103e42, 0x104036,
0x104249, 0x10443d, 0x104651, 0x104846, 0x104a3a, 0x104c4e, 0x104e43, 0x105038, 0x10524a, 0x10543e,
0x105652, 0x105847, 0x105a3b, 0x105c4f, 0x105e45, 0x106039, 0x10624c, 0x106441, 0x106635, 0x106849,
0x106a3d, 0x106c51, 0x106e47, 0x10703c, 0x10724f, 0x107444, 0x107638, 0x10784c, 0x107a3f, 0x107c53,
0x107e48 };
private static int GetBitInt(int data, int length, int shift) {
return (data & (((1 << length) - 1) << shift)) >> shift;
}
// WARNING: Dates before Oct. 1582 are inaccurate
private static long SolarToInt(int y, int m, int d) {
m = (m + 9) % 12;
y = y - m / 10;
return 365 * y + y / 4 - y / 100 + y / 400 + (m * 306 + 5) / 10 + (d - 1);
}
/**
*
* @param lunarYear
* 農曆年份
* @return String of Ganzhi: 甲子年 Tiangan:甲乙丙丁戊己庚辛壬癸<br/>
* Dizhi: 子醜寅卯辰巳無爲申酉戌亥
*/
public static String lunarYearToGanZhi(int lunarYear) {
final String[] tianGan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
final String[] diZhi = { "子", "醜", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
private static Solar SolarFromInt(long g) {
long y = (10000 * g + 14780) / 3652425;
long ddd = g - (365 * y + y / 4 - y / 100 + y / 400);
if (ddd < 0) {
y--;
ddd = g - (365 * y + y / 4 - y / 100 + y / 400);
}
long mi = (100 * ddd + 52) / 3060;
long mm = (mi + 2) % 12 + 1;
y = y + (mi + 2) / 12;
long dd = ddd - (mi * 306 + 5) / 10 + 1;
Solar solar = new Solar();
solar.solarYear = (int) y;
solar.solarMonth = (int) mm;
solar.solarDay = (int) dd;
return solar;
}
/**
* 農曆轉公曆
*/
public static Solar LunarToSolar(Lunar lunar) {
int days = lunar_month_days[lunar.lunarYear - lunar_month_days[0]];
int leap = GetBitInt(days, 4, 13);
int offset = 0;
int loopend = leap;
if (!lunar.isleap) {
if (lunar.lunarMonth <= leap || leap == 0) {
loopend = lunar.lunarMonth - 1;
} else {
loopend = lunar.lunarMonth;
}
}
for (int i = 0; i < loopend; i++) {
offset += GetBitInt(days, 1, 12 - i) == 1 ? 30 : 29;
}
offset += lunar.lunarDay;
int solar11 = solar_1_1[lunar.lunarYear - solar_1_1[0]];
int y = GetBitInt(solar11, 12, 9);
int m = GetBitInt(solar11, 4, 5);
int d = GetBitInt(solar11, 5, 0);
return SolarFromInt(SolarToInt(y, m, d) + offset - 1);
}
/**
* 根據時間轉農曆
* @param time
* @return
*/
public static Lunar TimeToLunar(Date time){
Solar solar = new Solar();
solar.solarYear = DateHelper.getYear(time);
solar.solarMonth = DateHelper.getMonth(time);
solar.solarDay = DateHelper.getDay(time);
return SolarToLunar(solar);
}
/**
* 公曆轉農曆
*/
public static Lunar SolarToLunar(Solar solar) {
Lunar lunar = new Lunar();
int index = solar.solarYear - solar_1_1[0];
int data = (solar.solarYear << 9) | (solar.solarMonth << 5) | (solar.solarDay);
int solar11 = 0;
if (solar_1_1[index] > data) {
index--;
}
solar11 = solar_1_1[index];
int y = GetBitInt(solar11, 12, 9);
int m = GetBitInt(solar11, 4, 5);
int d = GetBitInt(solar11, 5, 0);
long offset = SolarToInt(solar.solarYear, solar.solarMonth, solar.solarDay) - SolarToInt(y, m, d);
int days = lunar_month_days[index];
int leap = GetBitInt(days, 4, 13);
int lunarY = index + solar_1_1[0];
int lunarM = 1;
int lunarD = 1;
offset += 1;
for (int i = 0; i < 13; i++) {
int dm = GetBitInt(days, 1, 12 - i) == 1 ? 30 : 29;
if (offset > dm) {
lunarM++;
offset -= dm;
} else {
break;
}
}
lunarD = (int) (offset);
lunar.lunarYear = lunarY;
lunar.lunarMonth = lunarM;
lunar.isleap = false;
if (leap != 0 && lunarM > leap) {
lunar.lunarMonth = lunarM - 1;
if (lunarM == leap + 1) {
lunar.isleap = true;
}
}
lunar.lunarDay = lunarD;
return lunar;
}
}
MD5Helper
package com.sd.lottery.common.utils;
import java.security.MessageDigest;
public class MD5Helper {
public static String encrypt(String str) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(str.getBytes("UTF8"));
byte s[] = m.digest();
StringBuilder result = new StringBuilder();
for (byte value : s) {
result.append(Integer.toHexString((0x000000FF & value) | 0xFFFFFF00)
.substring(6));
}
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static String MD5(String content) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = content.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
}
/**
* 獲取當前客戶端IP
* @param request
* @return
*/
NetHelper
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.sd.lottery.common.enums.ResponseCode;
import com.sd.lottery.common.model.ResponseModel;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NetHelper {
/**
* 獲取當前客戶端IP
* @param request
* @return
*/
public static String getIp(HttpServletRequest request){
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if(ip.contains(",")){
String[] ips = ip.split(",");
ip = ips[0];
}
return ip;
}
/**
* 獲取主域名
* @param host
* @return
*/
public static String getMainDomain(String host){
String regStr="[0-9a-zA-Z]+((\\.com)|(\\.cn)|(\\.org)|(\\.net)|(\\.edu)|(\\.com.cn)|(\\.xyz)|(\\.xin)|(\\.club)|(\\.shop)|(\\.site)|(\\.wang)" +
"|(\\.top)|(\\.win)|(\\.online)|(\\.tech)|(\\.store)|(\\.bid)|(\\.cc)|(\\.ren)|(\\.lol)|(\\.pro)|(\\.red)|(\\.kim)|(\\.space)|(\\.link)|(\\.click)|(\\.news)|(\\.news)|(\\.ltd)|(\\.website)" +
"|(\\.biz)|(\\.help)|(\\.mom)|(\\.work)|(\\.date)|(\\.loan)|(\\.mobi)|(\\.live)|(\\.studio)|(\\.info)|(\\.pics)|(\\.photo)|(\\.trade)|(\\.vc)|(\\.party)|(\\.game)|(\\.rocks)|(\\.band)" +
"|(\\.gift)|(\\.wiki)|(\\.design)|(\\.software)|(\\.social)|(\\.lawyer)|(\\.engineer)|(\\.org)|(\\.net.cn)|(\\.org.cn)|(\\.gov.cn)|(\\.name)|(\\.tv)|(\\.me)|(\\.asia)|(\\.co)|(\\.press)|(\\.video)|(\\.market)" +
"|(\\.games)|(\\.science)|(\\.中國)|(\\.公司)|(\\.網絡)|(\\.pub)" +
"|(\\.la)|(\\.auction)|(\\.email)|(\\.sex)|(\\.sexy)|(\\.one)|(\\.host)|(\\.rent)|(\\.fans)|(\\.cn.com)|(\\.life)|(\\.cool)|(\\.run)" +
"|(\\.gold)|(\\.rip)|(\\.ceo)|(\\.sale)|(\\.hk)|(\\.io)|(\\.gg)|(\\.tm)|(\\.ph)|(\\.com.hk)|(\\.gs)|(\\.us)|(\\.vip))";
Pattern p = Pattern.compile(regStr);
Matcher m = p.matcher(host);
m.find();
host = m.group();
return host;
}
/**
* 獲取主機
* @param request
* @return
*/
public static String getHost(HttpServletRequest request) {
return request.getHeader("host");
}
public static JSONObject getRequestParam(HttpServletRequest request){
JSONObject jsonObject = null;
try {
BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 獲取網關轉發後真實host地址
* @param request
* @return
*/
public static String getHostForwarded(HttpServletRequest request){
String host = request.getHeader("x-forwarded-host");
if(host == null){
host = getHost(request);
}
return host;
}
/**
* 獲取網關轉發後真實ip地址
* @param request
* @return
*/
public static String getIPForwarded(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
return ip;
}
/**
* 獲取網關轉發後真實proto 協議
* @param request
* @return
*/
public static String getProtoForwarded(HttpServletRequest request){
String proto = request.getHeader("x-forwarded-proto");
if(proto == null){
proto = request.getScheme();
}
return proto;
}
/**
* POST JSON
* @param url url
* @param jsonObj 數據
* @return
*/
public static ResponseModel<ResponseCode, String> postJson(String url, Object jsonObj){
ResponseModel<ResponseCode, String> responseModel = new ResponseModel<>();
if(Strings.isNullOrEmpty(url)){
responseModel.setCode(ResponseCode.FAILED);
responseModel.setMsg("url爲空");
return responseModel;
}
try {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);
requestFactory.setReadTimeout(10000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
//創建請求頭
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Object> entity = new HttpEntity<>(jsonObj, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
String res = responseEntity.getBody();
responseModel.setData(res);
responseModel.setMsg(String.format("status:%s", responseEntity.getStatusCode()));
}
catch (Exception ex){
ex.printStackTrace();
responseModel.setData(ex.getMessage());
responseModel.setMsg("http請求出錯");
responseModel.setCode(ResponseCode.FAILED);
}
return responseModel;
}
public static String send(String url, Object data) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String encoding = "UTF-8";
String body = "";
//採用繞過驗證的方式處理https請求
SSLContext sslcontext = createIgnoreVerifySSL();
// 設置協議http和https對應的處理socket鏈接工廠的對象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//創建自定義的httpclient對象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//創建get方式請求對象
HttpGet httpGet = new HttpGet(url);
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = new StringEntity(JSONObject.toJSONString(data),"utf-8");//解決中文亂碼問題
dataEntity.setContentEncoding("UTF-8");
dataEntity.setContentType("application/json");
httpPost.setEntity(dataEntity);
//設置header信息
//指定報文頭【Content-type】、【User-Agent】
httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//執行請求操作,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//獲取結果實體
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}
/**
* 繞過驗證
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 實現一個X509TrustManager接口,用於繞過驗證,不用修改裏面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
}
NumberHelper
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class NumberHelper {
/*
*是否數字
*/
public final static boolean isNumeric(String s) {
if (s != null && !"".equals(s.trim()))
return s.matches("^[0-9]*$");
else
return false;
}
/**
* 生成整形隨機數
*
* @param min
* @param max
*/
public static int IntRandom(int min, int max) {
max += 1;
int result = min + ((int) (new Random().nextFloat() * (max - min)));
return result;
}
/**
* 字符串轉換成INT
*
* @param str
* @param defaultVal
* @return
*/
public static Integer StringToInt(String str, Integer defaultVal) {
Double d = StringToDouble(str, 0d);
if (d.equals(0d)) {
return defaultVal;
}
return d.intValue();
}
/**
* 字符串轉長整形
*
* @param str
* @param defaultVal
* @return
*/
public static Long StringToLong(String str, Long defaultVal) {
Double d = StringToDouble(str, 0d);
if (d.equals(0d)) {
return defaultVal;
}
return d.longValue();
}
/**
* 格式化DO
*
* @param val
* @param decimalN
* @return
*/
public static Double FormatDouble(Double val, int decimalN) {
if (val == null) {
return 0d;
}
BigDecimal b = new BigDecimal(Double.toString(val));
return b.setScale(decimalN, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 計算組合數 從n中取t的組合有多少種
*
* @param n
* @param t
* @return
*/
public static int ZhuHeCount(int n, int t) {
List<Integer> r = new ArrayList<Integer>();
List<List<Integer>> f = new ArrayList<List<Integer>>();
int i = 0, u = 0;
for (i = t - 1, u = 0; i >= 0; i--, u++) {
r.add(u, n - i - 1);
}
for (f.add(r); r.get(t - 1) >= t; ) {
r.set(0, r.get(0) - 1);
if (r.get(0) >= 0) {
//f.push(r.concat());
f.add(r);
} else {
for (i = 1; i < t; i++) {
if (r.get(i) > i) {
for (r.set(i, r.get(i) - 1), u = i - 1; u >= 0; u--) {
r.set(u, r.get(u + 1) - 1);
//r[u] = r[u + 1] - 1;
}
;
f.add(r);
//f.push(r.concat());
break;
}
}
}
}
return f.size();
}
public static Double StringToDouble(String odds, double d) {
if (odds == null) {
return d;
}
try {
return Double.parseDouble(odds);
} catch (Exception ex) {
return d;
}
}
public static Float StringToFloat(String odds, float f) {
if (odds == null) {
return f;
}
try {
return Float.parseFloat(odds);
} catch (Exception ex) {
return f;
}
}
public static Integer getMin(List<Integer> list) {
Integer val = null;
if (list == null) {
return val;
}
for (Integer p : list) {
if (val == null || val > p) {
val = p;
}
}
return val;
}
public static Integer getMax(List<Integer> list) {
Integer val = null;
if (list == null) {
return val;
}
for (Integer p : list) {
if (val == null || val < p) {
val = p;
}
}
return val;
}
/**
* 最大相同次數
*
* @param list
* @return
*/
public static Integer maxDiff(List<Integer> list) {
if (list == null) {
return 0;
}
int max = 0;
for (Integer item : list) {
int n = 0;
for (Integer compareItem : list) {
if (item.equals(compareItem)) {
n += 1;
}
}
if (n > max) {
max = n;
}
}
return max;
}
public static String addZero(String drawCode) {
List<String> balls = new ArrayList<>();
String[] numbers = drawCode.split(",");
for (String number : numbers) {
// 0 代表前面補充0
// 4 代表長度爲4
// d 代表參數爲正數型
String val = String.format("%02d", Integer.parseInt(number));
balls.add(val);
}
return String.join(",", balls);
}
}
StringHelper
import java.security.MessageDigest;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class StringHelper {
/**
* 格式化str字段
* @param str
* @return
*/
public static String formatLike(String str){
return MessageFormat.format("%{0}%", str);
}
/**
* 生成GUID
* @return
*/
public static String guid(){
String result = UUID.randomUUID().toString().replace("-", "");
return result;
}
public static String MD5(String content) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = content.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 左邊補充字符已達到指定長度
* @param val
* @param padChar
* @param len
* @return
*/
public static String PadLeft(String val, String padChar, Integer len){
if(val.length() > len){
return val;
}
String str ="";
for(int i = 0; i< len ; i++){
str += padChar;
}
String result = str.substring(0, len - val.length()) + val;
return result;
}
/**
* @作者
* @功能 String右對齊
*/
public static String padRight(String src, int len, char ch) {
int diff = len - src.length();
if (diff <= 0) {
return src;
}
char[] charr = new char[len];
System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());
for (int i = 0; i < diff; i++) {
charr[i] = ch;
}
return new String(charr);
}
public static <T> String ListToString(List<T> list, char separator){
if(list == null){
return null;
}
StringBuilder sb = new StringBuilder();
for(Object item : list){
if(sb.length() > 0){
sb.append(separator);
}
String str = item.toString();
sb.append(str);
}
return sb.toString();
}
/**
* 列表轉字符串
* @param list
* @param separator
* @param minLen 最小長度
* @return
*/
public static String ListToString(List<Integer> list, char separator, Integer minLen){
StringBuilder sb = new StringBuilder();
for(Object item : list){
if(sb.length() > 0){
sb.append(separator);
}
String str = item.toString();
if(minLen != null){
str = PadLeft(item.toString(), "0", minLen);
}
sb.append(str);
}
return sb.toString();
}
public static List<String> StringToStringList(String str, String separator){
List<String> result = new ArrayList<String>();
if(str == null){
return result;
}
String[] array = str.split(separator);
for(String item:array){
result.add(item);
}
return result;
}
/**
* 數組轉字符串
* @param arrays
* @param separator
* @return
*/
public static String ArraysToString(String[] arrays, String separator) {
String str = null;
for(String item : arrays){
if(str == null){
str = item;
}else{
str += separator + item;
}
}
return str;
}
/**
* 字符串,根據分隔符轉換成LIST
* @param str
* @param separator
* @return
*/
public static List<Integer> StringToIntegerList(String str, String separator){
List<Integer> result = new ArrayList<Integer>();
if(str == null){
return result;
}
String[] array = str.split(separator);
for(String item:array){
result.add(NumberHelper.StringToInt(item, 0));
}
return result;
}
}
ResponseModel
import com.alibaba.fastjson.JSONObject;
import com.sd.lottery.common.enums.ResponseCode;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
public class ResponseModel<E, T> implements Serializable {
private static final long serialVersionUID = 2761035997605462938L;
private Long timestamp;
private E code;
private T data;
private String msg;
private Long time;
private Exception exception;
private E businessCode;
private Map result;
private E errorCode;
private String message;
/**
* layui分頁
*/
private Integer count;
....//省去set,get
}
AccountPojo
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 賬號
*/
@Table(name = "kj_account")
public class AccountPojo {
/**
* 自增id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 賬號
*/
private String account;
/**
* 密碼
*/
private String password;
/**
* 姓名
*/
private String name;
/**
* 狀態(1:正常 0:停用)
*/
private Integer state;
//...省去set,get
}
``