I am a java white, in a recent development, there is such a task, intercepts the request, unified verification token of the request, for special reasons, works in all post request. Think of interceptors, Filter, aop.
Due to the requirement to make use of spring assemblies, therefore exclude Filter, due URL works there is no uniform standard, so aop also excluded, and finally the use of interceptors, the use of the process Required request body is missing error occurs, through the search data found request used to obtain the parameters body get in the flow, but the request flow can only be used once, it is to give way to replicate before obtaining flow convection. See the following specific implementation code.
1: First, define a class that inherits from HttpServletRequestWrapper, for backup stream
public class BufferedServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] buffer;
public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
InputStream is = request.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int read;
while ((read = is.read(buff)) > 0) {
baos.write(buff, 0, read);
}
this.buffer = baos.toByteArray();
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new BufferedServletInputStream(this.buffer);
}
// provide external flow reading method
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
2: custom interceptor spring assembly in the configuration file
<mvc:interceptors>
<-! Token check ->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<Bean class = "full path category">
<property name="excludeMapping">
<list>
<value>/doctorWebLoginAccount/doctorLogin/app</value>
<value>/doctorWebLoginAccount/doctorLogin/web</value>
<value>/ws</value>
<value>/fileUpload/uploadPicture</value>
<value>/fileUpload/uploadSignature</value>
<value>/doctor/registe</value>
<value>/hospitalAndDepartment/findHospital</value>
<value>/hospitalAndDepartment/findDepartment</value>
<value>/hospDoctorTreatment/usageSelect</value>
<value>/chiefComplaint/symptom</value>
<value>/initialDiagnose/list</value>
<value>/doctor/patientInfo</value>
<value>/doctor/updateAccountInfo</value>
<value>/doctor/getMessageCode</value>
<value>/doctor/storeBaseInfo</value>
<value>/doctor/storeBaseGoods/list</value>
<value>/doctor/checkPhoneNum</value>
<value>/storeBaseGoods/pageList</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
3: Define interception implementation class
public class ValidateTokenInterceptor implements HandlerInterceptor{
// not intercepted request
private String[] excludeMapping;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// do not need filtered requests
for(String exclude : excludeMapping){
if(request.getRequestURI().endsWith(exclude)){
return true;
}
}
BufferedServletRequestWrapper requestWrapper = new BufferedServletRequestWrapper(request);
Alternatively // stream, using tools GetRequestJsonUtils parameters acquired here json
JSONObject json = GetRequestJsonUtils.getRequestJsonObject(requestWrapper);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.info ( "before returning to the view!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.info ( "After the request!");
}
public void setExcludeMapping(String[] excludeMapping) {
this.excludeMapping = excludeMapping;
}
}
4: Finally a custom Filter (sequential execution request is chained spring Filter -> Blocker -> controller) for backup stream
public class TranslateRequestWrapper implements Filter{
/**
* Destruction
*/
@Override
public void destroy() {
}
/**
* Filter
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
ServletRequest requestWrapepr = null;
if(request instanceof HttpServletRequest){
requestWrapepr = new BufferedServletRequestWrapper((HttpServletRequest)request);
}
if(requestWrapepr == null){
chain.doFilter(request, response);
}else{
chain.doFilter(requestWrapepr, response);
}
}
/**
* Initialization
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
5: Attach tools read parameter from the stream
public class GetRequestJsonUtils {
public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
String json = getRequestJsonString(request);
return JSONObject.parseObject(json);
}
/***
* Get the content request in json string
*
* @param request
* @return : <code>byte[]</code>
* @throws IOException
*/
public static String getRequestJsonString(HttpServletRequest request)
throws IOException {
String submitMehtod = request.getMethod();
// GET
if (submitMehtod.equals("GET")) {
if(StringUtils.isNotEmpty(request.getQueryString())){
return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
}else{
return new String("".getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\"");
}
// POST
} else {
return getRequestPostStr(request);
}
}
/**
* Description: Gets the requested byte post [] array
* <pre>
* For example:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
/**
* Description: Get post content request
* <pre>
* For example:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static String getRequestPostStr(HttpServletRequest request)
throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
}
So there is no request body si missing
First, the use getReader () Gets body Second, the use getInputStream () Gets body Third, the difference between the two: Using the getInputStream () may specify their own e...
Operation request body 1.1 Get the request parameters Nomist String getParameter(String name) Get the value corresponding to the specified parameter name. Returns NULL if not If there are multiple fir...
Spring common problem solving -Required Request Body is missing Foreword 1. Case reproduction 2. Principles analysis 3. Problem solution 3.1 Custom adapter replace the filter 3.2 Packaging flow and re...
1. Background requirements Send a Get request, but the request parameters should be placed in the request body, so the following code is sorted out after multiple verifications. 2. POM dependency 3. S...
1. Request body parameter analysis: 1.1 GET request 1.1.1 The /?xxx&xx format in the request url is the query st...
The dubbo package of alibaba needs to be introduced...
During the test today, I found that there is a strange post request. The parameter name in the url is the same as the parameter name in the body request body. So will the value of the parameter obtain...
Form parameter It is to change the string parameter GET to POST Non-form pass parameters. It is json parameter transmission Among them, pay attention to request.body request.body is a binary ty...
Previous articleWe completed the basic interaction between the Node.js client and the server, and passed the client parameters through get requests, and the server processed the data with correspondin...