Pract 5
Pract 5
ServletOutputStream.
DESCRIPTION:-
In java with using 2 operant’s and 1 operator we can calculate the basic mathematically
operation such as addition, subtraction, multiplication, division
Servlet is a Java class which extends the capabilities of server that provides the
application accessed by means of request response model. It uses two interfaces i.e.
HTTPRequest & HTTPResponse
HTTPRequest: This is an interface which provides methods for extracting HTTP parameters
from the query or request body depending on the type of request i.e. get or post
HTTPResponse: This interface provides an OutputStream for retrieving information such as
images or PrintWriter for retrieving text output.
Source Code:
Index.jsp(GUI)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<body>
<h3>Please Enter Two Numbers :::</h3>
<form method="GET" action="Cal">
Number:<input type="text" id="t1" name="t1"/><br/>
<select name="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select></br>
Number:<input type="text" id="t2" name="t2">
<input type="submit" value="calculate"/></br>
</form>
</body>
</html>
Calculator.java(Servlet File)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Cal extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw= response.getWriter();
int n1 = Integer.parseInt(request.getParameter("t1"));
int n2 = Integer.parseInt(request.getParameter("t2"));
String op=request.getParameter("op");
if(op.equals("+")){pw.println("Addition :::"+(n1+n2));}
else if(op.equals("-")){pw.println("Subtraction :::"+(n1-n2));}
else if(op.equals("*")){pw.println("Multiplication :::"+(n1*n2));}
else if(op.equals("/")){pw.println("Division :::"+(n1/n2));}
else{pw.println("Remainder :::"+(n1%n2));}
pw.close(); }
}
Output: