views:

85

answers:

1

Hello,

I used to use "@RequestParam("a-b") String foo" to receive the "a-b" parameter from http query.

now I want to switch to Command Object, but I don't how to receive this param, I tried following 4 forms "ab", "aB", "a_b", "a_B", but neither works, for example, the following code will result as

URL: http://localhost:8080/test1?a-b=1
Result: Foo{ab='null', aB='null', a_b='null', a_B='null'}

Thanks in advance

@Controller
public class TestController {

@RequestMapping("/test1")
public String test1(
    Foo foo,
    HttpServletResponse response
) throws IOException {
    response.setContentType("text/plain");
    response.getOutputStream().write(foo.toString().getBytes("UTF-8"));
    return null;
}


public static class Foo {

    private String ab;
    private String aB;
    private String a_b;
    private String a_B;

    // getter and setter
    ...

    @Override
    public String toString() {
        return "Foo{" +
                "ab='" + ab + '\'' +
                ", aB='" + aB + '\'' +
                ", a_b='" + a_b + '\'' +
                ", a_B='" + a_B + '\'' +
                '}';
    }
}





}
+1  A: 

I'm confused -- you're clearly using the request parameter a-b, but expecting it to be passed in without the dash, or with the dash converted to an underscore? Java doesn't let you have class fields with dashes in their names, and I don't think that Spring MVC has any magical way of converting dashes in request parameter names, so I'd say you might just want to not use request parameters with dashes in them if you're going to use this method of passing them into your controllers.

If you have to have your request parameter named this way, then your other option is to provide a custom WebBindingInitializer, as described in the Customizing WebDataBinder Initialization section of the Spring manual, which maps the a-b request parameter to the relevant field of your Foo class. Although now that I read that more closely, WebBindingInitializers might not support binding command objects...

delfuego
`a-b` comes from an old API, and I should continue support this API, that's why I don't switch from `a-b` to `aB`.thanks.
lidaobing