java通過HttpServletRequest獲取post請求中的body內(nèi)容的方法
在java web應(yīng)用中,我們?nèi)绾潍@取post請求body中的內(nèi)容?以及需要注意的問題。
通常利用request獲取參數(shù)可以直接通過req.getParameter(name)的方式獲取url上面或者ajax data提交上來的參數(shù)。但是body是沒有名字的,無法通過參數(shù)名字這種方式獲取。這時(shí)候需要用到io流的方式來獲取body中的內(nèi)容。
這里先貼出一段代碼:
package com.lenovo.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.alibaba.dubbo.common.utils.IOUtils;
import com.lenovo.service.BusinessService;
import com.lenovo.utils.WebContext;
public class BusinessServlet extends HttpServlet{
public static final Logger log = Logger.getLogger(BusinessServlet.class);
/**
*
*/
private static final long serialVersionUID = 1L;
private static BusinessService service;
static{
service = (BusinessService) WebContext.getBean("businessService");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
String body = IOUtils.read(reader);
String name = req.getParameter("name");
if(StringUtils.isNotBlank(body)){
log.info("business receive somthing with body :"+body);
}
res.setCharacterEncoding("UTF-8");
res.setContentType("application/json");
res.setStatus(HttpServletResponse.SC_OK);
res.getWriter().println(service.getName(name));
}
}
在這段代碼doPost方法中,用到了IO流來獲取post提交的body,這樣我們就獲取了客戶端提交的參數(shù)。
需要注意的是:獲取body參數(shù),需要在request.getParameter()方法之前調(diào)用(如果有需要取QueryString參數(shù)的話),因?yàn)橐坏┱{(diào)用了getParameter()方法之后,再通過IO流的方式獲取body參數(shù)就失效了(親測返回"")。
另外,這里使用了dubbo-2.5.3.jar的IOUtils.read(reader)方法來讀取post body的內(nèi)容。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java?fastjson傳輸long數(shù)據(jù)卻接收到了int的問題
這篇文章主要介紹了java?fastjson傳輸long數(shù)據(jù)卻接收到了int的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
Idea報(bào)錯(cuò): A JNI error has occurred的問題
這篇文章主要介紹了Idea報(bào)錯(cuò): A JNI error has occurred的問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Spring 開發(fā)之組件賦值的實(shí)現(xiàn)方法
這篇文章主要介紹了Spring 開發(fā)之組件賦值的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

