0

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.

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • You're duplicating one line of code. I would not call that duplication of logic. The actual logic is in the tasks.start() method, and reused in the two controllers. – JB Nizet Nov 01 '17 at 17:05

2 Answers2

1

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.

derkoe
  • 5,649
  • 2
  • 23
  • 31
0

My thought: It is just a matter of how your design and name the controllers. Ideally, I create One controller per business domain object. instead of creating controllers for each page. If we name the Controller and Services for each business domain object, you could avoid this. So i would just have TaskController and call the same URI irrespective of where you call it either from Task page, TaskDetail page or TaskReport page.

VimalKumar
  • 1,611
  • 1
  • 14
  • 11
  • If you call the same `URI`, how would you know which of `Task`, `TaskDetail` or `TaskReport` page to direct the user to? – Johan Sjöberg Nov 03 '17 at 13:25
  • Thats good question. the approach that i explained would work for REST controller. For regular controllers, i think as long as there is no major code duplication, it is better to keep separate controllers and keep all the common logic in a Service class method. As "JB Nizet" said, it is not a major concern of code duplication. – VimalKumar Nov 03 '17 at 16:04