[go: up one dir, main page]

0% found this document useful (0 votes)
5 views3 pages

Question 3

Uploaded by

rijato8567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Question 3

Uploaded by

rijato8567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Q3.

Create a servelet that takes two number from a form and display their sum, difference, product
and division on a JSP page.

<!DOCTYPE html>

<html>

<head>

<title>Calculator Form</title>

</head>

<body>

<h2>Enter Two Numbers</h2>

<form action="CalculateServlet" method="post">

Number 1: <input type="text" name="num1" required><br><br>

Number 2: <input type="text" name="num2" required><br><br>

<input type="submit" value="Calculate">

</form>

</body>

</html>

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CalculateServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Get numbers from form

double num1 = Double.parseDouble(request.getParameter("num1"));

double num2 = Double.parseDouble(request.getParameter("num2"));

// Perform operations

double sum = num1 + num2;


double diff = num1 - num2;

double prod = num1 * num2;

double div = (num2 != 0) ? (num1 / num2) : Double.NaN;

// Set attributes to send to JSP

request.setAttribute("sum", sum);

request.setAttribute("diff", diff);

request.setAttribute("prod", prod);

request.setAttribute("div", div);

// Forward to JSP

RequestDispatcher rd = request.getRequestDispatcher("result.jsp");

rd.forward(request, response);

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE html>

<html>

<head>

<title>Calculation Results</title>

</head>

<body>

<h2>Results:</h2>

<p>Sum: ${sum}</p>

<p>Difference: ${diff}</p>

<p>Product: ${prod}</p>

<p>Division: ${div}</p>

<br>

<a href="input.jsp">Go Back</a>


</body>

</html>

Output:-

You might also like