如何使用Bean绑定请求url模板请求?

时间:2011-09-06 19:47:00

标签: spring spring-mvc

我有一个RESTful url的处理程序方法,比如/ jobtype / {jobType} / id / {jobId},我需要绑定到名为JobType的类。 JobType类包含jobId和jobType。

如何将URI模板绑定到JobType类?我尝试使用@PathVariable,但它只选择JobType而不是id。

webDataBinder如何在这种情况下提供帮助?我尝试使用@initBinder将JobType类绑定到属性编辑器,但它无法正常工作。

//Request handler method code
@RequestMapping(value="/jobtype/{jobType}/id/{jobId}")
public ModelAndView fooViewWithDate(JobType jobType){
    ModelAndView mav = new ModelAndView("/admin/foo");
    mav.addObject("jobType", jobType);
    return mav;
}

@InitBinder
public void initBinder(WebDataBinder wdb){
    wdb.registerCustomEditor(JobType.class, new JobTypePropertyEditor());
}


public class JobTypePropertyEditor extends PropertyEditorSupport {  
@Override
public void setAsText(String text) throws IllegalArgumentException {
    JobType jobType = new JobType();
    jobType.setName(text);
    setValue(jobType);
}

}

2 个答案:

答案 0 :(得分:2)

正如我之前回答的评论所述,这可能是一个解决方案。

@RequestMapping(value="/jobtype/{jobType}/id/{jobId}")
public ModelAndView fooViewWithDate(HttpServletRequest request) {
   LinkedHashMap map = (LinkedHashMap) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
   JobType jobType = new JobType(map);
   ModelAndView mav = new ModelAndView("/admin/foo");
   mav.addObject("jobType", jobType);
   return mav;
}

答案 1 :(得分:0)

我不确定我是否完全理解你的问题,但看起来JobType是一个名字和一个id,所以你应该把它放在@RequestMapping中。像这样:

//Request handler method code
@RequestMapping(value="/jobtype/{jobType}/id/{jobId}")
   public ModelAndView fooViewWithDate(@PathVariable JobType jobType, 
                                       @PathVariable int jobId){
   jobType.setId(jobId);
   ModelAndView mav = new ModelAndView("/admin/foo");
   mav.addObject("jobType", jobType);
   return mav;
}