/Users/lyon/j4p/src/bookExamples/ch05ControlStructs/ServletDispatcher.java

1    /** 
2     * Created by IntelliJ IDEA. 
3     * User: dlyon 
4     * Date: Nov 6, 2003 
5     * Time: 7:10:29 PM 
6     * To change this template use Options | File Templates. 
7     */ 
8    package bookExamples.ch05ControlStructs; 
9     
10   // examples.stringswitch.StringDispatcher 
11    
12   import javax.servlet.http.HttpServletRequest; 
13   import javax.servlet.http.HttpServletResponse; 
14   import javax.servlet.http.HttpServlet; 
15   import javax.servlet.RequestDispatcher; 
16   import javax.servlet.ServletException; 
17   import java.util.HashMap; 
18   import java.io.IOException; 
19    
20   public class ServletDispatcher { 
21       private HashMap hm = new HashMap(); 
22    
23       public void add(DispatchCommand dc) { 
24           hm.put(dc.getCommand(), dc); 
25       } 
26    
27       public void execute(String s, 
28                           HttpServletRequest request, 
29                           HttpServletResponse response) { 
30           DispatchCommand dc = (DispatchCommand) hm.get(s); 
31           if (dc == null) return; 
32           dc.run(request, response); 
33       } 
34    
35       public static void gotoPage(HttpServlet s, 
36                                   String address, 
37                                   HttpServletRequest request, 
38                                   HttpServletResponse response) { 
39           try { 
40               RequestDispatcher rd = s.getServletContext().getRequestDispatcher(address); 
41               rd.forward(request, response); 
42           } catch (ServletException e) { 
43               e.printStackTrace(); 
44           } catch (IOException e) { 
45               e.printStackTrace(); 
46           } 
47       } 
48   } 
49