WARN 4304 Required String parameter is not present

In a rest call, request parameter can be made as mandatory by setting required=true. If a parameter is mandatory and the parameter value is not received by restcontroller, then this warning message is thrown in the application. Browser shows as “There was an unexpected error (type=Bad Request, status=400).”



Exception

2019-10-03 17:40:07.516  WARN 4304 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present]

Error Message

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 03 17:42:47 IST 2019
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'name' is not present 


How to reproduce this issue

In Spring Boot Application, create a rest controller class. Create a method with a @Requestparam as a parameter in the rest controller class. Configure the request param as required=true. Now call this rest url without passing value to this request param.

package com.yawintutor;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

	@GetMapping("HelloWorld")
	public Message firstPage(@RequestParam(name = "name", required = true) String name) {
		return new Message(1, "Welcome to "+name+"!");
	}
	
}


Root Cause

Rest Controller method is configured with mandatory request parameter. If the url does not provide the mandatory request parameter, spring boot throws this warning.



Solution 1

In the rest controller, set @Requestparam(required=false). RestController will not force to send request param

	@GetMapping("HelloWorld")
	public Message firstPage(@RequestParam(name = "name", required = false) String name) {
		return new Message(1, "Welcome to "+name+"!");
	}


Solution 2

In the rest controller, set default value to the request param as @Requestparam(required=false, defaultValue = “Unknown”). The default value is assigned if the request parameter is not available in the url.

	@GetMapping("HelloWorld")
	public Message firstPage(@RequestParam(name = "name", required = false, default="unknown") String name) {
		return new Message(1, "Welcome to "+name+"!");
	}


Solution 3

In the request url, send the requested parameter with value as expected.

http://localhost:8080/HelloWorld?name=yawin



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *