Spring MVC - Custom Data binding with @RequestParam example

[Updated: Dec 28, 2017, Created: Dec 8, 2017]

Following example shows how to customize data binding to map query parameters by using @InitBinder and a custom PropertyEditor.

Example

Spring Controller

@Controller
@RequestMapping("/")
public class TradeController {

  @InitBinder("tradeDate")
  public void customizeBinding(WebDataBinder binder) {
      SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
      binder.registerCustomEditor(Date.class,
              new CustomDateEditor(dateFormatter, true));
  }

  @GetMapping("/trade")
  @ResponseBody
  public String handleRequest(@RequestParam Date tradeDate) {
      return "request received for " + tradeDate;
  }
}

Java Config class

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig {
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 5.0.1.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

@RequestParam Custom Binding Example Select All Download
  • request-param-web-binding-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also