Java

Servlet Application to perform simple calculator application

HTML FILE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>
 <form method="POST" action="http://localhost:8080/ZWebApp/calc">
  Enter First Number : <input type="text" name="first">
  <br><br><br>
  Select Operator : <input type="radio" name="operator" value="add" selected=true>+ &nbsp;&nbsp;<input type="radio" name="operator" value="sub">-&nbsp;&nbsp;<input type="radio" name="operator" value="mul">*&nbsp;&nbsp;<input type="radio" name="operator" value="div">/&nbsp;&nbsp;<input type="radio" name="operator" value="mod">%
  <br><br><br>
  Enter Second Number : <input type="text" name="second">
<br><br><br>
<input type="submit" value="Perform Operation">
</form>
 </body>

</html>

SERVLET FILE

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Calculator extends HttpServlet
{
 public void init(ServletConfig config) throws ServletException
 {
  super.init(config);
 }


 public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
 {
 
 PrintWriter pw;
 response.setContentType("text/html");
 pw=response.getWriter();

 int num1=Integer.parseInt(request.getParameter("first"));
 int num2=Integer.parseInt(request.getParameter("second"));
 String operator=request.getParameter("operator");

 pw.println("<html><body>");
 if (operator.equals("add"))
 {
  pw.println(""+num1+" + "+num2+" = "+(num1+num2));
 }

  else if (operator.equals("sub"))
 {
  pw.println(""+num1+" - "+num2+" = "+(num1-num2));
 }

   else if (operator.equals("mul"))
 {
  pw.println(""+num1+" * "+num2+" = "+(num1*num2));
 }

   else if (operator.equals("div"))
 {
  pw.println(""+num1+" / "+num2+" = "+(num1/num2));
 }

   else 
 {
  pw.println(""+num1+" % "+num2+" = "+(num1%num2));
 }


pw.println("</body></html>");
pw.close();

 }
}

Related Posts

Table Of Contents

;