百里香叶后控制器路径变量

时间:2017-11-08 19:08:55

标签: spring thymeleaf

我需要向百里香提出请求但有一些问题 我的控制器

   @RequestMapping(value = "/tasks/{project}", method = RequestMethod.GET)
@ResponseBody
public ModelAndView index(@PathVariable Project project) {
    ModelAndView modelAndView = new ModelAndView();
    List<Task> findAll = taskService.findAll(project);
    modelAndView.addObject("findAllTasks", findAll);
    final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
    modelAndView.addObject("user", userService.findByEmail(currentUser));
    modelAndView.setViewName("tasks");
    return modelAndView;
}
@RequestMapping(value = "/tasks/{id}", method = RequestMethod.POST)
@ResponseBody
public ModelAndView createNewProject(@Valid Task task, BindingResult bindingResult, @PathVariable ("id") int id ) {
    Project project = projectService.findOne(id);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("id", id);
    if (bindingResult.hasErrors()) {
        modelAndView.setViewName("tasks");
    } else {
        taskService.create(task, project);
        modelAndView.addObject("successMessage", "Task has been added succesfully");
        modelAndView.addObject("task", new Task());
        modelAndView.setViewName("tasks");
        List<Task> findAll = taskService.findAll(project);
        modelAndView.addObject("findAllTasks", findAll);
    }
    return modelAndView;
}

我的HTML

 <form autocomplete="off" action="#" th:action="@{'/tasks/' + ${id}}"
      th:object="${task}" method="post" class="form-horizontal"
      role="form">
    <input type="text" id="taskTitle" name="Title"  th:placeholder="Title"
           class="form-control" />
    <input type="text" id="body" name="body"  th:placeholder="text"
           class="form-control" />
    <input type="checkbox" id="public_feedback"
           class="form-control" /><label for="public_feedback">Public feedback</label>
    <span th:utext="${successMessage}"></span>
    <button type="submit" class="add">Add task</button>
</form>

但我的帖子请求是http://localhost:8080/tasks/null。获得请求工作是好的。和硬编码,例如

th:action="@{/tasks/1}" 

运作良好,但我需要获取当前项目的路径 我需要通过路径变量得到项目ID,我找不到任何答案。请帮帮我。

2 个答案:

答案 0 :(得分:0)

使用action

更新<form>中的th:action="@{|/tasks/${task.id}|}"属性

我相信每个id

都有一个task属性

答案 1 :(得分:0)

你是否在你的html中迭代每个任务?您可以向视图添加任务列表(称为findAllTask​​s),因此请确保在发布表单时使用正确的对象。否则就没有id。

您可以在视图中放置已存在的任务(带有ID),并在发布表单时使用该ID,或者如果您想使用帖子请求创建新的“任务”,只需删除ID并等待使您的存储库在创建对象时生成一个。

相关问题