使用Spring 3.0,我可以有一个可选的路径变量吗?
例如
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return new TestBean();
}
Run Code Online (Sandbox Code Playgroud)
在这里,我想/json/abc或/json称为相同的方法.
一个明显的解决方法是声明type为请求参数:
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
HttpServletRequest req,
@RequestParam(value = "type", required = false) String type,
@RequestParam("track") String track) {
return new TestBean();
}
Run Code Online (Sandbox Code Playgroud)
然后/json?type=abc&track=aa或/json?track=rr将工作
我在Spring MVC中有一个带有可选路径变量的方法.我试图在没有提供可选路径变量的情况下测试它.
来自Controller的片段,用于调用的资源URI-
@RequestMapping(value = "/some/uri/{foo}/{bar}", method = RequestMethod.PUT)
public <T> ResponseEntity<T> someMethod(@PathVariable("foo") String foo, @PathVariable(value = "bar", required = false) String bar) {
LOGGER.info("foo: {}, bar: {}", foo, bar);
}
Run Code Online (Sandbox Code Playgroud)
我使用MockMvc测试的片段 -
//inject context
@Autowired
private WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
@Before
public void setup() {
//build mockMvc
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void someMethodTest() throws Exception {
//works as expected
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", "bar"))
.andExpect(status().isOk()); //works
//following doesn't work
//pass null for optional
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", null))
.andExpect(status().isOk()); //throws …Run Code Online (Sandbox Code Playgroud) 我想以下列格式将参数传递给我的Web服务:
而不是
HTTP://.../greetings名称=尼尔&ID = 1
所以我改变了我的代码(注意,我只包含了代码中的第一个参数):
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
Run Code Online (Sandbox Code Playgroud)
至:
@RequestMapping
public Greeting greeting(@PathVariable String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
Run Code Online (Sandbox Code Playgroud)
哪个有效,但我不知道如何将默认值添加到@PathVariable,以便例如:
可以像查询参数一样工作.
我该怎么做呢?我想也许它会传递null,但它只会产生页面错误.
我想答案可能是添加多个重载,但听起来有点混乱.
谢谢.
谢谢.