0

I am getting values from user using a html file which is then used by the servlet to perform certain calculations.And when i execute my web application in the browser it takes values from user but when i click the submit button after getting values,this error is thrown. "HTTP ERROR 500 Problem accessing /servlet/MvcServlet. Reason: java.lang.Integer cannot be cast to java.lang.String"

My servlet code is like this:

int gpa=total/c;
req.setAttribute("gpa",gpa);
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp); `

and my jsp code is:

String gpa = (String) request.getAttribute("gpa");
int r=Integer.parseInt(gpa);
out.println("Your Result is "+ r);

Please help me out for passing my integer value "gpa" in servlet to jsp.

Leos Literak
  • 8,805
  • 19
  • 81
  • 156
User
  • 79
  • 1
  • 1
  • 9

3 Answers3

2

int gpa = (Integer) request.getAttribute("gpa");

Nidheesh
  • 662
  • 1
  • 8
  • 18
2

The obvious answer would be to obtain the data as Integer and let Java autounbox it to an int. This is notable by this piece of code:

int gpa = (Integer) request.getAttribute("gpa");

But you **should avoid having scriptlets (Java code) directly in your code. So the best bet would be using Expression Language directly in your JSP code:

<!DOCTYPE html>
<html lang="es">
    <head>
        <!-- head content here -->
    </head>
    <body>
        <!-- other content in your JSP file -->
        Your result is: ${gpa}
        <!-- There's no need of senseless scriptlet code -->
    </body>
</html>
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

when you send the int value to the jsp you can try this

int gpa = total/c;

String test = ""+gpa;
req.setAttribute("test",test);
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
    view.forward(req, resp); 

And then in the jsp you dont have to parse it . Just directly go -

String gpa = (String) request.getAttribute("test");
out.println("Your Result is "+ gpa);

Try this :D

Soumil Deshpande
  • 1,622
  • 12
  • 14
  • If the variable is already an `int`, there's no need to add overhead to convert it into a `String` to convert it back to `int`. – Luiggi Mendoza May 17 '14 at 17:31