0

I have a command object that represents a form object submitted. If a value from a form input field is blank, I want it to be null in the command object.

I read a different SO question that showed to use the InitBinder

I gave that a shot, but the initBinder method is never called.

My controller

package com.example;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.example.MyDTO;

@Controller
public class MyControllerImpl implements MyController {

    @InitBinder("myControllerImpl")
    public void initBinder(WebDataBinder binder) {
        System.out.println("init binder");
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @Override
    public String someAction( MyDTO someDTO ) {

        System.out.println(someDTO);

        // Do something with DTO. I want blank values to be null here

        return "somePage;
    }

}

DTO

package com.example;

public class MyDTO {

    private String name;

    public String getName() {

        return name;
    }

    public String setName() {

        return name;
    }

}

I also tried adding the class name to the InitBinder annotation

@InitBinder("myControllerImpl")

but it did not work.

What am I missing to get the init binder to be called?

I'm using Java 6 and Spring 3

2 Answers 2

1

You need to add @ControllerAdvice to controller class.

Sign up to request clarification or add additional context in comments.

5 Comments

Missed that. Unfortunately, we're a bit outdated and using Spring 3.1.1 Not sure if I can upgrade to 3.2, most likely not. So this way probably won't work.
I have the InitBinder annotation, but it looks like @ControllerAdvice annotation wasn't added till 3.2
@eric as I wrote, docs says it should work as it is, dunno what is happening on your side
Looks like it is my interface causing the issue. When I removed the interface and added all of the @RequestMappings from the interface to the Impl, it worked. Not really sure why, but it's a starting place.
1

The issue is that I'm using an interface on my controller. The implementation is proxied by Spring AOP. To get this to work, I had to add the following method on the interface:

@InitBinder
void initBinder(WebDataBinder binder);

Then in the implementation I have

@Override
public void initBinder(WebDataBinder binder) {
    System.out.println("init binder!");
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.