Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Avoid NumberFormatException in Spring MVC controller

In my Spring MVC controller I have a method like this:

public String myMethod(@RequestParam(defaultValue="0") int param) { ... }

When I pass a string as value of my param I'm obviously getting a NumberFormatException:

Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "test"

That's clear...

So I'm trying to find a way to redirect user to a default page when this error is occurring. Is there a common way to achieve this?

At the moment I'm thinking about using a String in place of an int to map my param, check if this is parsable to int and then switch to the appropriate logic, but this seems a workaround, not a solution...

Is there a more elegant way to handle this problem and keep the correct type binding for my param?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Please have a look into the @Valid annotation. Hope this helps. This annotation helps in adding more validations for the request parameter.

https://spring.io/guides/gs/validating-form-input/

over 4 years ago · Santiago Trujillo Report

0

I finally solved adding a CustomNumberEditor like this:

@InitBinder
public void registerNumbersBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true){
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            try{
                super.setAsText(text);
            }catch (IllegalArgumentException ex){
                setValue(0);
            }
        }
    });
}
over 4 years ago · Santiago Trujillo Report

0

In this scenario, you need to handle "MethodArgumentTypeMismatchException" you can do that using @ControllerAdvice

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!