HttpServletResponse工具类和HttpServletRequest工具类,前台参数接收方式和后台返回(JSON)数据格式
RequestUtils.java 操作类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | package cn.utils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.util.UrlPathHelper; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * HttpServletRequest 工具类 */ public class RequestUtils { private static final Logger log = LoggerFactory .getLogger(RequestUtils. class ); /** * HTTP POST请求 */ public static final String POST = "POST" ; /** * UTF-8编码 */ public static final String UTF8 = "UTF-8" ; /** * 获取QueryString的参数,并使用URLDecoder以UTF-8格式转码。如果请求是以post方法提交的, * 那么将通过HttpServletRequest#getParameter获取。 * * @param request * web请求 * @param name * 参数名称 * @return */ public static String getQueryParam(HttpServletRequest request, String name) { if (StringUtils.isBlank(name)) { return null ; } if (request.getMethod().equalsIgnoreCase(POST)) { return request.getParameter(name); } String s = request.getQueryString(); if (StringUtils.isBlank(s)) { return null ; } try { s = URLDecoder.decode(s, UTF8); } catch (UnsupportedEncodingException e) { log.error( "encoding " + UTF8 + " not support?" , e); } String[] values = parseQueryString(s).get(name); if (values != null && values.length > 0 ) { return values[values.length - 1 ]; } else { return null ; } } @SuppressWarnings ( "unchecked" ) public static Map<String, Object> getQueryParams(HttpServletRequest request) { Map<String, String[]> map; if (request.getMethod().equalsIgnoreCase(POST)) { map = request.getParameterMap(); } else { String s = request.getQueryString(); if (StringUtils.isBlank(s)) { return new HashMap<String, Object>(); } try { s = URLDecoder.decode(s, UTF8); } catch (UnsupportedEncodingException e) { log.error( "encoding " + UTF8 + " not support?" , e); } map = parseQueryString(s); } Map<String, Object> params = new HashMap<String, Object>(map.size()); int len; for (Map.Entry<String, String[]> entry : map.entrySet()) { len = entry.getValue().length; if (len == 1 ) { params.put(entry.getKey(), entry.getValue()[ 0 ]); } else if (len > 1 ) { params.put(entry.getKey(), entry.getValue()); } } return params; } /** * * Parses a query string passed from the client to the server and builds a * <code>HashTable</code> object with key-value pairs. The query string * should be in the form of a string packaged by the GET or POST method, * that is, it should have key-value pairs in the form <i>key=value</i>, * with each pair separated from the next by a & character. * * <p> * A key can appear more than once in the query string with different * values. However, the key appears only once in the hashtable, with its * value being an array of strings containing the multiple values sent by * the query string. * * <p> * The keys and values in the hashtable are stored in their decoded form, so * any + characters are converted to spaces, and characters sent in * hexadecimal notation (like <i>%xx</i>) are converted to ASCII characters. * * @param s * a string containing the query to be parsed * * @return a <code>HashTable</code> object built from the parsed key-value * pairs * * @exception IllegalArgumentException * if the query string is invalid * */ public static Map<String, String[]> parseQueryString(String s) { String valArray[] = null ; if (s == null ) { throw new IllegalArgumentException(); } Map<String, String[]> ht = new HashMap<String, String[]>(); StringTokenizer st = new StringTokenizer(s, "&" ); while (st.hasMoreTokens()) { String pair = (String) st.nextToken(); int pos = pair.indexOf( '=' ); if (pos == - 1 ) { continue ; } String key = pair.substring( 0 , pos); String val = pair.substring(pos + 1 , pair.length()); if (ht.containsKey(key)) { String oldVals[] = (String[]) ht.get(key); valArray = new String[oldVals.length + 1 ]; for ( int i = 0 ; i < oldVals.length; i++) { valArray[i] = oldVals[i]; } valArray[oldVals.length] = val; } else { valArray = new String[ 1 ]; valArray[ 0 ] = val; } ht.put(key, valArray); } return ht; } public static Map<String, String> getRequestMap(HttpServletRequest request, String prefix) { return getRequestMap(request, prefix, false ); } public static Map<String, String> getRequestMapWithPrefix( HttpServletRequest request, String prefix) { return getRequestMap(request, prefix, true ); } @SuppressWarnings ( "unchecked" ) private static Map<String, String> getRequestMap( HttpServletRequest request, String prefix, boolean nameWithPrefix) { Map<String, String> map = new HashMap<String, String>(); Enumeration<String> names = request.getParameterNames(); String name, key, value; while (names.hasMoreElements()) { name = names.nextElement(); if (name.startsWith(prefix)) { key = nameWithPrefix ? name : name.substring(prefix.length()); value = StringUtils.join(request.getParameterValues(name), ',' ); map.put(key, value); } } return map; } /** * 获取访问者IP * * 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。 * * 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割), * 如果还不存在则调用Request .getRemoteAddr()。 * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader( "X-Real-IP" ); if (!StringUtils.isBlank(ip) && ! "unknown" .equalsIgnoreCase(ip)) { if (ip.contains( "../" )||ip.contains( "..\\" )){ return "" ; } return ip; } ip = request.getHeader( "X-Forwarded-For" ); if (!StringUtils.isBlank(ip) && ! "unknown" .equalsIgnoreCase(ip)) { // 多次反向代理后会有多个IP值,第一个为真实IP。 int index = ip.indexOf( ',' ); if (index != - 1 ) { ip= ip.substring( 0 , index); } if (ip.contains( "../" )||ip.contains( "..\\" )){ return "" ; } return ip; } else { ip=request.getRemoteAddr(); if (ip.contains( "../" )||ip.contains( "..\\" )){ return "" ; } if (ip.equals( "0:0:0:0:0:0:0:1" )){ ip= "127.0.0.1" ; } return ip; } } /** * 获得当的访问路径 * * HttpServletRequest.getRequestURL+"?"+HttpServletRequest.getQueryString * * @param request * @return */ public static String getLocation(HttpServletRequest request) { UrlPathHelper helper = new UrlPathHelper(); StringBuffer buff = request.getRequestURL(); String uri = request.getRequestURI(); String origUri = helper.getOriginatingRequestUri(request); buff.replace(buff.length() - uri.length(), buff.length(), origUri); String queryString = helper.getOriginatingQueryString(request); if (queryString != null ) { buff.append( "?" ).append(queryString); } return buff.toString(); } public static Map<String,String> getSignMap(HttpServletRequest request){ Map<String,String>param= new HashMap<String, String>(); Enumeration penum=(Enumeration) request.getParameterNames(); while (penum.hasMoreElements()){ String pKey=(String) penum.nextElement(); String value=request.getParameter(pKey); //sign和uploadFile不参与 值为空也不参与 if (!pKey.equals( "sign" )&&!pKey.equals( "uploadFile" ) &&StringUtils.isNotBlank(value)){ param.put(pKey,value); } } return param; } public static void main(String[] args) { } } |
ResponseUtils.java 操作类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | package cn.utils; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpServletResponse 工具类 */ public final class ResponseUtils { public static final Logger log = LoggerFactory .getLogger(ResponseUtils. class ); /** * 发送文本。使用UTF-8编码。 * * @param response * HttpServletResponse * @param text * 发送的字符串 */ public static void renderText(HttpServletResponse response, String text) { render(response, "text/plain;charset=UTF-8" , text); } /** * 发送json。使用UTF-8编码。 * * @param response * HttpServletResponse * @param text * 发送的字符串 */ public static void renderJson(HttpServletResponse response, String text) { render(response, "application/json;charset=UTF-8" , text); } /** * 发送xml。使用UTF-8编码。 * * @param response * HttpServletResponse * @param text * 发送的字符串 */ public static void renderXml(HttpServletResponse response, String text) { render(response, "text/xml;charset=UTF-8" , text); } /** * 发送内容。使用UTF-8编码。 * * @param response * @param contentType * @param text */ public static void render(HttpServletResponse response, String contentType, String text) { response.setContentType(contentType); response.setHeader( "Pragma" , "No-cache" ); response.setHeader( "Cache-Control" , "no-cache" ); response.setDateHeader( "Expires" , 0 ); try { response.getWriter().write(text); } catch (IOException e) { log.error(e.getMessage(), e); } } public static void renderApiJson(HttpServletResponse response, HttpServletRequest request,ApiResponse apiResult) { //js跨域请求 String callback = request.getParameter( "callback" ); if (StringUtils.isNotBlank(callback)){ ResponseUtils.renderJson(response,callback+ "(" + apiResult.toString() + ")" ); } else { ResponseUtils.renderJson(response, apiResult.toString()); } } } |
ApiResponse.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package cn.utils; public class ApiResponse { public ApiResponse(String body, String message, String status) { super (); this .body = body; this .message = message; this .status = status; } /** * 返回信息主体 */ public String getBody() { return body; } public void setBody(String body) { this .body = body; } /** * API调用提示信息 */ public String getMessage() { return message; } public void setMessage(String message) { this .message = message; } /** * API接口调用状态 */ public String getStatus() { return status; } public void setStatus(String status) { this .status = status; } @Override public String toString() { return "{\"body\":" + body + ", \"message\":" + message + ",\"status\":" + status + "}" ; } private String body; private String message; private String status; } |
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了