ASHISH
ASHISH

Reputation: 67

Passing calculation result to JSP page

Index.jsp takes two input number and after submit the request go to Operation.java. It has a radio button to select Operation. Both inputs and radio button are submitted to Operation.java.

<body>
    <h1>Easy way to do fast operation</h1>
    <form action="Operation">
        First number::<input type="text" name="firstno"></input></br></br>
        Second number::<input type="text" name="Secondno"></input></br></br>
        <input type="radio" name="option" value="add">Add</input>
        <input type="radio" name="option" value="substract">Subtract</input>
        <input type="radio" name="option" value="mul">Multiply</input>
        <input type="radio" name="option" value="divide">Divide</input>
        </br></br>
        <input type="submit" value="submit"/>
    </form>    
    <%if(request.getAttribute("res")!=null){%>                   
        The result is ::${res}
    <%}%>
</body>  

Operation.java(Servlet) takes value from input button and do calculation based on the radio button click. It will calculate the result.

int result1=0;
int n1=Integer.parseInt(request.getParameter("firstno"));
int n2=Integer.parseInt(request.getParameter("Secondno"));
String radio=request.getParameter("option");
if(radio.equals("add"))
{
    result1=n1+n2;
}
 else if(radio.equals("substract"))
{
    result1=n1-n2;
}
else if(radio.equals("mul"))
{
    result1=n1*n2;
}

       request.setAttribute("res", result1);
        RequestDispatcher requestDispatcher =      request.getRequestDispatcher("index.jsp");
        requestDispatcher.forward(request, response);

After calculation I want to show the result on the index.jsp. How can I do that?

Upvotes: 1

Views: 4954

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 122008

There are several ways to communicate between servelt and jsp.

1)Through request.

2)Through session.

In your case,request level communication is enough.Dealing with session is little tricky,especially when you are not aware what it do.

In your servlet

            int n1=Integer.parseInt(request.getParameter("firstno"));
            int n2=Integer.parseInt(request.getParameter("Secondno"));

Those twolines causes nullpointer exception. if they are null.

Put null checks.

Then change the form action,it might be <form action="/Operation">.

Then from there set result to that request as a attribute.

Dispatch to the same jsp

get the request attribute in jsp.

Print there.

request.setAttribute("name", "value");
request.getRequestDispatcher("/index.jsp").forward(request, response);

Read more :

Upvotes: 1

Rob
Rob

Reputation: 11733

By rendering the desired output in the response. Servlet is a very thin wrapper around HTTP: you are processing an HttpRequest and producing an HttpResponse.

Upvotes: 1

Related Questions