Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast from Object to boolean

This is the error I am receiving,

org.apache.jasper.JasperException: Unable to compile class for JSP: 

    An error occurred at line: 13 in the jsp file: /index.jsp
    Cannot cast from Object to boolean

This is my code:

Controller Servlet

if(authentication.verifyCredentials(request.getParameter("username"), 
   request.getParameter("password")))
{
        session.setAttribute("username", request.getParameter("username"));
        session.setAttribute("loggedIn", true);
        dispatcher.forward(request, response);   
}

I also tried this,

session.setAttribute("loggedIn", new Boolean(true));

JSP

<% 
    if(session.getAttribute("loggedIn") != null)
    {
        if(((boolean)session.getAttribute("loggedIn")))
        {
            response.sendRedirect("Controller"); 
        }
    }   
%>

Yes I researched and also saw the previous stackoverflow post; however I still cannot resolve my problem. Please assist.

like image 318
Dennis Avatar asked Jun 03 '12 20:06

Dennis


People also ask

How do you cast a boolean to an object?

boolean val = false; To convert it into an object, use the valueOf() method and set the argument as the boolean primitive. Boolean res = Boolean. valueOf(val);

Can boolean be casted?

You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL . You cannot cast a STRING value to BOOLEAN , although you can cast a BOOLEAN value to STRING , returning '1' for true values and '0' for false values.

How do you cast boolean to boolean?

Use the valueOf() method to convert boolean value to Boolean. Firstly, let us take a boolean value. boolean val = false; Now, to convert it to Boolean object, use the valueOf() method.

Can null be cast to boolean?

Unfortunately the compiler is not capable of deducing that the statement boolean var1=(var=null); would always lead to the invalid assignment boolean var1=null .


2 Answers

Try casting it to Boolean (nullable) instead of boolean in the JSP:

if(((Boolean)session.getAttribute("loggedIn")))
{
    response.sendRedirect("Controller"); 
}
like image 130
ChristopheD Avatar answered Sep 22 '22 04:09

ChristopheD


try with

   if(((Boolean)session.getAttribute("loggedIn")))

instead of:

   if(((boolean)session.getAttribute("loggedIn")))

attribute has to be taken as Boolean, not as primitive type

like image 20
dantuch Avatar answered Sep 20 '22 04:09

dantuch