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

<html>
<body>
<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>
</select><br>
<input type=”submit” value=”Go”>
</form>
</body>
</html>

 

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.

 File: CalculateServlet.java

import java.io.*;
import javax.servlet.*;
public class CalculateServlet extends HttpServlet
{

public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
display();
PrintWriter out = response.getWriter();
String n1 = request.getParameter(“no1”);
String n2 = request.getParameter(“no2”);
String opt = request.getParameter(“opt”);
if(opt.equals(“p”))
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
{
doPost(request,response);
}

}

 File : web.xml

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<web-app xmlns=”http://java.sun.com/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”
version=”3.0″
metadata-complete=”true”>

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

<servlet>
<servlet-name>CalculateServlet</servlet-name>
<servlet-class>CalculateServlet</servlet-class>
</servlet>

<!– Define the Manager Servlet Mapping –>
<servlet-mapping>
<servlet-name>CalculateServlet</servlet-name>
<url-pattern>/CalculateServlet</url-pattern>
</servlet-mapping>

</web-app>

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