@RequestMapping(value = "update", method = RequestMethod.POST) public String update( @Valid @ModelAttribute("task") Task task, RedirectAttributes redirectAttributes) { taskService.saveTask(task); redirectAttributes.addFlashAttribute("message", "更新任务成功"); return "redirect:/task/"; }
@RequestMapping(value = "create", method = RequestMethod.POST) public String create(@Valid Task newTask, RedirectAttributes redirectAttributes) { User user = new User(getCurrentUserId()); newTask.setUser(user); taskService.saveTask(newTask); redirectAttributes.addFlashAttribute("message", "创建任务成功"); return "redirect:/task/"; }
@RequestMapping(value = "") public String list( @RequestParam(value = "page", defaultValue = "1") int pageNumber, @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, @RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model, ServletRequest request) { Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_"); Long userId = getCurrentUserId(); Page<Task> tasks = taskService.getUserTask(userId, searchParams, pageNumber, pageSize, sortType); model.addAttribute("tasks", tasks); model.addAttribute("sortType", sortType); model.addAttribute("sortTypes", sortTypes); // 将搜索条件编码成字符串,用于排序,分页的URL model.addAttribute( "searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_")); return "task/taskList"; }
@RequestMapping(value = "update/{id}", method = RequestMethod.GET) public String updateForm(@PathVariable("id") Long id, Model model) { model.addAttribute("task", taskService.getTask(id)); model.addAttribute("action", "update"); return "task/taskForm"; }
/** * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。 * 因为仅update()方法的form中有id属性,因此仅在update时实际执行. */ @ModelAttribute() public void getTask(@RequestParam(value = "id", required = false) Long id, Model model) { if (id != null) { model.addAttribute("task", taskService.getTask(id)); } }
@RequestMapping(value = "delete/{id}") public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) { taskService.deleteTask(id); redirectAttributes.addFlashAttribute("message", "删除任务成功"); return "redirect:/task/"; }