Step 1: Create a new
project
Step 2: Select java web → web
Application
--> index.html
<html>
<head>
<title>Calculator
App</title>
</head>
<body>
<form
action="CalculatorServlet" method="post" >
Enter First Number <input
type="text" name="txtN1" ><br> Enter Second Number
<input type="text" name="txtN2" ><br> Select an
Operation
<input type="radio"
name="opr" value="+">ADDTION
<input type="radio"
name="opr" value="*">MULTIPLY <input
type="radio" name="opr" value="/">DIVIDE
<input type="radio"
name="opr" value="-"> Substraction
<br> <input
type="reset">
<input type="submit"
value="Calculate" >
</form>
</body>
</html>
Step 3: Add a new
Servlet to source package
-Name the servlet and package
-Check “Add information to deployment
descriptor” to add servlet into web.xml But preferably use annotation.
CalculatorServlet.java
package mypack;
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
CalculatorServlet extends HttpServlet {
public void
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException { response.setContentType("text/html;charset=UTF-8);
PrintWriter out =
response.getWriter();
out.println("<html><head><title>Servlet
CalculatorServlet</title></head><body>");
double n1 =
Double.parseDouble(request.getParameter("txtN1"));
double n2 =
Double.parseDouble(request.getParameter("txtN2"));
double result =0;
String
opr=request.getParameter("opr");
if(opr.equals("+"))
result=n1+n2;
if(opr.equals("-"))
result=n1-n2;
if(opr.equals("*"))
result=n1*n2;
if(opr.equals("/"))
result=n1/n2;
out.println("<h1>
Result = "+result);
out.println("</body></html>");
}
}
Comments
Post a Comment