|
| 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.http.HttpServlet; |
| 8 | +import javax.servlet.http.HttpServletRequest; |
| 9 | +import javax.servlet.http.HttpServletResponse; |
| 10 | +import java.io.IOException; |
| 11 | + |
| 12 | +public class FrontControllerServlet extends HttpServlet { |
| 13 | + @Override |
| 14 | + protected void doGet( |
| 15 | + HttpServletRequest request, |
| 16 | + HttpServletResponse response |
| 17 | + ) throws ServletException, IOException { |
| 18 | + FrontCommand command = getCommand(request); |
| 19 | + command.init(getServletContext(), request, response); |
| 20 | + command.process(); |
| 21 | + } |
| 22 | + |
| 23 | + private FrontCommand getCommand(HttpServletRequest request) { |
| 24 | + try { |
| 25 | + return (FrontCommand) getCommandClass(request) |
| 26 | + .asSubclass(FrontCommand.class) |
| 27 | + .newInstance(); |
| 28 | + } catch (Exception e) { |
| 29 | + throw new RuntimeException("Failed to get command!", e); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + private Class getCommandClass(HttpServletRequest request) { |
| 34 | + try { |
| 35 | + return Class.forName( |
| 36 | + String.format( |
| 37 | + "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", |
| 38 | + request.getParameter("command") |
| 39 | + ) |
| 40 | + ); |
| 41 | + } catch (ClassNotFoundException e) { |
| 42 | + return UnknownCommand.class; |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments