Spring, middle score in request parameter

旧街凉风 提交于 2019-12-11 12:16:44

问题


Is there a way to map a query parameter with a middle score using requests in spring?

I have no problem binding single worded parameters doing this:

Uri example: http://localhost:8080/test/?product=hotels

public class CitiesRequest{
    private ProductType product;

    public ProductType getProduct() {
        return this.product;
    }

    public void setProduct(String product) {
        this.product = product;
    }
}

But I'd like to be able to receive parameters like this:

http://localhost:8080/test/?product-type=hotels

回答1:


By default, Spring maps the query parameter key to the name of the Java variable. However, it's syntactically incorrect to have a variable name with a hyphen in Java, which explains why you're finding it particularly difficult to get Spring to set the parameter's value for you.

One workaround that might work is to just have a Map<String, String[]> parameter to represent all of the parameters. Then Spring doesn't have to map any query parameters to variable names, so the hyphenated name might end up in that map of all parameters. It may not be as comfortable as pre-split parameter objects, but it might get the hyphenated keys.

Another solution might be to configure the WebDataBinder, which controls how data from HTTP requests are mapped onto your controller's request parameters. But that's a whole can of worms, especially if you're just starting out with Spring. You can read more about it in the documentation under "data binding".




回答2:


As Misha stated it is syntactically incorrect to have a variable name with a hyphen in Java. But Spring is fine with that and allows you to specify a parameter name (in the request) different from the variable name (in java code). For exemple, when using RequestMapping driven controller, one can write :

@RequestMapping("/test")
public ModelAndView getProduct(
        @RequestParam("product-type") String productType) {
...
}

That way, getProduct will be called for a url like http://localhost/test?product-type=hotels and the parameter productTypewill receive the value hotels. And all is still purely declarative.



来源:https://stackoverflow.com/questions/23892179/spring-middle-score-in-request-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!