1 7 package org.jboss.tutorial.ear.servlet; 8 9 import org.jboss.tutorial.ear.bean.CalculatorLocal; 10 11 import javax.annotation.EJB; 12 import javax.naming.InitialContext ; 13 import javax.naming.NamingException ; 14 import javax.servlet.ServletException ; 15 import javax.servlet.http.HttpServlet ; 16 import javax.servlet.http.HttpServletRequest ; 17 import javax.servlet.http.HttpServletResponse ; 18 import javax.annotation.EJB; 19 import java.io.IOException ; 20 import java.io.PrintWriter ; 21 22 27 public class CalculatorActionServlet extends HttpServlet 28 { 29 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 30 throws ServletException , IOException 31 { 32 doit(req, resp); 33 } 34 35 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 36 throws ServletException , IOException 37 { 38 doit(req, resp); 39 } 40 41 46 public void init() throws ServletException 47 { 48 super.init(); 49 try 50 { 51 InitialContext ctx = new InitialContext (); 52 53 CalculatorLocal calculator = (CalculatorLocal) ctx.lookup(CalculatorLocal.class.getName()); 55 setCalculator(calculator); 56 } 57 catch (NamingException e) 58 { 59 throw new RuntimeException (e); 60 } 61 62 } 63 64 private CalculatorLocal calculator; 65 66 70 @EJB(name = "calculator") 71 public void setCalculator(CalculatorLocal calculator) 72 { 73 this.calculator = calculator; 74 } 75 76 protected void doit(HttpServletRequest req, HttpServletResponse resp) 77 throws ServletException , IOException 78 { 79 int op1 = Integer.parseInt(req.getParameter("op1")); 80 int op2 = Integer.parseInt(req.getParameter("op2")); 81 82 String action = req.getParameter("action"); 83 84 int result = 0; 85 if (action.equals("Add")) 86 result = calculator.add(op1, op2); 87 else if (action.equals("Subtract")) result = calculator.subtract(op1, op2); 88 89 resp.setContentType("text/html"); 90 PrintWriter writer = resp.getWriter(); 91 writer.println("<html>"); 92 writer.println("<body>"); 93 writer.println("<h1>Answer: " + result + "</h1>"); 94 writer.println("</body"); 95 writer.println("</html>"); 96 } 97 } 98 | Popular Tags |