You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

266 lines
11 KiB

10 months ago
package com.dsideal.gw.Handler;
10 months ago
import com.dsideal.gw.Bean.RetBean;
10 months ago
import com.dsideal.gw.GwApplication;
10 months ago
import com.dsideal.gw.Util.CommonUtil;
import com.dsideal.gw.Util.JwtUtil;
10 months ago
import com.jfinal.handler.Handler;
10 months ago
import com.jfinal.kit.StrKit;
10 months ago
import com.jfinal.upload.MultipartRequest;
import com.jfinal.upload.UploadFile;
10 months ago
import io.jsonwebtoken.Claims;
10 months ago
import okhttp3.*;
10 months ago
import javax.servlet.http.Cookie;
10 months ago
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
10 months ago
import java.util.*;
10 months ago
/**
*
* GET
* http://10.10.21.20:8000/dsBase/dm/getDmSchoolProperty
* http://10.10.21.20:8000/dsBase/global/getGlobalList?page=1&limit=10
* POST
* http://10.10.21.20:8000/dsBase/global/testPost?a=100
*
* http://10.10.21.20:8000/dsBase/global/testUpload
* form-data
* upfile ---> file
*/
public class RouterHandler extends Handler {
//OkHttp的实例单例模式
private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient();
/**
* JSON
*
* @param res
*/
10 months ago
public void renderJson(HttpServletResponse res, String body) {
10 months ago
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "no-cache");
res.setCharacterEncoding("UTF-8");
res.setContentType("application/json");
try {
10 months ago
res.getWriter().println(body);
10 months ago
res.getWriter().flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//OkHttp的回调函数同步执行
private void executeRequest(Request request, HttpServletResponse res) throws IOException {
Response response = OK_HTTP_CLIENT.newCall(request).execute();
if (response.isSuccessful()) {
String responseBody = null;
if (response.body() != null) {
responseBody = response.body().string();
}
10 months ago
renderJson(res, responseBody);
10 months ago
} else {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "请求失败!").toString());
10 months ago
}
}
public static RequestBody createRequestBody(HttpServletRequest req) {
FormBody.Builder formBodyBuilder = new FormBody.Builder();
// 遍历请求中的参数
Enumeration<String> parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String paramValue = req.getParameter(paramName);
formBodyBuilder.add(paramName, paramValue);
}
// 构建RequestBody
return formBodyBuilder.build();
}
@Override
public void handle(String target, HttpServletRequest req, HttpServletResponse res, boolean[] isHandled) {
//可以正确获取到URL的完整路径
String servletPath = req.getServletPath();
String queryString = req.getQueryString();
//对于根目录的访问,放行
if (servletPath.equals("/")) {
next.handle(target, req, res, isHandled);
return;
}
//如果是白名单不检查jwt,否则需要检查jwt
10 months ago
if (!GwApplication.whiteSet.contains(servletPath)) {
//是不是通过了登录检查?
boolean canPass = true;
//1、存在Cookie,检查是不是正确的Cookie
Cookie[] cookies = req.getCookies();
String identity_id = null;
String person_id = null;
String bureau_id = null;
String token = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("identity_id".equals(cookie.getName())) {
String cookieValue = cookie.getValue();
identity_id = cookieValue;
}
if ("person_id".equals(cookie.getName())) {
person_id = cookie.getValue();
}
if ("bureau_id".equals(cookie.getName())) {
bureau_id = cookie.getValue();
}
if ("token".equals(cookie.getName())) {
token = cookie.getValue();
}
}
}
//如果没有找到Cookie那么直接不通过
if (StrKit.isBlank(token) || StrKit.isBlank(bureau_id) || StrKit.isBlank(identity_id) || StrKit.isBlank(person_id)) {
canPass = false;
}
//找到了Cookie,那是不是合法的Cookie呢需要检查一下Token
if (canPass) {
Map<String, Object> loginMap = new HashMap<>();
loginMap.put("identity_id", identity_id);
loginMap.put("person_id", person_id);
loginMap.put("bureau_id", bureau_id);
10 months ago
String cookie_token = CommonUtil.Sign(loginMap, GwApplication.PropKit.get("CookieMd5SingPwd"));
10 months ago
if (!token.equals(cookie_token)) {//根据Cookie中的Token和计算出来的Token是否一致
canPass = false;
}
}
if (!canPass) {
//如果不存在Cookie,那么检查是不是存在JWT,并且JWT是不是正确的
if (req.getHeader("Authorization") != null) {
String jwtToken = req.getHeader("Authorization");
Claims claims = JwtUtil.getClaims(jwtToken);
10 months ago
if (claims != null) {
10 months ago
canPass = true;
}
}
}
10 months ago
if (!canPass) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "登录已过期,请重新登录!").toString());
10 months ago
isHandled[0] = true; //停止filter
return;
}
10 months ago
}
//路由到哪个微服务
int xie1 = servletPath.indexOf('/'); // 找到第一个 '/' 的索引
int xie2 = servletPath.indexOf('/', xie1 + 1); // 从第一个 '/' 之后开始找第二个 '/' 的索引
//action名称
String action = servletPath.substring(xie2 + 1);
if (xie1 == -1 || xie2 == -1) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "输入的字符串格式不正确,没有找到两个 '/'。").toString());
10 months ago
isHandled[0] = true; //停止filter
return;
}
String prefix = servletPath.substring(xie1 + 1, xie2); // 截取两个 '/' 之间的内容
if (!GwApplication.routeList.containsKey(prefix)) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, prefix + "前缀没有找到合适的路由表,请检查是否请求正确!").toString());
10 months ago
isHandled[0] = true; //停止filter
return;
}
//路由到哪个微服务
String FORWARD_URL = GwApplication.routeList.get(prefix) + "/" + prefix + "/" + action;
//1、如果是上传文件
10 months ago
if (req.getMethod().equals("POST") && req.getContentType() != null && req.getContentType().startsWith("multipart/form-data")) {
10 months ago
// 指定文件类型
MediaType mediaType = MediaType.parse("multipart/form-data");
MultipartRequest mp = new MultipartRequest(req);
List<UploadFile> files = mp.getFiles();
if (files.isEmpty()) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "没有上传文件!").toString());
10 months ago
isHandled[0] = true;//停止filter
return;
}
10 months ago
UploadFile uploadFile = files.getFirst();
10 months ago
10 months ago
// 获取文件流
10 months ago
RequestBody requestBody = RequestBody.create(uploadFile.getFile(), mediaType);
10 months ago
// 构建MultipartBody
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
10 months ago
.addFormDataPart("file", uploadFile.getFileName(), requestBody)
10 months ago
.build();
// 构建Request
Request request = new Request.Builder()
.url(FORWARD_URL)
.post(body)
.build();
try {
executeRequest(request, res);
isHandled[0] = true;//停止filter
return;
} catch (Exception e) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "请求失败!" + e).toString());
10 months ago
isHandled[0] = true;//停止filter
return;
}
}
//2、处理GET请求
if (req.getMethod().equals("GET")) {
//参数:queryString
10 months ago
Request.Builder builder;
10 months ago
if (queryString != null) {
10 months ago
builder = new Request.Builder().url(FORWARD_URL + "?" + queryString);
10 months ago
} else {
10 months ago
builder = new Request.Builder().url(FORWARD_URL);
}
if (!StrKit.isBlank(req.getHeader("Authorization"))) {
builder.addHeader("Authorization", req.getHeader("Authorization"));
builder.addHeader("Accept", "application/json;odata=verbose");
10 months ago
}
10 months ago
Request request = builder.build();
10 months ago
try {
executeRequest(request, res);
isHandled[0] = true;//停止filter
return;
} catch (IOException e) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "请求失败!" + e).toString());
10 months ago
isHandled[0] = true;//停止filter
return;
}
}
//3、处理POST请求
if (req.getMethod().equals("POST")) {
RequestBody body = createRequestBody(req);
10 months ago
Request.Builder builder;
10 months ago
if (queryString != null) {
10 months ago
builder = new Request.Builder().url(FORWARD_URL + "?" + queryString);
10 months ago
} else {
10 months ago
builder = new Request.Builder().url(FORWARD_URL);
}
if (!StrKit.isBlank(req.getHeader("Authorization"))) {
builder.addHeader("Authorization", req.getHeader("Authorization"));
builder.addHeader("Accept", "application/json;odata=verbose");
10 months ago
}
10 months ago
builder.post(body);
Request request = builder.build();
10 months ago
try {
executeRequest(request, res);
isHandled[0] = true;//停止filter
return;
} catch (IOException e) {
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "请求失败!" + e).toString());
10 months ago
isHandled[0] = true;//停止filter
return;
}
}
//4、其它的OPTIONS
10 months ago
renderJson(res, new RetBean(RetBean.ERROR, "系统只支持GET,POST其它的OPTIONS不支持文件上传请使用S3协议进行直传不通过JAVA处理JAVA只处理授权").toString());
10 months ago
//停止filter
isHandled[0] = true;
}
}