What's a good way to structure spring web controllers when there are different web pages that share functionality?
Let's say there are a Tasks
and a Task
web page. I can start a task from both pages and I expect that I will remain on the same page when doing so .
What's the best way to do this? Am i forced to duplicate logic as follows:
@Controller
@RequestMapping("/tasks")
public class TasksController {
@GetMapping("/{id}/start")
public String start(@PathVariable String id) {
tasks.start(id);
return "redirect:/tasks.html";
}
}
and
@Controller
@RequestMapping("/task")
public class TaskController {
@GetMapping("/{id}/start")
public String start(@PathVariable String id) {
tasks.start(id);
return "redirect:/task.html";
}
}
ps. I'm not interested in async JavaScipt solutions.
You could use the Regex feature in path variables and get the page name in another variable. So, I would solve this the following way:
@Controller
public class TaskController {
...
@GetMapping({"/{page:tasks?}/{id}/start")
public String start(@PathVariable String page, @PathVariable String id) {
tasks.start(id);
return "redirect:/" + page + ".html";
}
}
If there's more logic or the entry points are quite different extract the common code to a service.