修正错误提交

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 以及其他信息
// 携带三个关键参数: code、client_id、client_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>