使用 Spring 我可以创建一个可选的路径变量吗? [英] With Spring can I make an optional path variable?

查看:21
本文介绍了使用 Spring 我可以创建一个可选的路径变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Spring 3.0 中,我可以有一个可选的路径变量吗?

With Spring 3.0, can I have an optional path variable?

例如

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
        HttpServletRequest req,
        @PathVariable String type,
        @RequestParam("track") String track) {
    return new TestBean();
}

这里我希望 /json/abc/json 调用相同的方法.
一种明显的解决方法是将 type 声明为请求参数:

Here I would like /json/abc or /json to call the same method.
One obvious workaround declare type as a request parameter:

@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();
}

然后 /json?type=abc&track=aa/json?track=rr 将工作

推荐答案

你不能有可选的路径变量,但你可以有两个调用相同服务代码的控制器方法:

You can't have optional path variables, but you can have two controller methods which call the same service code:

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
        HttpServletRequest req,
        @PathVariable String type,
        @RequestParam("track") String track) {
    return getTestBean(type);
}

@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
        HttpServletRequest req,
        @RequestParam("track") String track) {
    return getTestBean();
}

这篇关于使用 Spring 我可以创建一个可选的路径变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆