2 years ago

#66877

test-img

Aman Kush

I am facing an issue wgere empty string getting converted to null when passed in request body with RestController SpringBoot

I am facing a strange issue, I have a controller and I have a method which handles put request. The code for controller looks like this:


@RestController
@RequestMapping("/test")
public class TestController {

    @PutMapping(path = "/test/service")
    public Result test(
            @RequestBody TestObject testObj) {
        log.info("Received  request with data {}", testObj.toString());
        try {
            String data = "get from service";
            if (data != null) {
                Result result = new Result();
                result.setSuccess(true);

                result.setSuccessResult(response);
                return result;
            } 
        }

    }

Here is my testObject:

@JsonIgnoreProperties(ignoreUnknown=true)
public class TestObj { 
    
    @NotNull(message = "Should not be null")
    private Integer sequence;
    
    private String message;
    
    private String userId;
}

Now when I make the following request:

curl --location -g --request PUT '{{baseUrl}}/test/test/service' \
--header 'Content-Type: application/json' \
--header 'Authorization: asdasdasdadadasdadadsadasa' \
--data-raw '{
    "sequence":1,
    "message":"  "
}'

I see that "message" field in TestObj is null in logs though I am passing an empty string. Here is a sample output:

TestController:xx - Received request with data TestObj [sequence=1, message=null, userId=null]

Can anyone help me with this?

Update

The solutions in the other link do not work for me.

Update 2

Interceptor code:

public class Interceptor implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        try {

            String ipAddress = request.getRemoteAddr();
            String url = ((HttpServletRequest) request).getRequestURL().toString();
            String body = extractPostRequestBody(req);
            ObjectMapper objectMapper = new ObjectMapper();
            TestObj testObj = objectMapper.readValue(body, TestObj.class);

            LOG.info("IP " + ipAddress + ", Time " + new Date().toString() + "  url " + url);
            LOG.info("Body: {}", body);
            LOG.info("Test Request: " + testObj);
}

String extractPostRequestBody(HttpServletRequest request) {
        if ("PUT".equalsIgnoreCase(request.getMethod())) {
            Scanner s = null;
            try {
                s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
            } catch (IOException e) {
                e.printStackTrace();
            }

            return s != null && s.hasNext() ? s.next() : "";
        }
        return "";
    }
}

java

spring-boot

annotations

spring-restcontroller

0 Answers

Your Answer

Accepted video resources