[java] Spring: How to get parameters from POST body?

Web-service using spring in which I have to get the params from the body of my post request? The content of the body is like:-

source=”mysource”

&json=
{
    "items": [
        {
            "username": "test1",
            "allowed": true
        },
        {
            "username": "test2",
            "allowed": false
        }
    ]
}

And the web-service method looks like:-

@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Boolean> saveData(@RequestBody String a) throws MyException {
        return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a),HttpStatus.OK);

    }

Please let me know how do I get the params from the body? I can get the whole body in my string but I don't think that would be a valid approach. Please let me know how do I proceed further.

This question is related to java spring rest spring-mvc

The answer is


You will need these imports...

import javax.servlet.*;
import javax.servlet.http.*;

And, if you're using Maven, you'll also need this in the dependencies block of the pom.xml file in your project's base directory.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then the above-listed fix by Jason will work:

@ResponseBody
    public ResponseEntity<Boolean> saveData(HttpServletRequest request,
        HttpServletResponse response, Model model){
        String jsonString = request.getParameter("json");
    }

You can try using @RequestBodyParam

@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
    ...
}

https://github.com/LambdaExpression/RequestBodyParam


You can get entire post body into a POJO. Following is something similar

@RequestMapping(
    value = { "/api/pojo/edit" }, 
    method = RequestMethod.POST, 
    produces = "application/json", 
    consumes = ["application/json"])
@ResponseBody
public Boolean editWinner( @RequestBody Pojo pojo) { 

Where each field in Pojo (Including getter/setters) should match the Json request object that the controller receives..


In class do like this

@RequestMapping(value = "/saveData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(
    HttpServletResponse response,
    Bean beanName
) throws MyException {
    return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a), HttpStatus.OK);
}

In page do like this:

<form enctype="multipart/form-data" action="<%=request.getContextPath()%>/saveData" method="post" name="saveForm" id="saveForm">
<input type="text" value="${beanName.userName }" id="username" name="userName" />

</from>

You can bind the json to a POJO using MappingJacksonHttpMessageConverter . Thus your controller signature can read :-

  public ResponseEntity<Boolean> saveData(@RequestBody RequestDTO req) 

Where RequestDTO needs to be a bean appropriately annotated to work with jackson serializing/deserializing. Your *-servlet.xml file should have the Jackson message converter registered in RequestMappingHandler as follows :-

  <list >
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

  </list>
</property>
</bean>

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)