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