package com.smtservlet.core; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.core.MethodParameter; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import com.smtservlet.core.SMTApp.SMTRequestConfig; import com.smtservlet.database.SMTDaoAbstract.SMTDaoSelectPage; import com.smtservlet.util.Json; import com.smtservlet.util.SMTJsonWriter; import com.smtservlet.util.SMTStatic.SMTCalcTime; import com.smtservlet.util.SMTStatic.SMTConvEmpty; import com.smtservlet.util.SMTStatic.SMTConvType; import com.smtservlet.util.SMTStatic; /** * 将webRequest包装成SMTRequest类进行操作 */ public class SMTRequest { protected static class SMTLoginFuncItem { public boolean _inited = false; public boolean _isRoot = true; public boolean[] _isRegexGroup = new boolean[]{false, false}; public int _allowAuth = 0; public String _regex = null; public String _regexGroup = null; public Object _funcID = null; public Object _funcPID = null; public StringBuilder[] _sbRegex = new StringBuilder[2]; public boolean isRegexGroup() { return _isRegexGroup[_allowAuth]; } public void isRegexGroup(boolean isGroup) { if(isGroup && !SMTStatic.isNullOrEmpty(this._regexGroup)) _isRegexGroup[_allowAuth] = true; } public StringBuilder getRegexBuilder() { if(_sbRegex[_allowAuth] == null) _sbRegex[_allowAuth] = new StringBuilder(); return _sbRegex[_allowAuth]; } } public static class SMTJsonWrapperView implements View { /** * 要返回的text文本 */ public Json _json; public SMTJsonWrapperView(Json json) { _json = json; } @Override public String getContentType() { return null; } @Override public void render(Map arg0, HttpServletRequest arg1, HttpServletResponse arg2) throws Exception { throw new RuntimeException("unsupported"); } } public static interface SMTInitCtrlListNotify { public boolean initCtrlListToJsonWriter(String initType, String ctrlId, Json jsonInit, SMTJsonWriter jsonWr); public List querySQL(String statement, Map params); } public static interface SMTReturnDownTmpFileNotify { public void saveDownTmpFile(File file) throws Exception; } /** * 返回text文本的view视图 */ public static class SMTByteArrayView implements View { /** * 要返回的二进制数数据 */ byte[] _data; /** * 生成的文本类型 */ protected String _contentType; /** * 是否只支持下载模式 */ protected boolean _onlyDownload = false; /** * 下载后的缺省名 */ protected String _downName; /** * 构造函数 * * @param text - 要返回的文本 * @throws Exception */ public SMTByteArrayView(byte[] data, String downName, Object contentType) throws Exception { _data = data; _downName = downName; if(contentType == null) { throw new Exception("contentType can't null"); } if(contentType instanceof Boolean) { if(!(Boolean)contentType) { _contentType = "application/octet-stream;charset=UTF-8"; _onlyDownload = true; } else { String checkName = _downName.toLowerCase(); if(checkName.endsWith(".gif")) _contentType = "image/gif"; else if(checkName.endsWith(".jpg")) _contentType = "image/gif"; else if(checkName.endsWith(".png")) _contentType = "image/png"; else if(checkName.endsWith(".pdf")) _contentType = "application/pdf"; else { _contentType = "application/octet-stream;charset=UTF-8"; _onlyDownload = true; } } } else if(contentType instanceof String) { _contentType = (String)contentType; } else throw new Exception("unknow contentType : " + contentType); } @Override public String getContentType() { return null; } @Override public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { String contentType = _contentType; response.setContentType(contentType); response.setBufferSize(8192); if(_onlyDownload) { StringBuffer contentDisposition = new StringBuffer(); contentDisposition.append("attachment;"); contentDisposition.append("filename=\""); contentDisposition.append(new String( (_downName).getBytes("UTF-8"), "UTF-8" )); contentDisposition.append("\";"); response.setHeader("Content-Disposition",contentDisposition.toString()); } response.getOutputStream().write(_data, 0, _data.length); } } /** * 返回text文本的view视图 */ public static class SMTTextView implements View { /** * 要返回的text文本 */ protected String _text; protected String _contentType; /** * 构造函数 * * @param text - 要返回的文本 */ public SMTTextView(String text, String contentType) { _text = text; _contentType = contentType; } public String getText() { return _text; } @Override public String getContentType() { return null; } @Override public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setCharacterEncoding("UTF-8"); //response.setContentType(_textMode ? "text/plain;charset=UTF-8" : "text/html;charset=UTF-8"); response.setContentType(_contentType + ";charset=UTF-8"); byte[] data = _text.getBytes("UTF-8"); response.getOutputStream().write(data, 0, data.length); } } /** * 返回text文本的view视图 */ protected static class SMTDownloadFileView implements View { /** * 要下载的文件 */ protected File _file; /** * 下载后的缺省名 */ protected String _downName; /** * 下载成功后是否自动删除文件 */ protected boolean _delFile; /** * 生成的文本类型 */ protected String _contentType; /** * 是否只支持下载模式 */ protected boolean _onlyDownload = false; /** * 下载文件的视图 * * @param file - 文件名 * @param downName - 下载后的名称,为null则使用文件名 * @param contentType - Boolean : 是否自动检测类型 * - String : 指定类型 * @param delFile - 下载后是否自动删除 * @throws Exception */ public SMTDownloadFileView(File file, String downName, Object contentType, boolean delFile) throws Exception { _file = file; _delFile = delFile; if(downName == null) _downName = _file.getName(); else _downName = downName; if(contentType == null) { throw new Exception("contentType can't null"); } else if(contentType instanceof Boolean) { if(!(Boolean)contentType) { _contentType = "application/octet-stream;charset=UTF-8"; _onlyDownload = true; } else { String checkName = _downName.toLowerCase(); if(checkName.endsWith(".gif")) _contentType = "image/gif"; else if(checkName.endsWith(".jpg")) _contentType = "image/gif"; else if(checkName.endsWith(".png")) _contentType = "image/png"; else if(checkName.endsWith(".pdf")) _contentType = "application/pdf"; else { _contentType = "application/octet-stream;charset=UTF-8"; _onlyDownload = true; } } } else if(contentType instanceof String) { _contentType = (String)contentType; } else throw new Exception("unknow contentType : " + contentType); } @Override public String getContentType() { return null; } @Override public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { boolean downOK = false; FileInputStream is = null; ServletOutputStream out = null; try { is = new FileInputStream(_file); String contentType = _contentType; response.setContentType(contentType); response.setBufferSize(8192); if(_onlyDownload) { StringBuffer contentDisposition = new StringBuffer(); contentDisposition.append("attachment;"); contentDisposition.append("filename=\""); contentDisposition.append(new String( (_downName).getBytes("UTF-8"), "UTF-8" )); contentDisposition.append("\";"); response.setHeader("Content-Disposition",contentDisposition.toString()); } //response.setHeader( // "Content-Disposition","attachment;filename=\""+new String(shortFileName.getBytes("utf-8"),"GB18030")+"\";"); out = response.getOutputStream(); byte[] bytes = new byte[0xffff]; int b = 0; while ((b = is.read(bytes, 0, 0xffff)) > 0) { out.write(bytes, 0, b); } downOK = true; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { } } if(_delFile && downOK) _file.delete(); } } } /** * 返回text文本的view视图 */ protected static class SMTDownloadStreamView implements View { /** * 要下载的文件 */ protected InputStream _is; /** * 下载后的缺省名 */ protected String _downName; /** * 下载成功后是否自动关闭流 */ protected boolean _closeStream; /** * 生成的文本类型 */ protected String _contentType; /** * 是否只支持下载模式 */ protected boolean _onlyDownload = false; protected Date _lastModifiedTime; /** * 下载文件的视图 * * @param file - 文件名 * @param downName - 下载后的名称,为null则使用文件名 * @param contentType - Boolean : 是否自动检测类型 * - String : 指定类型 * @param delFile - 下载后是否自动删除 * @throws Exception */ public SMTDownloadStreamView(InputStream is, String downName, Object contentType, Date lastModifiedTime, boolean closeStream) throws Exception { _is = is; _closeStream = closeStream; _lastModifiedTime = lastModifiedTime; _downName = downName; if(contentType == null) { throw new Exception("contentType can't null"); } else if(contentType instanceof Boolean) { if(!(Boolean)contentType) { _contentType = "application/octet-stream;charset=UTF-8"; _onlyDownload = true; } else { String checkName = _downName.toLowerCase(); if(checkName.endsWith(".gif")) _contentType = "image/gif"; else if(checkName.endsWith(".jpg")) _contentType = "image/gif"; else if(checkName.endsWith(".png")) _contentType = "image/png"; else if(checkName.endsWith(".pdf")) _contentType = "application/pdf"; else { _contentType = "application/octet-stream;charset=UTF-8"; _onlyDownload = true; } } } else if(contentType instanceof String) { _contentType = (String)contentType; } else throw new Exception("unknow contentType : " + contentType); } @Override public String getContentType() { return null; } @Override public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { ServletOutputStream out = null; try { String contentType = _contentType; response.setContentType(contentType); if(_lastModifiedTime != null) response.setDateHeader("Last-Modified", _lastModifiedTime.getTime() + java.util.TimeZone.getDefault().getRawOffset()); response.setBufferSize(8192); if(_onlyDownload) { StringBuffer contentDisposition = new StringBuffer(); contentDisposition.append("attachment;"); contentDisposition.append("filename=\""); contentDisposition.append(new String( (_downName).getBytes("UTF-8"), "UTF-8" )); contentDisposition.append("\";"); response.setHeader("Content-Disposition",contentDisposition.toString()); } //response.setHeader( // "Content-Disposition","attachment;filename=\""+new String(shortFileName.getBytes("utf-8"),"GB18030")+"\";"); out = response.getOutputStream(); byte[] bytes = new byte[0xffff]; int b = 0; while ((b = _is.read(bytes, 0, 0xffff)) > 0) { out.write(bytes, 0, b); } } finally { if (_closeStream) { try { _is.close(); } catch (IOException e) { } } if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { } } } } } /** * log对象 */ protected static Logger _logger = LogManager.getLogger(SMTRequest.class); /** * 在request中保存SMTRequest使用的key */ public static String _requestSessionKey = "SMTRequest_Session_key"; public static String _requestUserIdKey = "SMTRequest_User_id_key"; /** * web request对象 */ protected NativeWebRequest _webRequest = null; /** * request code值 */ protected String _requestCode = null; /** * json配置对象 */ protected Json _jsonRequest = null; protected boolean _enableLog = true; protected MultipartFile _uploadFile = null; /** * 用于wrapper */ protected Json _wrapperJson = null; protected Map _mapName2Params = null; protected boolean _isWrapperMode = false; public void setEnableLog(boolean enable) { _enableLog = enable; } public void setUploadFile(MultipartFile uploadFile) { _uploadFile = uploadFile; } /** * 根据methodParameter中getParameterType()的指定 信息创建SMTRequest对象 * * @param methodParameter - methodParameter对象 * @param webRequest - webRequest对象 * @return - 返回创建后的SMTRequest派生类,如果类型不匹配则返回null */ public static SMTRequest newRequest(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { return newRequest(methodParameter.getParameterType(), webRequest); } /** * 根据type 信息创建SMTRequest对象 * * @param type - type对象 * @param webRequest - webRequest对象 * @return - 返回创建后的SMTRequest派生类,如果类型不匹配则返回null */ public static SMTRequest newRequest(Class type, NativeWebRequest webRequest) throws Exception { if(SMTRequest.class.isAssignableFrom(type)) { String requestCode = SMTApp.getRequestCode((HttpServletRequest)webRequest.getNativeRequest()); SMTRequestConfig requestConfig = SMTApp.getRequestConfig(requestCode); return newRequest(type, requestCode, requestConfig, webRequest); } return null; } public static SMTRequest newRequest(Class type, String requestCode, SMTRequestConfig requestConfig, NativeWebRequest webRequest) throws Exception { SMTRequest req; if(requestConfig._clzTranReq != null) { req = (SMTRequest) requestConfig._clzTranReq.newInstance(); req.initInstance(webRequest, requestCode, requestConfig); } else if(requestConfig._mapBean instanceof SMTAppNewRequest) { req = ((SMTAppNewRequest)requestConfig._mapBean).newSMTRequest(webRequest, requestCode, requestConfig); } else { req = (SMTRequest) SMTApp.getRequestClass(type).newInstance(); req.initInstance(webRequest, requestCode, requestConfig); } return req; } /** * 判断当前methodParameter中的getParameterType()是否是SMTRequest的派生类 * * @param methodParameter - methodParameter对象 * @return - 判断是否 */ public static boolean isSMTRequestType(MethodParameter methodParameter) { return SMTRequest.class.isAssignableFrom(methodParameter.getParameterType()); } /** * 从request对象中获取保存的SMTRequest对象 * * @param request - request对象 * @return - 返回SMTRequest对象 */ public static SMTRequest getInstance(HttpServletRequest request) { return (SMTRequest)request.getAttribute(_requestSessionKey); } public static void destroyInstance(HttpServletRequest request) { SMTRequest tranReq = SMTRequest.getInstance(request); if(tranReq != null) tranReq.destroy(false); } /** * 构造函数,只能在内部创建 */ protected SMTRequest() { } @Override protected void finalize() { destroy(true); } public void setLoginUserId(String userId) throws Exception { this.setSessionAttribute(_requestUserIdKey, userId); } public String getLoginUserId() throws Exception { return (String) this.getSessionAttribute(_requestUserIdKey); } /** * 判断当前request中发送的last-modify是否小于当前时间 * * @return - 返回比较结果 */ public boolean isRequestModified() throws Exception { return _webRequest.checkNotModified(SMTApp.getStartupTime()); } /** * 判断当前request中发送的last-modify是否小于指定时间 * * @param time - 比较的时间 * * @return - 返回比较结果 */ public boolean isRequestModified(long time) throws Exception { return _webRequest.checkNotModified(time); } /** * 返回当前请求的code,此code是通过url转换过来的 * * @return - 请求的code */ public String getRequestCode() throws Exception { return this._requestCode; } public String getRequestParameter(String parameter) { if(_mapName2Params != null) { String[] values = _mapName2Params.get(parameter); if(values != null) return values[0]; return null; } return this.getRequest().getParameter(parameter); } /** * 设置request的属性 * * @param name - 名称 * @param value - 属性 */ public void setRequestAttribute(String name, Object value) throws Exception { this.getRequest().setAttribute(name, value); } /** * 设置session的属性 * * @param name - 名称 * @param value - 属性 */ public void setSessionAttribute(String name, Object value) throws Exception { this.getSession().setAttribute(name, value); } /** * 设置全局的属性 * * @param name - 名称 * @param value - 属性 */ public void setGlobalAttribute(String name, Object value) throws Exception { this.getRequest().getServletContext().setAttribute(name, value); } /** * 设置属性 * * @param name - 名称 * @param value - 属性 * @param scope - RequestAttributes.SCOPE_REQUEST, RequestAttributes.SCOPE_SESSION, RequestAttributes.SCOPE_GLOBAL_SESSION */ public void setAttribute(String name, Object value, int scope) throws Exception { switch(scope) { case RequestAttributes.SCOPE_REQUEST: setRequestAttribute(name, value); break; case RequestAttributes.SCOPE_SESSION: setSessionAttribute(name, value); break; } } /** * 获取request的属性 * * @param name - 名称 * @return - 值 */ public Object getRequestAttribute(String name) throws Exception { return this.getRequest().getAttribute(name); } /** * 获取session的属性 * * @param name - 名称 * @return - 值 */ public Object getSessionAttribute(String name) throws Exception { return this.getSession().getAttribute(name); } /** * 获取全局的属性 * * @param name - 名称 * @return - 值 */ public Object getGlobalAttribute(String name) throws Exception { return this.getRequest().getServletContext().getAttribute(name); } /** * 获取属性 * * @param name - 名称 * @param scope - RequestAttributes.SCOPE_REQUEST, RequestAttributes.SCOPE_SESSION, RequestAttributes.SCOPE_GLOBAL_SESSION * @param value - 属性 */ public Object getAttribute(String name, Object value, int scope) throws Exception { switch(scope) { case RequestAttributes.SCOPE_REQUEST: return getRequestAttribute(name); case RequestAttributes.SCOPE_SESSION: return getSessionAttribute(name); } return null; } /** * 将请求的参数输出到log中 * * @param title - 输出的标题 */ protected void logRequestParams(String title) throws Exception { if(!_logger.isDebugEnabled()) return; StringBuilder sbLog = new StringBuilder(); if(title.length() > 0) sbLog.append(title + "\n"); String queryString = getRequest().getQueryString(); sbLog.append(String.format( "ReqURL:%s:%s%s\n", getRequest().getMethod(), getRequest().getRequestURL(), queryString== null ? "" : "?" + queryString)); Map map = _webRequest.getParameterMap(); for(Entry ent : map.entrySet()) { String keys = ent.getKey().toString(); String values = ((String[])ent.getValue())[0]; // if(this._disp.isSecurityParam(keys)) // log(SMTLog.Debug, String.format("ReqPara(Security):%s=***", keys, values)); // else sbLog.append(String.format("ReqPara:%s=%s\n", keys, values)); } _logger.debug(sbLog.toString()); } /** * 获取参数映射表 * * @return - 返回参数映射表 */ public Map getParameterMap() throws Exception { if(_mapName2Params != null) return _mapName2Params; return _webRequest.getParameterMap(); } /** * 初始化函数 * * @param webRequest - webRequest对象 * @throws Exception */ public void initInstance(NativeWebRequest webRequest, String requestCode, SMTRequestConfig requestConfig) throws Exception { // 保存基本信息 _webRequest = webRequest; this.setRequestAttribute(_requestSessionKey, this); logRequestParams("SMTRequest"); // 获取配置信息 this._requestCode = requestCode; if(requestConfig != null) _jsonRequest = requestConfig._jsonConfig; else _jsonRequest = SMTStatic.emptyObject; } /** * 获取当前请求对应的json配置,如果没有,则为空对象 * * @return - 当前请求的json配置 */ public Json getRequestJson() throws Exception { if(_wrapperJson != null) return _wrapperJson; return _jsonRequest; } public NativeWebRequest getNativeWebRequest() { return _webRequest; } /** * 获取当前请求的request对象 * * @return - 返回request对象 */ public HttpServletRequest getRequest() { return _webRequest.getNativeRequest(HttpServletRequest.class); } public HttpServletResponse getResponse() { return _webRequest.getNativeResponse(HttpServletResponse.class); } /** * 获取当前请求的session对象 * * @return - session对象 */ public HttpSession getSession() throws Exception { return getRequest().getSession(); } /** * 关闭当前请求 */ public void destroy(boolean isFinalize) { } /** * 返回jsp的视图 * * @param viewName - 视图名 * @return - 包装视图的ModelAndView对象 */ public ModelAndView returnView(String viewName) { HttpServletRequest request = this.getRequest(); String basePath = SMTApp.getRequestWebRoot(request); request.setAttribute("WEB_ROOT", basePath); request.setAttribute("JSP_PATH", this._requestCode); request.setAttribute("JSON_PATH", "request_map" + Json._jsonPathSplit + this._requestCode); if(_enableLog) _logger.debug("ResponseJsp:" + viewName); return new ModelAndView(viewName); } public ModelAndView returnDownloadByteArray(byte[] data, String fileName, Object contentType) throws Exception { _logger.debug("ResponseByteArray:" + fileName); return new ModelAndView(new SMTByteArrayView(data, fileName, contentType)); } /** * 返回文件下载 * * @param file - 文件名 * @param fileName - 下载后的缺省名 * @param contentType - Boolean : 是否自动检测类型 * - String : 指定类型 * @param delFile - 是否自动删除 * @return - 返回文件下载视图 */ public ModelAndView returnDownloadFile(File file, String fileName, Object contentType, boolean delFile) throws Exception { if(_enableLog) _logger.debug("ResponseFileText:" + file.getAbsolutePath()); return new ModelAndView(new SMTDownloadFileView(file, fileName, contentType, delFile)); } public ModelAndView returnDownloadStream(InputStream is, String downName, Object contentType, Date lastModifiedTime, boolean closeStream) throws Exception { if(_enableLog) _logger.debug("ResponseStreamText:" + downName); return new ModelAndView(new SMTDownloadStreamView(is, downName, contentType, lastModifiedTime, closeStream)); } /** * 返回文件下载 * * @param file - 文件名 * @param fileName - 下载后的缺省名 * @param delFile - 是否自动删除 * @return - 返回文件下载视图 */ public ModelAndView returnDownloadFile(File file, String fileName, boolean delFile) throws Exception { if(_enableLog) _logger.debug("ResponseFileText:" + file.getAbsolutePath()); return new ModelAndView(new SMTDownloadFileView(file, fileName, false, delFile)); } /** * 返回文本内的数据 * * @param file - 文件名 * @return */ public ModelAndView returnFileText(File file) throws Exception { if(_enableLog) _logger.debug("ResponseFile:" + file.getAbsolutePath()); return returnText(SMTStatic.readAllText(file), "text/plain"); } /** * 返回纯文字对象 * * @param viewName - 视图名 * @return - 包装视图的ModelAndView对象 */ public ModelAndView returnText(String text) { return returnText(text, "text/plain"); } public ModelAndView returnText(String text, String contentType) { if(_enableLog) { String logText; int maxSize = SMTApp.getThis().getMaxLogSize(); if(maxSize > 0 && text.length() > maxSize) logText = text.substring(0, maxSize); else logText = text; _logger.debug("ResponseText:" + logText); } return new ModelAndView(new SMTTextView(text, contentType)); } /** * 返回HTML对象 * * @param viewName - 视图名 * @return - 包装视图的ModelAndView对象 */ public ModelAndView returnHtml(String html) throws Exception { if(_enableLog) _logger.debug("ResponseHtml:" + (html.length() > 20 ? (html.substring(0, 20) + " ....") : html)); return new ModelAndView(new SMTTextView(html, "text/html")); } /** * 将json变成文字后返回 * * @param viewName - 视图名 * @return - 包装视图的ModelAndView对象 * @throws Exception */ public ModelAndView returnJson(SMTJsonWriter json) throws Exception { return returnJson(json.getRootJson()); } public ModelAndView returnSelectPage(SMTDaoSelectPage list) throws Exception { return returnSelectPage(list, true); } @SuppressWarnings("unchecked") public ModelAndView returnSelectPage(SMTDaoSelectPage list, boolean toString) throws Exception { SMTJsonWriter jsonWr = new SMTJsonWriter(false); jsonWr.addKeyValue("json_ok", true); jsonWr.beginMap("init_datatable"); jsonWr.addKeyValue("total", list.getTotal()); jsonWr.beginArray("map"); for(Object rec : list.getRecords()) { Map mrec = (Map)rec; jsonWr.beginMap(null); for(Entry entry : mrec.entrySet()) { Object value = entry.getValue(); if(value == null) value = ""; if(toString && !(value instanceof String)) { if(value instanceof Date) { value = SMTStatic.toString(value).substring(0, 10); } else { value = SMTStatic.toString(value); } } jsonWr.addKeyValue(entry.getKey().toUpperCase(), value); } jsonWr.endMap(); } jsonWr.endArray(); jsonWr.endMap(); return this.returnJson(jsonWr); } /** * 将json变成文字后返回 * * @param viewName - 视图名 * @return - 包装视图的ModelAndView对象 */ public ModelAndView returnJson(Json json) throws Exception { if(_isWrapperMode) return new ModelAndView(new SMTJsonWrapperView(json)); return returnText(json.toString(), "application/json"); } /** * 将参数转换成值 * * @param value - 字符串表现的值 * @param type - 数据类型 * @param skipEmpty - 空值是否返回null * @param throwError - 出错是否抛异常 * @return - Exception:错误,null:忽略, 其他:返回转换后的值, */ public Object convParamToValue(String paramName, SMTConvType type, SMTConvEmpty skipEmpty, boolean throwError) throws Exception { String value = this.getRequestParameter(paramName); if(skipEmpty == SMTConvEmpty.ErrorEmpty && value == null) { Exception ex = new Exception(String.format("can't find param [%s]", paramName)); if(throwError) throw ex; return ex; } Object ret = SMTStatic.convStrToValue(value == null ? "" : value, type, skipEmpty); if(throwError && ret instanceof Exception) throw new Exception(String.format("convert param [%s] to type [%s] exception", paramName, type), (Exception)ret); return ret; } /** * 将参数转换成数组 * * @param value - 字符串表现的值 * @param type - 数据类型 * @param split - 切分字符串 * @param skipEmpty - 空值是否返回null * @param throwError - 出错是否抛异常 * @return - Exception:错误,null:忽略, 其他:返回转换后的值, */ public Object convParamToArray(String paramName, SMTConvType type, SMTConvEmpty skipEmpty, String split, boolean throwError) throws Exception { String value = this.getRequestParameter(paramName); if(skipEmpty == SMTConvEmpty.ErrorEmpty && value == null) { Exception ex = new Exception(String.format("can't find param [%s]", paramName)); if(throwError) throw ex; return ex; } Object ret = SMTStatic.convStrToArray(value == null ? "" : value, type, skipEmpty, split); if(throwError && ret instanceof Exception) throw new Exception(String.format("convert param [%s] to array type [%s] exception", paramName, type), (Exception)ret); return ret; } /** * 通过json配置列表,将上传参数转换成值,并保存在map中 * * @param jsonParams - json配置列表 * @param mapName2Value - 返回的映射数据 * @param skipEmpty - 对于空白的缺省处理 * @param throwError - 出错是否抛异常 * @return - true:全部成功,false:有错 */ public boolean convParamListByJson(Json jsonParams, Map mapName2Value, SMTConvEmpty skipEmpty, boolean throwError) throws Exception { boolean ret = true; if(jsonParams.isObject()) { for(Entry entry : jsonParams.asJsonMap().entrySet()) { if(convParamByJson(entry.getValue(), mapName2Value, skipEmpty, throwError)) ret = false; } } else if(jsonParams.isArray()) { for(Json item : jsonParams.asJsonList()) { if(convParamByJson(item, mapName2Value, skipEmpty, throwError)) ret = false; } } else throw new Exception("jsonParams type is not map or array"); return ret; } /** * 通过json配置,将上传参数转换成值,并保存在map中 * * @param jsonParams - json配置列表 * @param mapName2Value - 返回的映射数据 * @param skipEmpty - 对于空白的缺省处理 * @param throwError - 出错是否抛异常 * @return - true:全部成功,false:有错 */ public boolean convParamByJson(Json jsonParam, Map mapName2Value, SMTConvEmpty skipEmpty, boolean throwError) throws Exception { if(!jsonParam.isObject()) throw new Exception("current is not map json:" + jsonParam.toString()); // 如果没有field或ctrl属性,则直接忽略 if(!jsonParam.has("field") || !jsonParam.has("ctrl") || !jsonParam.has("type")) return true; // 获取字段名 boolean ret = true; String field = jsonParam.at("field").asString(); String ctrl = jsonParam.at("ctrl").asString(); SMTConvType type = Enum.valueOf(SMTConvType.class, jsonParam.at("type").asString()); String mode = jsonParam.safeGetStr("mode", "only"); if(jsonParam.has("empty")) skipEmpty = Enum.valueOf(SMTConvEmpty.class, jsonParam.at("empty").asString()); // 取值 if(mode.equals("between")) { ret = insertValueToMap(field + "_s", convParamToValue(ctrl + "_s", type, skipEmpty, throwError), mapName2Value, ret); ret = insertValueToMap(field + "_e", convParamToValue(ctrl + "_e", type, skipEmpty, throwError), mapName2Value, ret); } else if(mode.equals("array")) { String split = jsonParam.safeGetStr("split", ","); ret = insertValueToMap(field, convParamToArray(ctrl, type, skipEmpty, split, throwError), mapName2Value, ret); } else if(mode.equals("only")) { ret = insertValueToMap(field, convParamToValue(ctrl, type, skipEmpty, throwError), mapName2Value, ret); } else if(mode.equals("day")) { Date date = (Date) convParamToValue(ctrl, SMTConvType.Date, skipEmpty, throwError); if(date != null) { insertValueToMap(field + "_s", SMTStatic.calculateTime(date, SMTCalcTime.SET_HOUR, 0, SMTCalcTime.SET_MINUTE, 0, SMTCalcTime.SET_SECOND, 0, SMTCalcTime.SET_MILLISECOND, 0), mapName2Value, ret); insertValueToMap(field + "_e", SMTStatic.calculateTime(date, SMTCalcTime.SET_HOUR, 23, SMTCalcTime.SET_MINUTE, 59, SMTCalcTime.SET_SECOND, 59, SMTCalcTime.SET_MILLISECOND, 999), mapName2Value, ret); } } else if(mode.equals("day_range")) { Date dateS = (Date) convParamToValue(ctrl + "___ctrls", SMTConvType.Date, skipEmpty, throwError); Date dateE = (Date) convParamToValue(ctrl + "___ctrle", SMTConvType.Date, skipEmpty, throwError); if(dateS != null) insertValueToMap(field + "_s", SMTStatic.calculateTime(dateS, SMTCalcTime.SET_HOUR, 0, SMTCalcTime.SET_MINUTE, 0, SMTCalcTime.SET_SECOND, 0, SMTCalcTime.SET_MILLISECOND, 0), mapName2Value, ret); if(dateE != null) insertValueToMap(field + "_e", SMTStatic.calculateTime(dateE, SMTCalcTime.SET_HOUR, 23, SMTCalcTime.SET_MINUTE, 59, SMTCalcTime.SET_SECOND, 59, SMTCalcTime.SET_MILLISECOND, 999), mapName2Value, ret); } else throw new Exception(String.format("mode [%s] is not 'between' or 'array' or 'only'", mode)); return ret; } /** * 如果value是有效输入则插入map,否则返回false * @param key - 要插入的key * @param value - 要插入的值 * @param mapName2Value - 返回插入的map * @param prevStat - 前一次的状态 * @return - 如果失败则返回false, 如果成功则返回prevStat */ protected boolean insertValueToMap(String key, Object value, Map mapName2Value, boolean prevStat) throws Exception { if(value == null) return true; if(value instanceof Exception) return false; mapName2Value.put(key, value); return prevStat; } /** * 返回json ok状态 * @param isOK - json_ok的值 * @param msg - json_msg的值 * @param url - json_url的值 * @return - 要返回的视图 */ public ModelAndView returnJsonState(boolean isOK, String msg, String url) throws Exception { return this.returnJson(newReturnJsonWriter(isOK, msg, url)); } /** * 创建缺省的JsonWriter为返回json准备 * @param isOK - json_ok的值 * @param msg - json_msg的值 * @param url - json_url的值 * @return - 返回生成后的JsonWriter */ public SMTJsonWriter newReturnJsonWriter(boolean isOK, String msg, String url) throws Exception { SMTJsonWriter jsonWr = new SMTJsonWriter(false); jsonWr.addKeyValue("json_ok", isOK); if(msg != null) jsonWr.addKeyValue("json_msg", msg); if(url != null) jsonWr.addKeyValue("json_url", url); return jsonWr; } public SMTJsonWriter newReturnAsyncEndJsonWriter(boolean returnRequestParam, String[] params) throws Exception { SMTJsonWriter jsonWr = new SMTJsonWriter(false); jsonWr.addKeyValue("json_ok", true); jsonWr.beginMap("json_async"); { jsonWr.addKeyValue("waiting", false); } jsonWr.endMap(); // 将request的参数复制到输出参数中 if(returnRequestParam) { Map mapParams = getParameterMap(); if(mapParams.size() > 0) { for(Entry entry : getParameterMap().entrySet()) { jsonWr.addKeyValue(entry.getKey(), entry.getValue()[0]); } } } // 将外部设置的参数保存 if(params != null && params.length > 0) { for(int i = 0; i < params.length; i += 2) { jsonWr.addKeyValue(params[i + 0], params[i + 1]); } } return jsonWr; } public ModelAndView returnAsyncEndJsonWriter(boolean returnRequestParam, String[] params) throws Exception { return this.returnJson(newReturnAsyncEndJsonWriter(returnRequestParam, params)); } /** * 返回异步返回的jsonWriter对象 * * @param waiting - 是否继续等待 * @param code - 等待时请求的code * @param waitTime - 下次发起请求的时间 * @param returnRequestParam - 是否将request中的参数返回 * @param params - 附加的参数 * @return - 返回的jsonWrite对象 * @throws Exception */ public ModelAndView returnAsyncJsonWriter(String code, int waitTime, String waitMsg, boolean returnRequestParam, String[] params) throws Exception { return this.returnJson(newReturnAsyncJsonWriter(code, waitTime, waitMsg, returnRequestParam, params)); } /** * 生成异步返回的jsonWriter对象 * * @param waiting - 是否继续等待 * @param code - 等待时请求的code * @param waitTime - 下次发起请求的时间 * @param returnRequestParam - 是否将request中的参数返回 * @param params - 附加的参数 * @return - 生成后的jsonWrite对象 * @throws Exception */ public SMTJsonWriter newReturnAsyncJsonWriter(String code, int waitTime, String waitMsg, boolean returnRequestParam, String[] params) throws Exception { SMTJsonWriter jsonWr = new SMTJsonWriter(false); jsonWr.addKeyValue("json_ok", true); jsonWr.beginMap("json_async"); { jsonWr.addKeyValue("waiting", true); jsonWr.addKeyValue("code", code); if(waitTime > 0) jsonWr.addKeyValue("wait_time", waitTime); if(!SMTStatic.isNullOrEmpty(waitMsg)) jsonWr.addKeyValue("wait_msg", waitMsg); // 将request的参数复制到输出参数中 if(returnRequestParam) { //HttpServletRequest request = this.getRequest(); Map mapParams = getParameterMap(); if(mapParams.size() > 0) { jsonWr.beginMap("params"); for(Entry entry : getParameterMap().entrySet()) { jsonWr.addKeyValue(entry.getKey(), entry.getValue()[0]); } jsonWr.endMap(); } } // 将外部设置的参数保存 if(params != null && params.length > 0) { jsonWr.beginMap("params"); for(int i = 0; i < params.length; i += 2) { jsonWr.addKeyValue(params[i + 0], params[i + 1]); } jsonWr.endMap(); } } jsonWr.endMap(); return jsonWr; } public String getSessionId() throws Exception { return this.getSession().getId(); } protected void checkLoginFuncItem(SMTLoginFuncItem funcItem, List listFuncItem, boolean isRoot) throws Exception { if(funcItem._inited || funcItem._allowAuth == -1) return; funcItem._inited = true; funcItem._isRoot = isRoot; Object funcID = funcItem._funcID; boolean bIncAll = true; // 扫描当前项的子项 StringBuilder sbRegexBuilder = funcItem.getRegexBuilder(); for(SMTLoginFuncItem funcChild : listFuncItem) { // 如果当前选项已经初始化过,或不是本选项的子项则忽略 if(funcChild._inited || !(funcID.equals(funcChild._funcPID))) continue; // 如果子项中存在不和_allowAuth一致的项,则表示不包含所有项 if(funcItem._allowAuth != funcChild._allowAuth) { bIncAll = false; continue; } // 初始化当前项 checkLoginFuncItem(funcChild, listFuncItem, false); // 获取当前子项所拥有的正则表达式 // 将子项的正则加入父项 if(sbRegexBuilder.length() > 0) sbRegexBuilder.append("|"); // 如果子项已经属于分组,则将分组后的正则加入 if(funcChild.isRegexGroup()) { sbRegexBuilder.append(String.format("(?:%s)", funcChild._regexGroup)); } // 如果子项未属于分组信息,则将子项本身的正则加入,且标记父项未未分组 else { sbRegexBuilder.append(funcChild.getRegexBuilder().toString()); bIncAll = false; } } // 将本身的正则加入 if(sbRegexBuilder.length() > 0) sbRegexBuilder.append("|"); sbRegexBuilder.append(String.format("(?:%s)", funcItem._regex)); // 设置父项的group标志 funcItem.isRegexGroup(bIncAll); } public void clearWrapperMode() { _wrapperJson = null; _mapName2Params = null; _isWrapperMode = false; } public void setWrapperMode(Map mapName2Params) { _mapName2Params = mapName2Params; _isWrapperMode = true; } public Object jsGetReqParam(String name, String type, boolean required) throws Exception { SMTStatic.SMTConvType convType; char cType = type.charAt(0); switch(cType) { case 'S': convType = SMTStatic.SMTConvType.String; break; case 'D': convType = SMTStatic.SMTConvType.Double; break; case 'T': convType = SMTStatic.SMTConvType.Date; break; case 'I': convType = SMTStatic.SMTConvType.Integer; break; default: throw new Exception("unsupport param type : " + type); } Object ovalue = this.convParamToValue(name, convType, required ? SMTStatic.SMTConvEmpty.ErrorEmpty : SMTStatic.SMTConvEmpty.SkipEmpty, true); if(convType == SMTStatic.SMTConvType.Date) ovalue = SMTStatic.toString(ovalue); return ovalue; } public String[] convParamToStringArray(String paramName, boolean required) throws Exception { String value = convParamToString(paramName, false); if(value == null) { if(required) throw new Exception("not input param : " + paramName); else return null; } return value.split("\\,"); } public double[] convParamToDoubleArray(String paramName, boolean required) throws Exception { String[] sp = convParamToStringArray(paramName, required); if(sp == null) return null; double[] ret = new double[sp.length]; for(int i = 0; i < sp.length; i ++) { ret[i] = SMTStatic.toDouble(sp[i]); } return ret; } public int[] convParamToIntegerArray(String paramName, boolean required) throws Exception { String[] sp = convParamToStringArray(paramName, required); if(sp == null) return null; int[] ret = new int[sp.length]; for(int i = 0; i < sp.length; i ++) { ret[i] = SMTStatic.toInt(sp[i]); } return ret; } public Boolean convParamToBoolean(String paramName, boolean required) throws Exception { String value = (String) convParamToValue(paramName, SMTConvType.String, required ? SMTStatic.SMTConvEmpty.ErrorEmpty : SMTStatic.SMTConvEmpty.SkipEmpty, true); if(value == null) return null; if(value.equalsIgnoreCase("true")) return true; return false; } public String convParamToString(String paramName, boolean required) throws Exception { return (String) convParamToValue(paramName, SMTConvType.String, required ? SMTStatic.SMTConvEmpty.ErrorEmpty : SMTStatic.SMTConvEmpty.SkipEmpty, true); } public Integer convParamToInteger(String paramName, boolean required) throws Exception { return (Integer) convParamToValue(paramName, SMTConvType.Integer, required ? SMTStatic.SMTConvEmpty.ErrorEmpty : SMTStatic.SMTConvEmpty.SkipEmpty, true); } public Double convParamToDouble(String paramName, boolean required) throws Exception { return (Double) convParamToValue(paramName, SMTConvType.Double, required ? SMTStatic.SMTConvEmpty.ErrorEmpty : SMTStatic.SMTConvEmpty.SkipEmpty, true); } public Date convParamToDate(String paramName, boolean required) throws Exception { return (Date) convParamToValue(paramName, SMTConvType.Date, required ? SMTStatic.SMTConvEmpty.ErrorEmpty : SMTStatic.SMTConvEmpty.SkipEmpty, true); } public Json convParamToJson(String paramName, boolean required) throws Exception { String sJson = convParamToString(paramName, required); if(SMTStatic.isNullOrEmpty(sJson)) return null; return Json.read(sJson); } }