Simple Calculator using Servlet

      Comments Off on Simple Calculator using Servlet

Simple Calculator using Servlet

Simple Calculator using Servlet

This program shows how you can create simple calculator using Servlet. Here you need to create one home page which will be used take some input from the users like number1, number2 and operator.

Once you user fill all required fields and click on submit you need to send their request to Servlet. Here Servlet will process calculate that data based on the operator selected by the users.

Sample Code

<form method=”get” action=”./CalculateServlet”>
Number 1 : <input type=”text” name=”no1″> <br>
Number 2 : <input type=”text” name=”no2″> <br>
Operator :
<select name=”opt”>
<option value=”p”> + </option>
<option value=”m”> – </option>
<option value=”mul”> * </option>
<option value=”d”> / </option>
<input type=”submit” value=”Go”>


Hope you have understand the basic concept of the simple calculator using servlet. In Calculator part 1 I have explained the layout of the calculator which you need to prepare, Here is the code for the same. This part of simple calculator using servlet explains the way to do it completely.


import javax.servlet.*;
public class CalculateServlet extends HttpServlet

public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
PrintWriter out = response.getWriter();
String n1 = request.getParameter(“no1”);
String n2 = request.getParameter(“no2”);
String opt = request.getParameter(“opt”);
out.println(Integer.parseInt(n1) + Integer.parseInt(n2));
else if(opt.equals(“m”))
out.println(Integer.parseInt(n1) – Integer.parseInt(n2));

public void doGet(HttpServletRequest request,HttpServletResponse response) throws     IOException,ServletException


 File : web.xml

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<web-app xmlns=””

<display-name>Tomcat Manager Application</display-name>
A scriptable management web application for the Tomcat Web Server;
Manager lets you view, load/unload/etc particular web applications.


<!– Define the Manager Servlet Mapping –>


If you like my article, Please share with your friends on Facebook, WhatsaApp, Twitter, etc. Thanks in Advance.