开发者

how to map "a-b" query to a command object in Spring MVC

开发者 https://www.devze.com 2022-12-14 10:09 出处:网络
I used to use \"@RequestParam(\"a-b\") String foo\" to receive the \"a-b\" parameter from http query.

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 + '\'' +
                '}';
    }
}





}


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号