HttpServletRequest 工具类

Posted fuhengheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpServletRequest 工具类相关的知识,希望对你有一定的参考价值。

  1 package com.gta.yyyf.commons.utils;
  2 
  3 import java.io.UnsupportedEncodingException;
  4 import java.net.URLDecoder;
  5 import java.util.Enumeration;
  6 import java.util.HashMap;
  7 import java.util.Map;
  8 import java.util.StringTokenizer;
  9 
 10 import javax.servlet.http.HttpServletRequest;
 11 
 12 import org.apache.commons.lang3.StringUtils;
 13 import org.apache.commons.logging.Log;
 14 import org.apache.commons.logging.LogFactory;
 15 
 16 /**
 17  * 
 18  * 功能描述:HttpServletRequest 工具类
 19  *
 20  * @author biyun.huang
 21  *
 22  *         <p>
 23  *         修改历史:(修改人,修改时间,修改原因/内容)
 24  *         </p>
 25  */
 26 public class RequestUtils {
 27 
 28     private static final Log logger = LogFactory.getLog(RequestUtils.class);
 29     public static final String POST = "POST";
 30 
 31     public static final String UTF8 = "UTF-8";
 32     public static final String GET = "GET";
 33 
 34     /**
 35      * 获取QueryString的参数,并使用URLDecoder以UTF-8格式转码。如果请求是以post方法提交的,
 36      * 那么将通过HttpServletRequest#getParameter获取。
 37      * 
 38      * @param request
 39      *            web请求
 40      * @param name
 41      *            参数名称
 42      * @return
 43      */
 44     public static String getQueryParam(HttpServletRequest request, String name) {
 45         if (StringUtils.isBlank(name)) {
 46             return null;
 47         }
 48         if (request.getMethod().equalsIgnoreCase(POST)) {
 49             return request.getParameter(name);
 50         }
 51         String s = request.getQueryString();
 52         if (StringUtils.isBlank(s)) {
 53             return null;
 54         }
 55         try {
 56             s = URLDecoder.decode(s, UTF8);
 57         } catch (UnsupportedEncodingException e) {
 58             logger.error("encoding " + UTF8 + " not support?", e);
 59         }
 60         String[] values = parseQueryString(s).get(name);
 61         if (values != null && values.length > 0) {
 62             return values[values.length - 1];
 63         } else {
 64             return null;
 65         }
 66     }
 67 
 68     public static Map<String, Object> getQueryParams(HttpServletRequest request) {
 69         Map<String, String[]> map;
 70         if (request.getMethod().equalsIgnoreCase(POST)) {
 71             map = request.getParameterMap();
 72         } else {
 73             String s = request.getQueryString();
 74             if (StringUtils.isBlank(s)) {
 75                 return new HashMap<String, Object>();
 76             }
 77             try {
 78                 s = URLDecoder.decode(s, UTF8);
 79             } catch (UnsupportedEncodingException e) {
 80                 logger.error("encoding " + UTF8 + " not support?", e);
 81             }
 82             map = parseQueryString(s);
 83         }
 84 
 85         Map<String, Object> params = new HashMap<String, Object>(map.size());
 86         int len;
 87         for (Map.Entry<String, String[]> entry : map.entrySet()) {
 88             len = entry.getValue().length;
 89             if (len == 1) {
 90                 params.put(entry.getKey(), entry.getValue()[0]);
 91             } else if (len > 1) {
 92                 params.put(entry.getKey(), entry.getValue());
 93             }
 94         }
 95         return params;
 96     }
 97 
 98     /**
 99      * 
100      * Parses a query string passed from the client to the server and builds a
101      * <code>HashTable</code> object with key-value pairs. The query string
102      * should be in the form of a string packaged by the GET or POST method,
103      * that is, it should have key-value pairs in the form <i>key=value</i>,
104      * with each pair separated from the next by a &amp; character.
105      * 
106      * <p>
107      * A key can appear more than once in the query string with different
108      * values. However, the key appears only once in the hashtable, with its
109      * value being an array of strings containing the multiple values sent by
110      * the query string.
111      * 
112      * <p>
113      * The keys and values in the hashtable are stored in their decoded form, so
114      * any + characters are converted to spaces, and characters sent in
115      * hexadecimal notation (like <i>%xx</i>) are converted to ASCII characters.
116      * 
117      * @param s
118      *            a string containing the query to be parsed
119      * 
120      * @return a <code>HashTable</code> object built from the parsed key-value
121      *         pairs
122      * 
123      * @exception IllegalArgumentException
124      *                if the query string is invalid
125      * 
126      */
127     public static Map<String, String[]> parseQueryString(String s) {
128         String valArray[] = null;
129         if (s == null) {
130             throw new IllegalArgumentException();
131         }
132         Map<String, String[]> ht = new HashMap<String, String[]>();
133         StringTokenizer st = new StringTokenizer(s, "&");
134         while (st.hasMoreTokens()) {
135             String pair = (String) st.nextToken();
136             int pos = pair.indexOf(‘=‘);
137             if (pos == -1) {
138                 continue;
139             }
140             String key = pair.substring(0, pos);
141             String val = pair.substring(pos + 1, pair.length());
142             if (ht.containsKey(key)) {
143                 String oldVals[] = (String[]) ht.get(key);
144                 valArray = new String[oldVals.length + 1];
145                 for (int i = 0; i < oldVals.length; i++) {
146                     valArray[i] = oldVals[i];
147                 }
148                 valArray[oldVals.length] = val;
149             } else {
150                 valArray = new String[1];
151                 valArray[0] = val;
152             }
153             ht.put(key, valArray);
154         }
155         return ht;
156     }
157 
158     public static Map<String, String> getRequestMap(HttpServletRequest request,
159             String prefix) {
160         return getRequestMap(request, prefix, false);
161     }
162 
163     public static Map<String, String> getRequestMapWithPrefix(
164             HttpServletRequest request, String prefix) {
165         return getRequestMap(request, prefix, true);
166     }
167 
168     private static Map<String, String> getRequestMap(
169             HttpServletRequest request, String prefix, boolean nameWithPrefix) {
170         Map<String, String> map = new HashMap<String, String>();
171         Enumeration<String> names = request.getParameterNames();
172         String name, key, value;
173         while (names.hasMoreElements()) {
174             name = names.nextElement();
175             if (name.startsWith(prefix)) {
176                 key = nameWithPrefix ? name : name.substring(prefix.length());
177                 value = StringUtils.join(request.getParameterValues(name), ‘,‘);
178                 map.put(key, value);
179             }
180         }
181         return map;
182     }
183 
184     /**
185      * 获取访问者IP
186      * 
187      * 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效??
188      * 
189      * 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(??分割)??
190      * 如果还不存在则调用Request .getRemoteAddr()??
191      * 
192      * @param request
193      * @return
194      */
195     public static String getIpAddr(HttpServletRequest request) {
196         String ip = request.getHeader("X-Real-IP");
197         if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
198             return ip;
199         }
200         ip = request.getHeader("X-Forwarded-For");
201         if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
202 
203             int index = ip.indexOf(‘,‘);
204             if (index != -1) {
205                 return ip.substring(0, index);
206             } else {
207                 return ip;
208             }
209         } else {
210             return request.getRemoteAddr();
211         }
212     }
213 
214     @SuppressWarnings("unused")
215     private static String cleanXSS(String value) {
216         // You‘ll need to remove the spaces from the html entities below
217         value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
218         value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
219         value = value.replaceAll("‘", "&#39;");
220         value = value.replaceAll("\"", "&quot;");// by:wgc
221         value = value.replaceAll("eval\\((.*)\\)", "");
222         value = value.replaceAll("[\\\"\\\‘][\\s]*javascript:(.*)[\\\"\\\‘]",
223                 "\"\"");
224         value = value.replaceAll("script", "");
225         return value;
226     }
227 
228     public static String[] getQueryParamValues(HttpServletRequest request,
229             String name) {
230         if (StringUtils.isBlank(name)) {
231             return null;
232         }
233         if (request.getMethod().equalsIgnoreCase(POST)) {
234             return request.getParameterValues(name);
235         } else {
236             return null;
237         }
238     }
239 
240     public static void main(String[] args) {
241         try {
242             System.out.println(URLDecoder.decode("%E6%B7%B1%E5%9C%B3", UTF8));
243         } catch (UnsupportedEncodingException e) {
244             logger.error(e);
245             e.printStackTrace();
246         }
247     }
248 }

 

以上是关于HttpServletRequest 工具类的主要内容,如果未能解决你的问题,请参考以下文章

JAVA 普通类中怎么调用HTTPSERVLETRequest

HttpServletResponse工具类和HttpServletRequest工具类,前台参数接收方式和后台返回(JSON)数据格式

15Java常用类(数组工具类Arrays)基本类型包装类(Integer类)正则表达式String的split(String regex)和replaceAll(String regex, (代码片

Spring BootSpringBoot 如何保证接口安全?老鸟们都是这么玩的!

代码片--练习匿名内部类

HttpServletRequest类