All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
net.wicp.tams.common.web.J2EEAssist Maven / Gradle / Ivy
/*
* **********************************************************************
* Copyright (c) 2022 .
* All rights reserved.
* 项目名称:common
* 项目描述:公共的工具集
* 版权说明:本软件属andy.zhou([email protected] )所有。
* ***********************************************************************
*/
package net.wicp.tams.common.web;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.json.JSONUtil;
import net.wicp.tams.common.constant.ContentType;
public abstract class J2EEAssist {
/***
* 得oriUrl的当前URL
*
* @param request
* @param protocol
* @param oriUrl
* @return
*/
public static String buildUrlAbsolute(HttpServletRequest request, String protocol, String oriUrl) {
String pro = StringUtil.hasNull(protocol, request.getProtocol().split("/")[0]);
String pre = String.format("%s://%s:%s", pro, request.getServerName(), request.getLocalPort());
return IOUtil.mergeFolderAndFilePath(pre, oriUrl);
}
public static String buildWebsockertUrl(HttpServletRequest request, boolean isSsl, String oriUrl) {
return buildUrlAbsolute(request, isSsl ? "wss" : "ws", oriUrl);
}
/****
* 得到请求的参数,如果是数组则对象是JSONArray,否则是String,与Tapestry.packParams方法一样,注意两个方法连动
*
* @param request
* @return
*/
@SuppressWarnings("rawtypes")
public static ObjectNode packParams(HttpServletRequest request, boolean convert) {
ObjectNode retobj = JsonNodeFactory.instance.objectNode();
if (request == null) {
return retobj;
}
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String key = String.valueOf(parameterNames.nextElement());
if (key.endsWith("[]")) {
String[] objs = request.getParameterValues(key);
if (ArrayUtils.isNotEmpty(objs)) {
ArrayNode ary = JsonNodeFactory.instance.arrayNode();
for (int i = 0; i < objs.length; i++) {
ary.add(convert ? JSONUtil.convertJsonValue(StringUtil.trimSpace(objs[i]))
: StringUtil.trimSpace(objs[i]));
}
retobj.set(key.replace("[]", ""), ary);
}
} else {
String str = ArrayUtils.isNotEmpty(request.getParameterValues(key))
? CollectionUtil.arrayJoin(request.getParameterValues(key), ",")
: request.getParameter(key);// 存在如:下拉多选值,奇怪的是:修改前如果选择了一项,request.getParameter(key)不为空,如果修改前没有选择项则为空?
retobj.put(key, convert ? JSONUtil.convertJsonValue(StringUtil.trimSpace(str))
: StringUtil.trimSpace(request.getParameter(key)));// 去除前后空格,复制粘贴失误
}
}
return retobj;
}
/**
* 得到请求中的payload数据
*
* @param req
* @return
*/
public static String getRequestPayload(HttpServletRequest req) {
try {
StringBuilder sb = new StringBuilder();
BufferedReader reader = req.getReader();
char[] buff = new char[1024];
int len;
while ((len = reader.read(buff)) != -1) {
sb.append(buff, 0, len);
}
return URLDecoder.decode(sb.toString(), "UTF-8");
} catch (Exception e) {
return null;
}
}
/***
* 通过response得到Excel输出流
*
* @param response 响应信息
* @param fileName 导出excel文件的名字
* @param isclear 清空输出流
* @return 输出流
*/
public static OutputStream getExcelOS(HttpServletResponse response, String fileName, boolean isclear) {
try {
OutputStream os = response.getOutputStream();
if (isclear) {
response.reset();// 清空输出流
}
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
return os;
} catch (IOException e) {
return null;
}
}
/***
* 通过response得到文件输出流
*
* @param response 响应信息
* @param fileFullName 导出excel文件的名字
* @param isclear 清空输出流
* @return 输出流
*/
public static OutputStream getFileOS(HttpServletResponse response, String fileFullName, ContentType contentType,
boolean isclear) {
try {
OutputStream os = response.getOutputStream();
if (isclear) {
response.reset();// 清空输出流
}
response.setHeader("Content-disposition", "attachment; filename=" + fileFullName);// 设定输出文件头
response.setContentType(contentType.getValue());// 定义输出类型//"application/octet-stream"
return os;
} catch (IOException e) {
return null;
}
}
public static OutputStream getFileOS(HttpServletResponse response, String fileFullName) {
ContentType contentType = ContentType.findByFileName(fileFullName);
return getFileOS(response, fileFullName, contentType, true);
}
/***
* 返回json数据
*
* @param response
* @param jsonMsg
*/
public static void returnJsonResponse(HttpServletResponse response, String jsonMsg) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
try {
PrintWriter out = response.getWriter();
out.print(jsonMsg);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void resWithJson(HttpServletResponse response, Result ret) {
// 将实体对象转换为JSON Object转换
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(ret.retJsonObj().toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
/***
* 读request的
*
* @param request
* @return
* @throws IOException
*/
public static byte[] readBody(HttpServletRequest request) throws IOException {
int formDataLength = request.getContentLength();
DataInputStream dataStream = new DataInputStream(request.getInputStream());
byte body[] = new byte[formDataLength];
int totalBytes = 0;
while (totalBytes < formDataLength) {
int bytes = dataStream.read(body, totalBytes, formDataLength);
totalBytes += bytes;
}
return body;
}
/***
* 得到webservice地址
*
* @param request http请求
* @param relaUrl webservice相对地址
* @return
*/
public static String getWebService(HttpServletRequest request, String relaUrl) {
String returl = Conf.get("common.web.websocket.context");
if (StringUtil.isNull(returl)) {// 没有设置websocket端口
String context = Conf.get("common.apiext.context");
returl = context.replace(request.getScheme(), "ws");
}
return IOUtil.mergeFolderAndFilePath(returl, relaUrl);
}
/***
* 返回json数据
*
* @param response
* @param optResult 要返回的结果封装
*/
public static void returnJsonResponse(HttpServletResponse response, Result optResult) {
returnJsonResponse(response, optResult.retJsonObj().toString());
}
}