|
| 1 | +package com.baeldung.enterprise.patterns.front.controller; |
| 2 | + |
| 3 | +import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; |
| 4 | +import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; |
| 5 | + |
| 6 | +import javax.servlet.ServletException; |
| 7 | +import javax.servlet.annotation.WebServlet; |
| 8 | +import javax.servlet.http.HttpServlet; |
| 9 | +import javax.servlet.http.HttpServletRequest; |
| 10 | +import javax.servlet.http.HttpServletResponse; |
| 11 | +import java.io.IOException; |
| 12 | + |
| 13 | +@WebServlet(name = "front-controller", urlPatterns = "/") |
| 14 | +public class FrontControllerServlet extends HttpServlet { |
| 15 | + @Override |
| 16 | + protected void doGet( |
| 17 | + HttpServletRequest request, |
| 18 | + HttpServletResponse response |
| 19 | + ) throws ServletException, IOException { |
| 20 | + doCommand(request, response); |
| 21 | + } |
| 22 | + |
| 23 | + @Override |
| 24 | + protected void doPost( |
| 25 | + HttpServletRequest request, |
| 26 | + HttpServletResponse response |
| 27 | + ) throws ServletException, IOException { |
| 28 | + doCommand(request, response); |
| 29 | + } |
| 30 | + |
| 31 | + private void doCommand( |
| 32 | + HttpServletRequest request, |
| 33 | + HttpServletResponse response |
| 34 | + ) throws ServletException, IOException { |
| 35 | + FrontCommand command = getCommand(request); |
| 36 | + command.init(request, response); |
| 37 | + command.process(); |
| 38 | + } |
| 39 | + |
| 40 | + private FrontCommand getCommand(HttpServletRequest request) { |
| 41 | + try { |
| 42 | + Class type = Class.forName( |
| 43 | + String.format( |
| 44 | + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", |
| 45 | + request.getParameter("command") |
| 46 | + ) |
| 47 | + ); |
| 48 | + return (FrontCommand) type |
| 49 | + .asSubclass(FrontCommand.class) |
| 50 | + .newInstance(); |
| 51 | + } catch (Exception e) { |
| 52 | + return new UnknownCommand(); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments