修正错误提交

This commit is contained in:
click33 2021-07-17 23:55:21 +08:00
parent 971c2860f0
commit ee80633582
14 changed files with 0 additions and 2117 deletions

View File

@ -1,76 +0,0 @@
package com.pj.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ejlchina.okhttps.OkHttps;
import com.pj.utils.AjaxJson;
import com.pj.utils.SoMap;
import cn.dev33.satoken.stp.StpUtil;
/**
* 登录注册Controller
* @author kong
*/
@RestController
public class ClientAccController {
// 返回当前登录者的账号id, 如果未登录, 返回null
@RequestMapping("/getLoginInfo")
public AjaxJson getLoginInfo() {
Object loginId = StpUtil.getLoginIdDefaultNull();
return AjaxJson.getSuccessData(loginId);
}
// 注销登录
@RequestMapping("/logout")
public AjaxJson logout() {
StpUtil.logout();
return AjaxJson.getSuccess();
}
// 根据code码进行登录
@RequestMapping("/doCodeLogin")
public AjaxJson doCodeLogin(String code) {
System.out.println("------------------ 成功进入请求 ------------------");
// 请求服务提供方接口地址获取 access_token 以及其他信息
// 携带三个关键参数: codeclient_idclient_secret
String str = OkHttps.sync("http://localhost:8001/oauth2/getAccessToken")
.addBodyPara("code", code)
.addBodyPara("client_id", "123123123")
.addBodyPara("client_secret", "aaaa-bbbb-cccc-dddd-eeee")
.post()
.getBody()
.toString();
SoMap so = SoMap.getSoMap().setJsonString(str);
System.out.println("返回结果: " + so);
// code不等于200 代表请求失败
if(so.getInt("code") != 200) {
return AjaxJson.getError(so.getString("msg"));
}
// 根据openid获取其对应的userId
String openid = so.getString("openid");
long userId = getUserIdByOpenid(openid);
// 登录并返回账号信息
StpUtil.login(userId);
return AjaxJson.getSuccessData(userId).set("openid", openid);
}
// ------------ 模拟方法 ------------------
// 模拟方法根据openid获取userId
private long getUserIdByOpenid(String openid) {
// 此方法仅做模拟实际开发要根据具体业务逻辑来获取userId
return 10001;
}
}

View File

@ -1,59 +0,0 @@
package com.pj.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pj.utils.AjaxJson;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
/**
* 全局异常拦截
* <p> @ControllerAdvice 可指定包前缀例如(basePackages = "com.pj.controller.admin")
* @author kong
*
*/
@ControllerAdvice
public class ExceptionHandle {
/** 全局异常拦截 */
@ResponseBody
@ExceptionHandler
public AjaxJson handlerException(Exception e) {
// 打印堆栈以供调试
e.printStackTrace();
// 记录日志信息
AjaxJson aj = null;
// ------------- 判断异常类型提供个性化提示信息
// 如果是未登录异常
if(e instanceof NotLoginException){
aj = AjaxJson.getNotLogin();
}
// 如果是角色异常
else if(e instanceof NotRoleException) {
NotPermissionException ee = (NotPermissionException) e;
aj = AjaxJson.getNotJur("无此角色:" + ee.getCode());
}
// 如果是权限异常
else if(e instanceof NotPermissionException) {
NotPermissionException ee = (NotPermissionException) e;
aj = AjaxJson.getNotJur("无此权限:" + ee.getCode());
}
// 普通异常输出500 + 异常信息
else {
aj = AjaxJson.getError(e.getMessage());
}
// 返回到前台
return aj;
}
}

View File

@ -1,223 +0,0 @@
package com.pj.utils;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* ajax请求返回Json格式数据的封装 <br>
* 所有预留字段<br>
* code=状态码 <br>
* msg=描述信息 <br>
* data=携带对象 <br>
* pageNo=当前页 <br>
* pageSize=页大小 <br>
* startIndex=起始索引 <br>
* dataCount=数据总数 <br>
* pageCount=分页总数 <br>
* <p> 返回范例</p>
* <pre>
{
"code": 200, // 成功时=200, 失败时=500 msg=失败原因
"msg": "ok",
"data": {}
}
</pre>
*/
public class AjaxJson extends LinkedHashMap<String, Object> implements Serializable{
private static final long serialVersionUID = 1L; // 序列化版本号
public static final int CODE_SUCCESS = 200; // 成功状态码
public static final int CODE_ERROR = 500; // 错误状态码
public static final int CODE_WARNING = 501; // 警告状态码
public static final int CODE_NOT_JUR = 403; // 无权限状态码
public static final int CODE_NOT_LOGIN = 401; // 未登录状态码
public static final int CODE_INVALID_REQUEST = 400; // 无效请求状态码
// ============================ 写值取值 ==================================
/** 给code赋值连缀风格 */
public AjaxJson setCode(int code) {
this.put("code", code);
return this;
}
/** 返回code */
public Integer getCode() {
return (Integer)this.get("code");
}
/** 给msg赋值连缀风格 */
public AjaxJson setMsg(String msg) {
this.put("msg", msg);
return this;
}
/** 获取msg */
public String getMsg() {
return (String)this.get("msg");
}
/** 给data赋值连缀风格 */
public AjaxJson setData(Object data) {
this.put("data", data);
return this;
}
/** 获取data */
public String getData() {
return (String)this.get("data");
}
/** 将data还原为指定类型并返回 */
@SuppressWarnings("unchecked")
public <T> T getData(Class<T> cs) {
return (T) this.getData();
}
/** 给dataCount(数据总数)赋值,连缀风格 */
public AjaxJson setDataCount(Long dataCount) {
this.put("dataCount", dataCount);
// 如果提供了数据总数则尝试计算page信息
if(dataCount != null && dataCount >= 0) {
// 如果已有page信息
if(get("pageNo") != null) {
this.initPageInfo();
}
// // 或者是JavaWeb环境
// else if(SoMap.isJavaWeb()) {
// SoMap so = SoMap.getRequestSoMap();
// this.setPageNoAndSize(so.getKeyPageNo(), so.getKeyPageSize());
// this.initPageInfo();
// }
}
return this;
}
/** 获取dataCount(数据总数) */
public String getDataCount() {
return (String)this.get("dataCount");
}
/** 设置pageNo 和 pageSize并计算出startIndex于pageCount */
public AjaxJson setPageNoAndSize(long pageNo, long pageSize) {
this.put("pageNo", pageNo);
this.put("pageSize", pageSize);
return this;
}
/** 根据 pageSize dataCount计算startIndex 与 pageCount */
public AjaxJson initPageInfo() {
long pageNo = (long)this.get("pageNo");
long pageSize = (long)this.get("pageSize");
long dataCount = (long)this.get("dataCount");
this.set("startIndex", (pageNo - 1) * pageSize);
long pc = dataCount / pageSize;
this.set("pageCount", (dataCount % pageSize == 0 ? pc : pc + 1));
return this;
}
/** 写入一个值 自定义key, 连缀风格 */
public AjaxJson set(String key, Object data) {
this.put(key, data);
return this;
}
/** 写入一个Map, 连缀风格 */
public AjaxJson setMap(Map<String, ?> map) {
for (String key : map.keySet()) {
this.put(key, map.get(key));
}
return this;
}
// ============================ 构建 ==================================
public AjaxJson(int code, String msg, Object data, Long dataCount) {
this.setCode(code);
this.setMsg(msg);
this.setData(data);
this.setDataCount(dataCount == null ? -1 : dataCount);
}
/** 返回成功 */
public static AjaxJson getSuccess() {
return new AjaxJson(CODE_SUCCESS, "ok", null, null);
}
public static AjaxJson getSuccess(String msg) {
return new AjaxJson(CODE_SUCCESS, msg, null, null);
}
public static AjaxJson getSuccess(String msg, Object data) {
return new AjaxJson(CODE_SUCCESS, msg, data, null);
}
public static AjaxJson getSuccessData(Object data) {
return new AjaxJson(CODE_SUCCESS, "ok", data, null);
}
/** 返回失败 */
public static AjaxJson getError() {
return new AjaxJson(CODE_ERROR, "error", null, null);
}
public static AjaxJson getError(String msg) {
return new AjaxJson(CODE_ERROR, msg, null, null);
}
/** 返回警告 */
public static AjaxJson getWarning() {
return new AjaxJson(CODE_ERROR, "warning", null, null);
}
public static AjaxJson getWarning(String msg) {
return new AjaxJson(CODE_WARNING, msg, null, null);
}
/** 返回未登录 */
public static AjaxJson getNotLogin() {
return new AjaxJson(CODE_NOT_LOGIN, "未登录,请登录后再次访问", null, null);
}
/** 返回没有权限的 */
public static AjaxJson getNotJur(String msg) {
return new AjaxJson(CODE_NOT_JUR, msg, null, null);
}
/** 返回一个自定义状态码的 */
public static AjaxJson get(int code, String msg){
return new AjaxJson(code, msg, null, null);
}
/** 返回分页和数据的 */
public static AjaxJson getPageData(Long dataCount, Object data){
return new AjaxJson(CODE_SUCCESS, "ok", data, dataCount);
}
/** 返回, 根据受影响行数的(大于0=ok小于0=error) */
public static AjaxJson getByLine(int line){
if(line > 0){
return getSuccess("ok", line);
}
return getError("error").setData(line);
}
/** 返回,根据布尔值来确定最终结果的 (true=okfalse=error) */
public static AjaxJson getByBoolean(boolean b){
return b ? getSuccess("ok") : getError("error");
}
// // 历史版本遗留代码
// public int code; // 状态码
// public String msg; // 描述信息
// public Object data; // 携带对象
// public Long dataCount; // 数据总数用于分页
}

View File

@ -1,127 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>客户端-登录页</title>
<style type="text/css">
*{margin: 0px; padding: 0px;}
.login-box{width: 500px; margin: 50px auto;}
</style>
</head>
<body>
<div class="login-box">
<h2>客户端-登录页</h2> <br>
<div>
当前是否登录: <span class="login-info"></span>
<button onclick="logout()">注销登录</button>
</div>
<br/>
点此按钮开始使用OAuth2.0开放平台快捷登录:
<button onclick="requestOAuth2()">快捷登录</button>
</div>
<script src="https://unpkg.zhimg.com/jquery@3.4.1/dist/jquery.min.js"></script>
<script type="text/javascript">
// 获取登录信息
var currUserId = null;
function getLoginInfo() {
$.ajax({
url: '/getLoginInfo',
data: {},
dataType: 'json',
success: function(res) {
if(res.data == null) {
$(".login-info").html('<b style="color: red;">未登录</b>');
// 如果当前未登录并且此时url中有code参数, 则尝试使用code码进行登录
var code = getParam('code', null);
if(code != null) {
doCodeLogin();
}
} else {
$(".login-info").html('<b style="color: green;">已登录, userId=' + res.data + '</b>');
currUserId = res.data;
}
},
error: function(e, ee, eee) {
console.log('error');
alert(eee);
}
});
}
getLoginInfo();
// 注销登录
function logout() {
$.ajax({
url: '/logout',
dataType: 'json',
success: function(res) {
alert('注销成功');
location.href = "./login.html";
},
error: function(e, ee, eee) {
alert(eee);
}
});
}
// 请求OAuth2授权
function requestOAuth2() {
// 如果当前已经登录,则必须先退出
if(currUserId != null) {
alert('当前已经登录, 请先注销');
return;
}
// 拼接地址
var url = "http://localhost:8001/oauth2/authorize" +
"?client_id=123123123" + // 应用id
"&scope=userinfo" + // 授权范围
// "&redirect_uri=" + encodeURIComponent(location.href) // 重定向地址
"&redirect_uri=" + encodeURIComponent("http://localhost:8002/login.html") // 重定向地址
"&response_type=code" + // 返回格式
"&state=123456789"; // 授权范围
console.log(url);
location.href = url;
}
// 使用code进行 (从url中获取code码进行登录)
function doCodeLogin() {
var code = getParam('code');
$.ajax({
url: '/doCodeLogin',
data: {
code: code
},
dataType: 'json',
success: function(res) {
if(res.code == 200) {
alert('OAuth2登录成功');
getLoginInfo(); // 刷新user信息
} else {
alert("登录失败:" + res.msg);
}
},
error: function(e, ee, eee) {
alert(eee);
}
});
}
// 从url中查询到指定名称的参数值
function getParam(name, defaultValue){
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == name){return pair[1];}
}
return(defaultValue == undefined ? null : defaultValue);
}
</script>
</body>
</html>

View File

@ -1,59 +0,0 @@
package com.pj.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pj.utils.AjaxJson;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
/**
* 全局异常拦截
* <p> @ControllerAdvice 可指定包前缀例如(basePackages = "com.pj.controller.admin")
* @author kong
*
*/
@ControllerAdvice
public class ExceptionHandle {
/** 全局异常拦截 */
@ResponseBody
@ExceptionHandler
public AjaxJson handlerException(Exception e) {
// 打印堆栈以供调试
e.printStackTrace();
// 记录日志信息
AjaxJson aj = null;
// ------------- 判断异常类型提供个性化提示信息
// 如果是未登录异常
if(e instanceof NotLoginException){
aj = AjaxJson.getNotLogin();
}
// 如果是角色异常
else if(e instanceof NotRoleException) {
NotPermissionException ee = (NotPermissionException) e;
aj = AjaxJson.getNotJur("无此角色:" + ee.getCode());
}
// 如果是权限异常
else if(e instanceof NotPermissionException) {
NotPermissionException ee = (NotPermissionException) e;
aj = AjaxJson.getNotJur("无此权限:" + ee.getCode());
}
// 普通异常输出500 + 异常信息
else {
aj = AjaxJson.getError(e.getMessage());
}
// 返回到前台
return aj;
}
}

View File

@ -1,311 +0,0 @@
package com.pj.controller;
import java.io.IOException;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pj.utils.AjaxJson;
import com.pj.utils.SoMap;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.oauth2.SaOAuth2Manager;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Consts.Param;
import cn.dev33.satoken.oauth2.model.AccessTokenModel;
import cn.dev33.satoken.oauth2.model.ClientTokenModel;
import cn.dev33.satoken.oauth2.model.CodeModel;
import cn.dev33.satoken.oauth2.model.RequestAuthModel;
import cn.dev33.satoken.spring.SpringMVCUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
@RestController
//@RequestMapping("/oauth2/")
public class OAuth2Controller {
// OAuth-Server端处理所有OAuth相关请求
@RequestMapping("/oauth2/authorize")
public Object request() {
System.out.println("------------进入请求:" + SaHolder.getRequest().getUrl());
return SaOAuth2Handle.authorize();
}
// OAuth-Server端处理所有OAuth相关请求
@RequestMapping("/oauth2/token")
public Object token() {
System.out.println("------------进入请求:" + SaHolder.getRequest().getUrl());
return SaOAuth2Handle.token();
}
// OAuth-Server端刷新Token
@RequestMapping("/oauth2/ref")
public Object ref(String refresh_token) {
System.out.println("------------进入请求:" + SaHolder.getRequest().getUrl());
return SaResult.data(
SaOAuth2Util.saOAuth2Template.refreshAccessToken(refresh_token).toLineMap()
);
}
// 隐藏式
@RequestMapping("/oauth2/yc")
public Object yc() {
SaRequest req = SaHolder.getRequest();
SaResponse res = SaHolder.getResponse();
SaOAuth2Config cfg = SaOAuth2Manager.getConfig();
// ------------- 以下都是雷同代码
// 1构建请求Model TODO 貌似这个RequestAuthModel对象也可以省略掉
RequestAuthModel ra = SaOAuth2Util.generateRequestAuth(req, StpUtil.getLoginId());
// 2如果尚未登录, 则先去登录
if(StpUtil.isLogin() == false) {
return cfg.notLoginView.get();
}
// 3判断重定向域名的格式是否合法
boolean isRigh = SaOAuth2Util.isRightUrl(ra.clientId, ra.redirectUri);
if(isRigh == false) {
return cfg.invalidUrlView.apply(ra.clientId, ra.redirectUri);
}
// 4判断此次申请的Scope该Client是否已经签约
boolean isContract = SaOAuth2Util.isContract(ra.clientId, ra.scope);
if(isContract == false) {
return cfg.invalidScopeView.apply(ra.clientId, ra.scope);
}
// 5判断此次申请的Scope该用户是否已经授权过了
boolean isGrant = SaOAuth2Util.isGrant(StpUtil.getLoginId(), ra.clientId, ra.scope);
if(isGrant == false) {
// 如果尚未授权则转到授权页面开始授权操作
return cfg.confirmView.apply(ra.clientId, ra.scope);
}
// ------------- 以上都是雷同代码
// 6开始重定向授权下放code
AccessTokenModel at = SaOAuth2Util.generateAccessToken(ra);
String redirectUri = SaOAuth2Util.buildRedirectUri2(ra.redirectUri, at.accessToken, ra.state);
return res.redirect(redirectUri);
}
// 密码式
@RequestMapping("/oauth2/password")
public Object password() {
SaRequest req = SaHolder.getRequest();
SaResponse res = SaHolder.getResponse();
SaOAuth2Config cfg = SaOAuth2Manager.getConfig();
// 1构建请求Model TODO 貌似这个RequestAuthModel对象也可以省略掉
// RequestAuthModel ra = SaOAuth2Util.generateRequestAuth(req, StpUtil.getLoginId());
String username = req.getParamNotNull("username");
String password = req.getParamNotNull("password");
String clientId = req.getParamNotNull("client_id");
Object retObj = cfg.doLoginHandle.apply(username, password);
if(StpUtil.isLogin() == false) {
return retObj;
}
RequestAuthModel ra = new RequestAuthModel();
ra.clientId = req.getParamNotNull(Param.client_id);
// ra.responseType = req.getParamNotNull(Param.response_type);
// ra.redirectUri = req.getParamNotNull(Param.redirect_uri);
// ra.state = req.getParam(Param.state);
ra.scope = "";// 默认应该为空还是内个呢 SaOAuth2Util.saOAuth2Template.getClientScopeList(clientId);
ra.loginId = StpUtil.getLoginId();
// 6开始重定向授权下放code TODO 这里需要也生成 ref_token
AccessTokenModel at = SaOAuth2Util.generateAccessToken(ra);
//
return SaResult.data(at);
}
// 凭证式
@RequestMapping("/oauth2/appat")
public Object appat() {
SaRequest req = SaHolder.getRequest();
SaResponse res = SaHolder.getResponse();
SaOAuth2Config cfg = SaOAuth2Manager.getConfig();
String clientId = req.getParamNotNull(Param.client_id);
String scope = req.getParam(Param.scope);
ClientTokenModel ct = SaOAuth2Util.generateClientToken(clientId, scope);
//
return SaResult.data(ct.toLineMap());
}
@Autowired
public void setSaOAuth2Config(SaOAuth2Config saOAuth2Config) {
System.out.println("-----------123 " + saOAuth2Config);
saOAuth2Config.
// 未登录的视图
setNotLoginView(()->{
// return "您暂未登录";
HttpServletRequest request = SpringMVCUtil.getRequest();
HttpServletResponse response = SpringMVCUtil.getResponse();
response.setContentType("text/html");
try {
request.getRequestDispatcher("/login.html").forward(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
return null;
}).
// 未登录的视图
setConfirmView((clientId, scope)->{
return "本次操作需要授权";
})
// 登录处理函数
.setDoLoginHandle((name, pwd) -> {
if("sa".equals(name) && "123456".equals(pwd)) {
StpUtil.login(10001);
return AjaxJson.getSuccess();
}
return SaResult.error();
})
;
}
// 获取授权码
@RequestMapping("/authorize")
public AjaxJson authorize(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 获取参数
System.out.println("------------------ 成功进入请求 ------------------");
// 如果暂未登录则先跳转到登录页 (转发)
if(StpUtil.isLogin() == false) {
response.setContentType("text/html");
request.getRequestDispatcher("/login.html").forward(request, response);
return AjaxJson.getSuccess();
}
// 构建Model
RequestAuthModel authModel = new RequestAuthModel()
.setClientId(request.getParameter("client_id")) // 应用id
.setScope(request.getParameter("scope")) // 授权类型
.setLoginId(StpUtil.getLoginIdAsLong()) // 当前登录账号id
.setRedirectUri(URLDecoder.decode(request.getParameter("redirect_uri"), "utf-8")) // 重定向地址
.setResponseType(request.getParameter("response_type")) // 返回类型
.setState(request.getParameter("state")) // 状态值
.checkModel(); // 校验参数完整性
// 生成授权码Model
CodeModel codeModel = SaOAuth2Util.generateCode(authModel);
// 打印调试
System.out.println("应用id=" + authModel.getClientId() + "请求授权,授权类型=" + authModel.getResponseType());
System.out.println("重定向地址:" + authModel.getRedirectUri());
// System.out.println("拼接完成的redirect_uri: " + codeModel.getRedirectUri());
// System.out.println("如果用户拒绝授权,则重定向至: " + codeModel.getRejectUri());
// 如果请求的权限用户已经确认直接开始重定向授权
// if(codeModel.getIsConfirm() == true) {
// response.sendRedirect(codeModel.getRedirectUri());
// } else {
// // 如果请求的权限用户尚未确认则进入到确定页
// request.setAttribute("name", "sdd");
// response.sendRedirect("/auth.html?code=" + codeModel.getCode());
// }
return AjaxJson.getSuccess();
}
// 根据授权码获取应用信息
@RequestMapping("/getCodeInfo")
public AjaxJson getCodeInfo(String code) {
// 获取codeModel
CodeModel codeModel = SaOAuth2Util.getCode(code);
System.out.println(code);
System.out.println(codeModel);
// 返回
return AjaxJson.getSuccessData(codeModel);
}
// 确认授权一个授权码
@RequestMapping("/confirm")
public AjaxJson confirm(String code) {
// 获取codeModel
CodeModel codeModel = SaOAuth2Util.getCode(code);
if(codeModel == null) {
return AjaxJson.getError("无效code码");
}
// 此处的判断是为了保证当前账号id 创建授权码的账号id一致 才可以进行确认
if(codeModel.getLoginId().toString().equals(StpUtil.getLoginIdAsString()) == false) {
return AjaxJson.getError("暂无权限");
}
// 进行确认
// SaOAuth2Util.confirmCode(code);
// 返回ok
return AjaxJson.getSuccess();
}
// 根据授权码等参数获取 access_token 等信息
@RequestMapping("/getAccessToken")
public SoMap getAccessToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取参数
System.out.println("------------------ 成功进入请求 ------------------");
String code = request.getParameter("code"); // code码
String clientId = request.getParameter("client_id"); // 应用id
String clientSecret = request.getParameter("client_secret"); // 应用秘钥
// 校验参数
// SaOAuth2Util.checkCodeIdSecret(code, clientId, clientSecret);
// 生成
CodeModel codeModel = SaOAuth2Util.getCode(code);
AccessTokenModel tokenModel = SaOAuth2Util.generateAccessToken(code);
// 生成AccessToken之后将授权码立即销毁
SaOAuth2Util.deleteCode(code);
// 返回
return SoMap.getSoMap()
.setModel(tokenModel)
.set("code", 200)
.set("msg", "ok");
}
// 根据access_token返回指定的资源
@RequestMapping("/getResources")
public SoMap getResources(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取信息
String accessToken = request.getParameter("access_token");
Object LoginId = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
System.out.println("LoginId=" + LoginId);
// 根据LoginId获取相应信息...
// 此处仅做模拟
return new SoMap()
.set("nickname", "shengzhang")
.set("acatar", "xxx")
.set("sex", 1);
}
}

View File

@ -1,28 +0,0 @@
package com.pj.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pj.utils.AjaxJson;
import cn.dev33.satoken.stp.StpUtil;
/**
* 服务端登录Controller
* @author kong
*/
@RestController
public class ServerAccController {
// 登录方法
@RequestMapping("/doLogin")
public AjaxJson test(String username, String password) {
System.out.println("------------------ 成功进入请求 ------------------");
if("test".equals(username) && "test".equals(password)) {
StpUtil.login(10001);
return AjaxJson.getSuccess();
}
return AjaxJson.getError();
}
}

View File

@ -1,29 +0,0 @@
package com.pj.oauth2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
/**
* 注册Bean
*
* @author kong
*
*/
@Component
public class SaOAuth2BeanRegister {
/**
* 获取OAuth2配置Bean
*
* @return 配置对象
*/
@Bean
@ConfigurationProperties(prefix = "sa-token.oauth2")
public SaOAuth2Config getSaOAuth2Config() {
return new SaOAuth2Config();
}
}

View File

@ -1,40 +0,0 @@
package com.pj.oauth2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.oauth2.SaOAuth2Manager;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Template;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
/**
* 利用Spring完成自动装配
*
* @author kong
*
*/
@Component
public class SaOAuth2SpringAutowired {
/**
* 注入OAuth2配置Bean
*
* @param saOAuth2Config 配置对象
*/
@Autowired
public void setSaOAuth2Config(SaOAuth2Config saOAuth2Config) {
SaOAuth2Manager.setConfig(saOAuth2Config);
}
/**
* 注入OAuth2接口Bean
*
* @param saOAuth2Interface OAuth2接口Bean
*/
@Autowired(required = false)
public void setSaOAuth2Interface(SaOAuth2Template saOAuth2Interface) {
SaOAuth2Util.saOAuth2Template = saOAuth2Interface;
}
}

View File

@ -1,223 +0,0 @@
package com.pj.utils;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* ajax请求返回Json格式数据的封装 <br>
* 所有预留字段<br>
* code=状态码 <br>
* msg=描述信息 <br>
* data=携带对象 <br>
* pageNo=当前页 <br>
* pageSize=页大小 <br>
* startIndex=起始索引 <br>
* dataCount=数据总数 <br>
* pageCount=分页总数 <br>
* <p> 返回范例</p>
* <pre>
{
"code": 200, // 成功时=200, 失败时=500 msg=失败原因
"msg": "ok",
"data": {}
}
</pre>
*/
public class AjaxJson extends LinkedHashMap<String, Object> implements Serializable{
private static final long serialVersionUID = 1L; // 序列化版本号
public static final int CODE_SUCCESS = 200; // 成功状态码
public static final int CODE_ERROR = 500; // 错误状态码
public static final int CODE_WARNING = 501; // 警告状态码
public static final int CODE_NOT_JUR = 403; // 无权限状态码
public static final int CODE_NOT_LOGIN = 401; // 未登录状态码
public static final int CODE_INVALID_REQUEST = 400; // 无效请求状态码
// ============================ 写值取值 ==================================
/** 给code赋值连缀风格 */
public AjaxJson setCode(int code) {
this.put("code", code);
return this;
}
/** 返回code */
public Integer getCode() {
return (Integer)this.get("code");
}
/** 给msg赋值连缀风格 */
public AjaxJson setMsg(String msg) {
this.put("msg", msg);
return this;
}
/** 获取msg */
public String getMsg() {
return (String)this.get("msg");
}
/** 给data赋值连缀风格 */
public AjaxJson setData(Object data) {
this.put("data", data);
return this;
}
/** 获取data */
public String getData() {
return (String)this.get("data");
}
/** 将data还原为指定类型并返回 */
@SuppressWarnings("unchecked")
public <T> T getData(Class<T> cs) {
return (T) this.getData();
}
/** 给dataCount(数据总数)赋值,连缀风格 */
public AjaxJson setDataCount(Long dataCount) {
this.put("dataCount", dataCount);
// 如果提供了数据总数则尝试计算page信息
if(dataCount != null && dataCount >= 0) {
// 如果已有page信息
if(get("pageNo") != null) {
this.initPageInfo();
}
// // 或者是JavaWeb环境
// else if(SoMap.isJavaWeb()) {
// SoMap so = SoMap.getRequestSoMap();
// this.setPageNoAndSize(so.getKeyPageNo(), so.getKeyPageSize());
// this.initPageInfo();
// }
}
return this;
}
/** 获取dataCount(数据总数) */
public String getDataCount() {
return (String)this.get("dataCount");
}
/** 设置pageNo 和 pageSize并计算出startIndex于pageCount */
public AjaxJson setPageNoAndSize(long pageNo, long pageSize) {
this.put("pageNo", pageNo);
this.put("pageSize", pageSize);
return this;
}
/** 根据 pageSize dataCount计算startIndex 与 pageCount */
public AjaxJson initPageInfo() {
long pageNo = (long)this.get("pageNo");
long pageSize = (long)this.get("pageSize");
long dataCount = (long)this.get("dataCount");
this.set("startIndex", (pageNo - 1) * pageSize);
long pc = dataCount / pageSize;
this.set("pageCount", (dataCount % pageSize == 0 ? pc : pc + 1));
return this;
}
/** 写入一个值 自定义key, 连缀风格 */
public AjaxJson set(String key, Object data) {
this.put(key, data);
return this;
}
/** 写入一个Map, 连缀风格 */
public AjaxJson setMap(Map<String, ?> map) {
for (String key : map.keySet()) {
this.put(key, map.get(key));
}
return this;
}
// ============================ 构建 ==================================
public AjaxJson(int code, String msg, Object data, Long dataCount) {
this.setCode(code);
this.setMsg(msg);
this.setData(data);
this.setDataCount(dataCount == null ? -1 : dataCount);
}
/** 返回成功 */
public static AjaxJson getSuccess() {
return new AjaxJson(CODE_SUCCESS, "ok", null, null);
}
public static AjaxJson getSuccess(String msg) {
return new AjaxJson(CODE_SUCCESS, msg, null, null);
}
public static AjaxJson getSuccess(String msg, Object data) {
return new AjaxJson(CODE_SUCCESS, msg, data, null);
}
public static AjaxJson getSuccessData(Object data) {
return new AjaxJson(CODE_SUCCESS, "ok", data, null);
}
/** 返回失败 */
public static AjaxJson getError() {
return new AjaxJson(CODE_ERROR, "error", null, null);
}
public static AjaxJson getError(String msg) {
return new AjaxJson(CODE_ERROR, msg, null, null);
}
/** 返回警告 */
public static AjaxJson getWarning() {
return new AjaxJson(CODE_ERROR, "warning", null, null);
}
public static AjaxJson getWarning(String msg) {
return new AjaxJson(CODE_WARNING, msg, null, null);
}
/** 返回未登录 */
public static AjaxJson getNotLogin() {
return new AjaxJson(CODE_NOT_LOGIN, "未登录,请登录后再次访问", null, null);
}
/** 返回没有权限的 */
public static AjaxJson getNotJur(String msg) {
return new AjaxJson(CODE_NOT_JUR, msg, null, null);
}
/** 返回一个自定义状态码的 */
public static AjaxJson get(int code, String msg){
return new AjaxJson(code, msg, null, null);
}
/** 返回分页和数据的 */
public static AjaxJson getPageData(Long dataCount, Object data){
return new AjaxJson(CODE_SUCCESS, "ok", data, dataCount);
}
/** 返回, 根据受影响行数的(大于0=ok小于0=error) */
public static AjaxJson getByLine(int line){
if(line > 0){
return getSuccess("ok", line);
}
return getError("error").setData(line);
}
/** 返回,根据布尔值来确定最终结果的 (true=okfalse=error) */
public static AjaxJson getByBoolean(boolean b){
return b ? getSuccess("ok") : getError("error");
}
// // 历史版本遗留代码
// public int code; // 状态码
// public String msg; // 描述信息
// public Object data; // 携带对象
// public Long dataCount; // 数据总数用于分页
}

View File

@ -1,723 +0,0 @@
package com.pj.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Map< String, Object> 是最常用的一种Map类型但是它写着麻烦
* <p>所以特封装此类继承Map进行一些扩展可以让Map更灵活使用
* <p>最新2020-12-10 新增部分构造方法
* @author kong
*/
public class SoMap extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
public SoMap() {
}
/** 以下元素会在isNull函数中被判定为Null */
public static final Object[] NULL_ELEMENT_ARRAY = {null, ""};
public static final List<Object> NULL_ELEMENT_LIST;
static {
NULL_ELEMENT_LIST = Arrays.asList(NULL_ELEMENT_ARRAY);
}
// ============================= 读值 =============================
/** 获取一个值 */
@Override
public Object get(Object key) {
if("this".equals(key)) {
return this;
}
return super.get(key);
}
/** 如果为空,则返回默认值 */
public Object get(Object key, Object defaultValue) {
Object value = get(key);
if(valueIsNull(value)) {
return defaultValue;
}
return value;
}
/** 转为String并返回 */
public String getString(String key) {
Object value = get(key);
if(value == null) {
return null;
}
return String.valueOf(value);
}
/** 如果为空,则返回默认值 */
public String getString(String key, String defaultValue) {
Object value = get(key);
if(valueIsNull(value)) {
return defaultValue;
}
return String.valueOf(value);
}
/** 转为int并返回 */
public int getInt(String key) {
Object value = get(key);
if(valueIsNull(value)) {
return 0;
}
return Integer.valueOf(String.valueOf(value));
}
/** 转为int并返回同时指定默认值 */
public int getInt(String key, int defaultValue) {
Object value = get(key);
if(valueIsNull(value)) {
return defaultValue;
}
return Integer.valueOf(String.valueOf(value));
}
/** 转为long并返回 */
public long getLong(String key) {
Object value = get(key);
if(valueIsNull(value)) {
return 0;
}
return Long.valueOf(String.valueOf(value));
}
/** 转为double并返回 */
public double getDouble(String key) {
Object value = get(key);
if(valueIsNull(value)) {
return 0.0;
}
return Double.valueOf(String.valueOf(value));
}
/** 转为boolean并返回 */
public boolean getBoolean(String key) {
Object value = get(key);
if(valueIsNull(value)) {
return false;
}
return Boolean.valueOf(String.valueOf(value));
}
/** 转为Date并返回根据自定义格式 */
public Date getDateByFormat(String key, String format) {
try {
return new SimpleDateFormat(format).parse(getString(key));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** 转为Date并返回根据格式 yyyy-MM-dd */
public Date getDate(String key) {
return getDateByFormat(key, "yyyy-MM-dd");
}
/** 转为Date并返回根据格式 yyyy-MM-dd HH:mm:ss */
public Date getDateTime(String key) {
return getDateByFormat(key, "yyyy-MM-dd HH:mm:ss");
}
/** 获取集合(必须原先就是个集合,否则会创建个新集合并返回) */
@SuppressWarnings("unchecked")
public List<Object> getList(String key) {
Object value = get(key);
List<Object> list = null;
if(value == null || value.equals("")) {
list = new ArrayList<Object>();
}
else if(value instanceof List) {
list = (List<Object>)value;
} else {
list = new ArrayList<Object>();
list.add(value);
}
return list;
}
/** 获取集合 (指定泛型类型) */
public <T> List<T> getList(String key, Class<T> cs) {
List<Object> list = getList(key);
List<T> list2 = new ArrayList<T>();
for (Object obj : list) {
T objC = getValueByClass(obj, cs);
list2.add(objC);
}
return list2;
}
/** 获取集合(逗号分隔式)(指定类型) */
public <T> List<T> getListByComma(String key, Class<T> cs) {
String listStr = getString(key);
if(listStr == null || listStr.equals("")) {
return new ArrayList<>();
}
// 开始转化
String [] arr = listStr.split(",");
List<T> list = new ArrayList<T>();
for (String str : arr) {
if(cs == int.class || cs == Integer.class || cs == long.class || cs == Long.class) {
str = str.trim();
}
T objC = getValueByClass(str, cs);
list.add(objC);
}
return list;
}
/** 根据指定类型从map中取值返回实体对象 */
public <T> T getModel(Class<T> cs) {
try {
return getModelByObject(cs.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** 从map中取值塞到一个对象中 */
public <T> T getModelByObject(T obj) {
// 获取类型
Class<?> cs = obj.getClass();
// 循环复制
for (Field field : cs.getDeclaredFields()) {
try {
// 获取对象
Object value = this.get(field.getName());
if(value == null) {
continue;
}
field.setAccessible(true);
Object valueConvert = getValueByClass(value, field.getType());
field.set(obj, valueConvert);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("属性取值出错:" + field.getName(), e);
}
}
return obj;
}
/**
* 将指定值转化为指定类型并返回
* @param obj
* @param cs
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getValueByClass(Object obj, Class<T> cs) {
String obj2 = String.valueOf(obj);
Object obj3 = null;
if (cs.equals(String.class)) {
obj3 = obj2;
} else if (cs.equals(int.class) || cs.equals(Integer.class)) {
obj3 = Integer.valueOf(obj2);
} else if (cs.equals(long.class) || cs.equals(Long.class)) {
obj3 = Long.valueOf(obj2);
} else if (cs.equals(short.class) || cs.equals(Short.class)) {
obj3 = Short.valueOf(obj2);
} else if (cs.equals(byte.class) || cs.equals(Byte.class)) {
obj3 = Byte.valueOf(obj2);
} else if (cs.equals(float.class) || cs.equals(Float.class)) {
obj3 = Float.valueOf(obj2);
} else if (cs.equals(double.class) || cs.equals(Double.class)) {
obj3 = Double.valueOf(obj2);
} else if (cs.equals(boolean.class) || cs.equals(Boolean.class)) {
obj3 = Boolean.valueOf(obj2);
} else {
obj3 = (T)obj;
}
return (T)obj3;
}
// ============================= 写值 =============================
/**
* 给指定key添加一个默认值只有在这个key原来无值的情况先才会set进去
*/
public void setDefaultValue(String key, Object defaultValue) {
if(isNull(key)) {
set(key, defaultValue);
}
}
/** set一个值连缀风格 */
public SoMap set(String key, Object value) {
// 防止敏感key
if(key.toLowerCase().equals("this")) {
return this;
}
put(key, value);
return this;
}
/** 将一个Map塞进SoMap */
public SoMap setMap(Map<String, ?> map) {
if(map != null) {
for (String key : map.keySet()) {
this.set(key, map.get(key));
}
}
return this;
}
/** 将一个对象解析塞进SoMap */
public SoMap setModel(Object model) {
if(model == null) {
return this;
}
Field[] fields = model.getClass().getDeclaredFields();
for (Field field : fields) {
try{
field.setAccessible(true);
boolean isStatic = Modifier.isStatic(field.getModifiers());
if(!isStatic) {
this.set(field.getName(), field.get(model));
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
return this;
}
/** 将json字符串解析后塞进SoMap */
public SoMap setJsonString(String jsonString) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> map = new ObjectMapper().readValue(jsonString, Map.class);
return this.setMap(map);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
// ============================= 删值 =============================
/** delete一个值连缀风格 */
public SoMap delete(String key) {
remove(key);
return this;
}
/** 清理所有value为null的字段 */
public SoMap clearNull() {
Iterator<String> iterator = this.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
if(this.isNull(key)) {
iterator.remove();
this.remove(key);
}
}
return this;
}
/** 清理指定key */
public SoMap clearIn(String ...keys) {
List<String> keys2 = Arrays.asList(keys);
Iterator<String> iterator = this.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
if(keys2.contains(key) == true) {
iterator.remove();
this.remove(key);
}
}
return this;
}
/** 清理掉不在列表中的key */
public SoMap clearNotIn(String ...keys) {
List<String> keys2 = Arrays.asList(keys);
Iterator<String> iterator = this.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
if(keys2.contains(key) == false) {
iterator.remove();
this.remove(key);
}
}
return this;
}
/** 清理掉所有key */
public SoMap clearAll() {
clear();
return this;
}
// ============================= 快速构建 =============================
/** 构建一个SoMap并返回 */
public static SoMap getSoMap() {
return new SoMap();
}
/** 构建一个SoMap并返回 */
public static SoMap getSoMap(String key, Object value) {
return new SoMap().set(key, value);
}
/** 构建一个SoMap并返回 */
public static SoMap getSoMap(Map<String, ?> map) {
return new SoMap().setMap(map);
}
/** 将一个对象集合解析成为SoMap */
public static SoMap getSoMapByModel(Object model) {
return SoMap.getSoMap().setModel(model);
}
/** 将一个对象集合解析成为SoMap集合 */
public static List<SoMap> getSoMapByList(List<?> list) {
List<SoMap> listMap = new ArrayList<SoMap>();
for (Object model : list) {
listMap.add(getSoMapByModel(model));
}
return listMap;
}
/** 克隆指定key返回一个新的SoMap */
public SoMap cloneKeys(String... keys) {
SoMap so = new SoMap();
for (String key : keys) {
so.set(key, this.get(key));
}
return so;
}
/** 克隆所有key返回一个新的SoMap */
public SoMap cloneSoMap() {
SoMap so = new SoMap();
for (String key : this.keySet()) {
so.set(key, this.get(key));
}
return so;
}
/** 将所有key转为大写 */
public SoMap toUpperCase() {
SoMap so = new SoMap();
for (String key : this.keySet()) {
so.set(key.toUpperCase(), this.get(key));
}
this.clearAll().setMap(so);
return this;
}
/** 将所有key转为小写 */
public SoMap toLowerCase() {
SoMap so = new SoMap();
for (String key : this.keySet()) {
so.set(key.toLowerCase(), this.get(key));
}
this.clearAll().setMap(so);
return this;
}
/** 将所有key中下划线转为中划线模式 (kebab-case风格) */
public SoMap toKebabCase() {
SoMap so = new SoMap();
for (String key : this.keySet()) {
so.set(wordEachKebabCase(key), this.get(key));
}
this.clearAll().setMap(so);
return this;
}
/** 将所有key中下划线转为小驼峰模式 */
public SoMap toHumpCase() {
SoMap so = new SoMap();
for (String key : this.keySet()) {
so.set(wordEachBigFs(key), this.get(key));
}
this.clearAll().setMap(so);
return this;
}
/** 将所有key中小驼峰转为下划线模式 */
public SoMap humpToLineCase() {
SoMap so = new SoMap();
for (String key : this.keySet()) {
so.set(wordHumpToLine(key), this.get(key));
}
this.clearAll().setMap(so);
return this;
}
// ============================= 辅助方法 =============================
/** 指定key是否为null判定标准为 NULL_ELEMENT_ARRAY 中的元素 */
public boolean isNull(String key) {
return valueIsNull(get(key));
}
/** 指定key列表中是否包含value为null的元素只要有一个为null就会返回true */
public boolean isContainNull(String ...keys) {
for (String key : keys) {
if(this.isNull(key)) {
return true;
}
}
return false;
}
/** 与isNull()相反 */
public boolean isNotNull(String key) {
return !isNull(key);
}
/** 指定key的value是否为null作用同isNotNull() */
public boolean has(String key) {
return !isNull(key);
}
/** 指定value在此SoMap的判断标准中是否为null */
public boolean valueIsNull(Object value) {
return NULL_ELEMENT_LIST.contains(value);
}
/** 验证指定key不为空为空则抛出异常 */
public SoMap checkNull(String ...keys) {
for (String key : keys) {
if(this.isNull(key)) {
throw new RuntimeException("参数" + key + "不能为空");
}
}
return this;
}
static Pattern patternNumber = Pattern.compile("[0-9]*");
/** 指定key是否为数字 */
public boolean isNumber(String key) {
String value = getString(key);
if(value == null) {
return false;
}
return patternNumber.matcher(value).matches();
}
/**
* 转为JSON字符串
*/
public String toJsonString() {
try {
// SoMap so = SoMap.getSoMap(this);
return new ObjectMapper().writeValueAsString(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// /**
// * 转为JSON字符串, 带格式的
// */
// public String toJsonFormatString() {
// try {
// return JSON.toJSONString(this, true);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// ============================= web辅助 =============================
/**
* 返回当前request请求的的所有参数
* @return
*/
public static SoMap getRequestSoMap() {
// 大善人SpringMVC提供的封装
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(servletRequestAttributes == null) {
throw new RuntimeException("当前线程非JavaWeb环境");
}
// 当前request
HttpServletRequest request = servletRequestAttributes.getRequest();
if (request.getAttribute("currentSoMap") == null || request.getAttribute("currentSoMap") instanceof SoMap == false ) {
initRequestSoMap(request);
}
return (SoMap)request.getAttribute("currentSoMap");
}
/** 初始化当前request的 SoMap */
private static void initRequestSoMap(HttpServletRequest request) {
SoMap soMap = new SoMap();
Map<String, String[]> parameterMap = request.getParameterMap(); // 获取所有参数
for (String key : parameterMap.keySet()) {
try {
String[] values = parameterMap.get(key); // 获得values
if(values.length == 1) {
soMap.set(key, values[0]);
} else {
List<String> list = new ArrayList<String>();
for (String v : values) {
list.add(v);
}
soMap.set(key, list);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
request.setAttribute("currentSoMap", soMap);
}
/**
* 验证返回当前线程是否为JavaWeb环境
* @return
*/
public static boolean isJavaWeb() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();// 大善人SpringMVC提供的封装
if(servletRequestAttributes == null) {
return false;
}
return true;
}
// ============================= 常见key 以下key经常用所以封装以下方便写代码 =============================
/** get 当前页 */
public int getKeyPageNo() {
int pageNo = getInt("pageNo", 1);
if(pageNo <= 0) {
pageNo = 1;
}
return pageNo;
}
/** get 页大小 */
public int getKeyPageSize() {
int pageSize = getInt("pageSize", 10);
if(pageSize <= 0 || pageSize > 1000) {
pageSize = 10;
}
return pageSize;
}
/** get 排序方式 */
public int getKeySortType() {
return getInt("sortType");
}
// ============================= 工具方法 =============================
/**
* 将一个一维集合转换为树形集合
* @param list 集合
* @param idKey id标识key
* @param parentIdKey 父id标识key
* @param childListKey 子节点标识key
* @return 转换后的tree集合
*/
public static List<SoMap> listToTree(List<SoMap> list, String idKey, String parentIdKey, String childListKey) {
// 声明新的集合存储tree形数据
List<SoMap> newTreeList = new ArrayList<SoMap>();
// 声明hash-Map方便查找数据
SoMap hash = new SoMap();
// 将数组转为Object的形式key为数组中的id
for (int i = 0; i < list.size(); i++) {
SoMap json = (SoMap) list.get(i);
hash.put(json.getString(idKey), json);
}
// 遍历结果集
for (int j = 0; j < list.size(); j++) {
// 单条记录
SoMap aVal = (SoMap) list.get(j);
// 在hash中取出key为单条记录中pid的值
SoMap hashVp = (SoMap) hash.get(aVal.get(parentIdKey, "").toString());
// 如果记录的pid存在则说明它有父节点将她添加到孩子节点的集合中
if (hashVp != null) {
// 检查是否有child属性有则添加没有则新建
if (hashVp.get(childListKey) != null) {
@SuppressWarnings("unchecked")
List<SoMap> ch = (List<SoMap>) hashVp.get(childListKey);
ch.add(aVal);
hashVp.put(childListKey, ch);
} else {
List<SoMap> ch = new ArrayList<SoMap>();
ch.add(aVal);
hashVp.put(childListKey, ch);
}
} else {
newTreeList.add(aVal);
}
}
return newTreeList;
}
/** 指定字符串的字符串下划线转大写模式 */
private static String wordEachBig(String str){
String newStr = "";
for (String s : str.split("_")) {
newStr += wordFirstBig(s);
}
return newStr;
}
/** 返回下划线转小驼峰形式 */
private static String wordEachBigFs(String str){
return wordFirstSmall(wordEachBig(str));
}
/** 将指定单词首字母大写 */
private static String wordFirstBig(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
}
/** 将指定单词首字母小写 */
private static String wordFirstSmall(String str) {
return str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
}
/** 下划线转中划线 */
private static String wordEachKebabCase(String str) {
return str.replaceAll("_", "-");
}
/** 驼峰转下划线 */
private static String wordHumpToLine(String str) {
return str.replaceAll("[A-Z]", "_$0").toLowerCase();
}
}

View File

@ -1,93 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>服务提供方-确认授权页</title>
<style type="text/css">
*{margin: 0px; padding: 0px;}
.login-box{width: 300px; margin: 50px auto; padding: 100px; border: 1px #000 solid;}
</style>
</head>
<body>
<div class="login-box">
<h2>服务提供方-确认授权页</h2> <br>
<div>
<div>应用id: <span class="client_id"></span></div>
<div>请求授权: <span class="scope"></span></div>
<br>
<div>是否同意授权: </div>
<div>
<button onclick="ok()">同意</button>
<button onclick="no()">拒绝</button>
</div>
</div>
</div>
<script src="https://unpkg.zhimg.com/jquery@3.4.1/dist/jquery.min.js"></script>
<script type="text/javascript">
// 获取code详细信息
var code = getParam("code", null);
var codeObj = null;
if(code == null) {
throw alert("无效code");
}
$.ajax({
url: '/oauth2/getCodeInfo',
data: {code: code},
dataType: 'json',
success: function(res) {
if(res.data == null) {
return alert('无效授权码');
}
codeObj = res.data;
$(".client_id").html(res.data.clientId);
$(".scope").html(res.data.scope);
},
error: function(e, ee, eee) {
console.log('error');
alert(eee);
}
});
// 确认授权
function ok() {
$.ajax({
url: '/oauth2/confirm',
data: {code: code},
dataType: 'json',
success: function(res) {
if(res.code == 200) {
// 跳转
location.href = codeObj.redirectUri;
} else {
alert(res.msg);
}
},
error: function(e, ee, eee) {
alert(eee);
}
});
}
// 拒绝授权时,跳入拒绝授权地址
function no() {
// alert(codeObj.rejectUri)
location.href = codeObj.rejectUri;
}
// 从url中查询到指定名称的参数值
function getParam(name, defaultValue){
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == name){return pair[1];}
}
return(defaultValue == undefined ? null : defaultValue);
}
</script>
</body>
</html>

View File

@ -1,53 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>服务提供方-登录页</title>
<style type="text/css">
*{margin: 0px; padding: 0px;}
.login-box{width: 400px; margin: 50px auto;}
</style>
</head>
<body>
<div class="login-box">
<h2>服务提供方-登录页</h2> <br>
<div>注:您当前在服务提供方尚未登录,请先登录</div>
<div>测试账号: test test</div> <br>
账号:<input name="username" /> <br>
密码:<input name="password" type="password" /> <br>
<button onclick="doLogin()">登录</button>
</div>
<script src="https://unpkg.zhimg.com/jquery@3.4.1/dist/jquery.min.js"></script>
<script type="text/javascript">
// 登录方法
function getLoginId() {
}
// 登录方法
function doLogin() {
console.log('-----------');
$.ajax({
url: '/doLogin',
data: {
username: $('[name=username]').val(),
password: $('[name=password]').val()
},
dataType: 'json',
success: function(res) {
if(res.code == 200) {
alert('登录成功');
location.reload(true);
} else {
alert('登录失败');
}
},
error: function(e) {
console.log('error');
}
});
}
</script>
</body>
</html>

View File

@ -1,73 +0,0 @@
//package cn.dev33.satoken.oauth2.model;
//
///**
// * 权限Model
// * @author kong
// *
// */
//public class ScopeModel {
//
// /**
// * 权限名称
// */
// private String name;
//
// /**
// * 详细介绍
// */
// private String introduce;
//
//
// /**
// * 构造一个
// */
// public ScopeModel() {
// super();
// }
// /**
// * 构造一个
// * @param name 权限名称
// * @param introduce 权限详细介绍
// */
// public ScopeModel(String name, String introduce) {
// super();
// this.name = name;
// this.introduce = introduce;
// }
//
// /**
// * @return name
// */
// public String getName() {
// return name;
// }
//
// /**
// * @param name 要设置的 name
// */
// public void setName(String name) {
// this.name = name;
// }
//
// /**
// * @return introduce
// */
// public String getIntroduce() {
// return introduce;
// }
//
// /**
// * @param introduce 要设置的 introduce
// */
// public void setIntroduce(String introduce) {
// this.introduce = introduce;
// }
//
//
//
//
//
//
//
//
//}