/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servlets;
import beans.Operation;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
/**
*
* @author Corina
*/
public class OperationServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext sc = getServletContext();
Operation operation = (Operation) request.getAttribute("operationBean");
BigInteger firstNumber = new BigInteger(operation.getFirstNumber());
BigInteger secondNumber = new BigInteger(operation.getSecondNumber());
String result;
try {
result = calculate(firstNumber, secondNumber, operation.getOperator()).toString();
} catch (ArithmeticException ex) {
result = "Illegal Operation";
}
operation.setResult(result);
request.setAttribute("operationBean", operation);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private BigInteger calculate(BigInteger firstNumber, BigInteger secondNumber, String operator)
throws ArithmeticException, IllegalArgumentException {
switch (operator) {
case "+":
return firstNumber.add(secondNumber);
case "-":
return firstNumber.subtract(secondNumber);
case "*":
return firstNumber.multiply(secondNumber);
case "/":
return firstNumber.divide(secondNumber);
case "%":
return firstNumber.mod(secondNumber);
}
return null;
}
}