Spring MVC在带有变量的控制器类上使用@RequestMapping

时间:2015-01-29 21:19:07

标签: spring spring-mvc routes mapping request-mapping

我想编写整个控制器来处理实体。 我想在类级别声明实体的id并在每个方法上使用它。这是控制器类:

@Controller
@RequestMapping(value="/job/{j_id}/instance")
public class JobController extends GenericController {
    private final String htmlDir = "job/";

    @RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
    public ModelAndView open(@PathVariable Long instance_id) {
        ModelAndView result = new ModelAndView(htmlDir  + "instance");
        result.addObject("instance_id", instance_id);

我想在j_id

中使用变量@RequestMapping
        return result;
    }
}

我能解决这个问题吗?请帮忙。请给我一些代码。

1 个答案:

答案 0 :(得分:2)

尝试这样

@Controller
@RequestMapping(value="/job/{j_id}/instance")
public class JobController  {
    private final String htmlDir = "job/";

    @RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
    public ModelAndView open(@PathVariable(value="j_id") Long instance_id) {
        ModelAndView result = new ModelAndView(htmlDir  + "instance");
        result.addObject("instance_id", instance_id);
        System.out.println("Instance Id -------------> " + instance_id);
        return result;
    }

}

请注意" @PathVariable(值=" j_id")"

要获取这两个变量,您可以按如下方式更改该行:

    @RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
    public ModelAndView open(@PathVariable(value="j_id") Long jnstance_id, @PathVariable(value="i_id") Long instance_id) {
            .....
    }