J.Joe J.Joe - 3 months ago 31
Java Question

How to use @PathVariable to Pojo?

I've created a POJO like this.

public class Param(){
@NotNull
private Sring paraA;
@NotNull
private Sring paraB;

//Setter and getter
}


And I want to use
JSR303
to check it.

@RequestMapping(value = "/test/{paraA}/{paraB}")
@ResponseBody
public BaseJsonRsp test(@PathVariable @Valid Param param) {
//doSomething
}


But this code it doesn't work and I've got following error

HTTP Status 500 - Missing URI template variable 'value' for method parameter of type PatchValue!


Why? How to fix it? Thanks.

Answer

Have a look at the Spring Refererence Docs on @PathVariable:

A @PathVariable argument can be of any simple type such as int, long, Date, etc.

If you want to use your Param type as the controller method argument, you won't be able to do so using @PathVariable.

Alternatively, you can map your parameters to individual String variables (using @PathVariable), and then manually construct your Param after that. Note that @PathVariable assumes that the placeholder in your URL is the same as the variable name by default. If your variable name doesn't match, you'd do something like

@RequestMapping(value = "/test/{paraA}/{paraB}")
@ResponseBody
public BaseJsonRsp test(@PathVariable("paraA") String myParam, 
                        @PathVariable("paraB") String otherParam) {
    //doSomething
}