servlet获取get,post(json,form-date)三种请求参数

一,get

userCode = request.getParameter("userCode");

二,post(json)

if (userCode == null || "".equals(userCode)) {
			String jsonstr = CommonUtils.readJSONString(request);
			System.out.println(jsonstr);
			if (jsonstr != null || !"".equals(jsonstr)) {
				JSONObject jsonObject = JSONObject.parseObject(jsonstr);
				// 获取到key为shoppingCartItemList的值
				try {
					userCode = jsonObject.getString("userCode");
				} catch (NullPointerException e) {

					userCode = "-1";
					// TODO: handle exception
				}
				
			}
		}



public static String readJSONString(HttpServletRequest request){
		   StringBuffer json = new StringBuffer();
		   String line = null;
		   try {
		   BufferedReader reader = request.getReader();
		   while((line = reader.readLine()) != null) {
		   json.append(line);
		   }
		   }
		   catch(Exception e) {
		   System.out.println(e.toString());
		   }
		   return json.toString();
 }

三,post(form-date)

if ("-1".equals(userCode)) {
			List items = null;
			try {
				items = upload.parseRequest(request);
				Map params = new HashMap();
				if (items != null) {
					for (Object object : items) {
						FileItem fileItem = (FileItem) object;
						if (fileItem.isFormField()) {
							params.put(fileItem.getFieldName(),
									fileItem.getString("utf-8"));// 如果你页面编码是utf-8的
						}
					}
					// 使用params.get获取参数值
					userCode = (String) params.get("userCode");
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				userCode = "-1";
			}

		}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果POST请求中提交的参数JSON格式,可以通过以下步骤在Java Servlet获取: 1. 在Servlet的doPost方法中,通过HttpServletRequest对象获取POST请求中的JSON格式参数,并将参数转化为Java对象,示例代码如下: ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取POST请求中的JSON格式参数 BufferedReader reader = request.getReader(); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } String jsonString = sb.toString(); // 将参数转化为Java对象 ObjectMapper objectMapper = new ObjectMapper(); MyParam myParam = objectMapper.readValue(jsonString, MyParam.class); // ... } ``` 在上面的示例中,通过request.getReader()方法获取POST请求中的字符流,然后将字符流转化为JSON格式字符串。接着,使用Jackson库中的ObjectMapper类将JSON格式字符串转化为Java对象。 2. 在前端页面中,使用Ajax向Servlet提交POST请求,并传递JSON格式参数,示例代码如下: ``` var myParam = { "param1": "value1", "param2": "value2" }; $.ajax({ type: "POST", url: "/servlet/MyServlet", contentType: "application/json", data: JSON.stringify(myParam), success: function(data) { // ... } }); ``` 在上面的示例中,通过contentType属性指定请求数据类型为JSON格式,使用JSON.stringify方法将JavaScript对象转化为JSON格式字符串,然后将JSON格式字符串作为请求参数传递给Servlet
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值