转换后的@PathVariables可以互相引用吗?
我有一个 Spring @RequestMapping
和几个 @PathVariable
,第一个是缩小到第二个的必要条件 - 您可以在示例中看到下面我需要联系部门才能获得模块。使用普通的 String
@PathVariable
s 我可以这样做:
@RequestMapping("/admin/{dept}/{mod}/")
public String showModule(@PathVariable String dept, @PathVariable String mod) {
Department department = dao.findDepartment(dept);
Module module = department.findModule(mod);
return "view";
}
但是我热衷于使用 Spring 的 Converter
API 来指定Department
直接作为 @PathVariable
。因此,在我注册了自定义 Converter
类后,这才有效:
@RequestMapping("/admin/{dept}/")
public String showDept(@PathVariable Department dept) {
return "view";
}
但是 Converter API 不提供正在转换的单个参数之外的访问权限,因此无法实现 Converter
模块
的code>。我可以使用其他 API 吗?我正在关注 HandlerMethodArgumentResolver - 有没有人解决了这样的问题,或者您是否坚持使用 String @PathVariables?
我正在使用 Spring 3.1。
I've got a Spring @RequestMapping
with a couple of @PathVariable
s, and the first one is necessary to narrow down to the second one - you can see in the example below that I need to get the Department in order to get the Module. Using plain String
@PathVariable
s I can do it like this:
@RequestMapping("/admin/{dept}/{mod}/")
public String showModule(@PathVariable String dept, @PathVariable String mod) {
Department department = dao.findDepartment(dept);
Module module = department.findModule(mod);
return "view";
}
But I'm keen to use Spring's Converter
API to be able to specify the Department
directly as the @PathVariable
. So this works after I've registered a custom Converter
class:
@RequestMapping("/admin/{dept}/")
public String showDept(@PathVariable Department dept) {
return "view";
}
But the Converter API doesn't give access outside of the single argument being converted, so it's not possible to implement the Converter
for Module
. Is there another API I can use? I'm eyeing up HandlerMethodArgumentResolver
- has anyone solved a problem like this, or are you sticking to String @PathVariables?
I'm using Spring 3.1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有这样做,但我想到的一种方法是为它们两个制作一个单独的转换器:
并使转换器能够接受“deptid-modid”形式的输入,例如“ch-c104”。不可能用斜杠分隔它们,因为请求与 /admin/*/ 的 RequestMapping 模式不匹配。
就我而言,需求略有变化,因此模块代码完全唯一,不需要将范围限定到部门。所以我不需要再这样做了。如果我这样做,我可能会避免自动模块转换并在方法中手动进行。
I haven't done it like this but one way I thought of was to make a separate converter for the both of them:
And have the converter able to take an input of the form "deptid-modid" e.g. "ch-c104". It wouldn't be possible to separate them with a slash as the request wouldn't match the RequestMapping pattern of /admin/*/.
In my case, the requirements have changed slightly so that module codes are fully unique and don't need to be scoped to department. So I don't need to do this any more. If I did, I would probably eschew the automatic Module conversion and do it manually in the method.