KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mockobjects > examples > calcserver > CalculatorServlet


1 package com.mockobjects.examples.calcserver;
2
3 import java.io.IOException JavaDoc;
4 import java.io.PrintWriter JavaDoc;
5 import java.sql.Connection JavaDoc;
6 import java.sql.SQLException JavaDoc;
7 import javax.servlet.ServletException JavaDoc;
8 import javax.servlet.http.HttpServlet JavaDoc;
9 import javax.servlet.http.HttpServletRequest JavaDoc;
10 import javax.servlet.http.HttpServletResponse JavaDoc;
11
12 public class CalculatorServlet extends HttpServlet JavaDoc {
13     IntCalculator myCalculator;
14
15
16     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
17         performTask(request, response);
18     }
19
20     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
21         performTask(request, response);
22     }
23
24     public String JavaDoc getServletInfo() {
25         return super.getServletInfo();
26     }
27
28     public void init() throws ServletException JavaDoc {
29         try {
30             Connection JavaDoc connection = Database.createConnection();
31             myCalculator =
32                     new SqlSavingCalculator(
33                             new Calculator(),
34                             connection.prepareStatement("INSERT INTO LOG VALUES (?)"));
35         } catch (SQLException JavaDoc ex) {
36             throw new ServletException JavaDoc(ex);
37         }
38     }
39
40
41     public void init(IntCalculator calculator) {
42         myCalculator = calculator;
43     }
44
45
46     public void performTask(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
47         response.setContentType("text/plain");
48
49         PrintWriter JavaDoc wr = response.getWriter();
50         try {
51             int value1 = Integer.parseInt(request.getParameter("value1"));
52             int value2 = Integer.parseInt(request.getParameter("value2"));
53
54             String JavaDoc operation = request.getPathInfo();
55             wr.println(myCalculator.calculate(value1, value2, operation));
56         } catch (NumberFormatException JavaDoc ex) {
57             wr.println("Calculation failed " + ex);
58         } catch (CalculatorException ex) {
59             wr.println("Calculation failed " + ex);
60         }
61     }
62 }
Popular Tags