In a java web application, how do we get the content in the post request body? And issues that need to be paid attention to.
Usually, using request to obtain parameters can directly obtain parameters submitted by url or ajax data through req.getParameter(name). However, the body has no name and cannot be obtained through parameter names. At this time, you need to use the io stream to get the content in the body.
Here is a code:
package com.lenovo.servlet;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import javax.servlet.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 something with body :"+body); } res.setCharacterEncoding("UTF-8"); res.setContentType("application/json"); res.setStatus(HttpServletResponse.SC_OK); res.getWriter().println(service.getName(name)); } } In this code doPost method, IO stream is used to obtain the post submitted body, so we get the parameters submitted by the client.
It should be noted that: to obtain the body parameters, you need to call it before the request.getParameter() method (if you need to take the QueryString parameter), because once the getParameter() method is called, the body parameters are obtained through IO streams will be invalid (return "" for personal tests).
In addition, the IOUtils.read(reader) method of dubbo-2.5.3.jar is used here to read the content of the post body.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.