当前位置:   article > 正文

从HttpServletRequest获取参数_application/json 获取参数

application/json 获取参数

如何从HttpServletRequest中获取参数

package com.game.common.http.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONObject;


/**
 * 公共的action
 * 
 * @author administrator
 *
 */
public abstract class BaseActionServlet {


	/**
	 * 获取Ip
	 * 
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * 回传参数
	 * 
	 * @param response
	 * @param code
	 * @param message
	 */
	public static void responseCode(HttpServletResponse response, String code, String message) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			JSONObject json = new JSONObject();
			json.put("code", code);
			json.put("message", message);
			out.print(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 回传参数
	 * 
	 * @param response
	 * @param code
	 * @param message
	 */
	public static void responseCode(HttpServletResponse response, int code, String message) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			JSONObject json = new JSONObject();
			json.put("code", code);
			json.put("message", message);
			out.print(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 回传参数
	 * 
	 * @param response
	 * @param code
	 * @param message
	 */
	public static void responseCode(HttpServletResponse response, Map<String, String> params, int code,
			String message) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			JSONObject json = new JSONObject();
			json.put("code", code);
			json.put("message", message);

			if (null != params) {
				params.forEach((k, v) -> {
					json.put(k, v);
				});
			}

			out.print(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 回传参数
	 * 
	 * @param resp
	 *            回传类
	 * @param data
	 *            回传数据
	 * @throws IOException
	 */
	public static void responseData(HttpServletResponse response, String data) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print(data);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 回传参数
	 * 
	 * @param resp
	 * @param errorCode
	 *            错误码
	 * @throws IOException
	 */
	public static void responseData(HttpServletResponse response, int errorCode) {
		JSONObject json = new JSONObject();
		json.put("Result", 0);
		json.put("ErrorCode", errorCode);
		responseData(response, json.toString());
	}

	/**
	 * 回传参数
	 * 
	 * @param resp
	 * @param code
	 *            状态码
	 * @throws IOException
	 */
	public static void responseCode(HttpServletResponse response, int code) {
//		JSONObject json = new JSONObject();
//		json.put("code", code);
		String str="{\"code\":"+code+"}";
		responseData(response, str);
	}

	/**
	 * 回传参数
	 * 
	 * @param resp
	 * @param errorCode
	 *            错误码
	 * @throws IOException
	 */
	public static void responseDataSuccess(HttpServletResponse response) {
		JSONObject json = new JSONObject();
		json.put("Result", 1);
		json.put("ErrorCode", 1);
		responseData(response, json.toString());
	}

	/**
	 * 回传参数,data参数格式key1,value1,key2,value2,key3,value3.....,数据会自动封装成json
	 * 
	 * @param resp
	 * @param data
	 *            格式key1,value1,key2,value2,key3,value3.....
	 * @throws IOException
	 */
	public static void responseDatas(HttpServletResponse resp, String... data) {
		JSONObject json = new JSONObject();
		if (null != data && data.length > 0) {
			for (int i = 0; i < data.length; i = i + 2) {
				json.put(data[i], data[i + 1]);
			}
		}
		responseData(resp, json.toString());
	}
	
	
	/**
	 * 回传参数
	 * 
	 * @param resp
	 *            回传类
	 * @param data
	 *            json回传数据
	 * @throws IOException
	 */
	public static void responseData(HttpServletResponse response, JSONObject data) {
		String str="";
		if(null!=data){
			str=data.toString();
		}
		responseData(response,str);
	}
	

	/**
	 * 将参数字符串转换为Map<paramKey,paramValue> eg.
	 * xxKey=xxValue&yyKey=yyValue&zzKey=zzValue -->
	 * Map{xxKey=xxValue,yyKey=yyValue,zzKey=zzValue}
	 * 
	 * @param request
	 *            要转换的字符串
	 * @param bools
	 *            是否第一次读取参数(true 非第一读取参数返回现有paramMap , 空值或false 重新读取paramMap)
	 * @return Map
	 * @throws UnsupportedEncodingException
	 * @throws FileUploadException 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> getParameters(HttpServletRequest request) throws UnsupportedEncodingException {

		// 参数Map
		Map<String, String[]> properties = request.getParameterMap();
		// 返回值Map
		Map<String, String> returnMap = new HashMap<String, String>();
		Iterator<?> entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = null;
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {

			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString().trim();
			}
			returnMap.put(name, value);
		}

		return returnMap;
	}

	/**
	 * 将参数字符串转换为Map<paramKey,paramValue> eg.
	 * xxKey=xxValue&yyKey=yyValue&zzKey=zzValue -->
	 * Map{xxKey=xxValue,yyKey=yyValue,zzKey=zzValue}
	 * 
	 * (处理multipart/form-data类型的表单请求)
	 * @param request
	 *            要转换的字符串
	 * @param bools
	 *            是否第一次读取参数(true 非第一读取参数返回现有paramMap , 空值或false 重新读取paramMap)
	 * @return Map
	 * @throws UnsupportedEncodingException
	 * @throws FileUploadException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> getParametersForMultipartFormData(HttpServletRequest request)
			throws UnsupportedEncodingException, FileUploadException {
		Map<String, String> returnMap = new HashMap<String, String>();
		
		// 返回值Map
		// 文件上传的三部曲
		// 创建工厂
		DiskFileItemFactory factoy = new DiskFileItemFactory();
		// 创建解析器
		ServletFileUpload sfu = new ServletFileUpload(factoy);
		// 设置上传文件的大小
		sfu.setFileSizeMax(20 * 1024);
		// 解析request
		List<FileItem> list = sfu.parseRequest(request);

		// 只处理非文件内容
		for (FileItem fi : list) {
			if (fi.isFormField()) {//只要普通字段,不要文件
				returnMap.put(fi.getFieldName(), fi.getString());
			}
		}
		return returnMap;
	}
	
	/**
	 * 获取参数
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws FileUploadException
	 */
	public static Map<String, String> getParams(HttpServletRequest request) throws UnsupportedEncodingException, FileUploadException{
		Map<String,String> params=getParameters(request);
		if(params.size()>0){
			return params;
		}
		return getParametersForMultipartFormData(request);
	}
	

}
  • 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
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331

方法:
public static Map<String, String> getParameters(HttpServletRequest request);
解释:从request.getParameterMap()里获取请求参数
在这里插入图片描述

方法:
public static Map<String, String> getParametersForMultipartFormData(HttpServletRequest request);
解释:通过上传解析器的形式发送请求参数
在这里插入图片描述

传送门

获取body里的请求内容

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/309935
推荐阅读
相关标签
  

闽ICP备14008679号