How to get boolean value with requst getAttribute java?

13.2k views Asked by At

How to get boolean value set as an attribute value in request.

Consider the following snippet

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  {

 boolean isOriginal = (boolean) req.getAttribute(“isOriginalFile");
//Some code
}

Where the request may/may not contain the isOriginalFile attribute. How to handle this?

2

There are 2 answers

1
Tomasz Gawel On BEST ANSWER

Assuming that getting false when attribute is null is what you expect:

boolean isOriginal = Boolean.TRUE == req.getAttribute("isOriginalFile");

Then if you set the attribute to anything else than Boolean.TRUE (including null) you will get false.

You may set it in either way:

req.setAttribute("isOriginalFile", Boolean.TRUE);
req.setAttribute("isOriginalFile", (Boolean) true);
req.setAttribute("isOriginalFile", true);

But not as String (because it will be then evaluated to false):

req.setAttribute("isOriginalFile", "true");
4
anacron On

Parse the value returned by the getAttribute method.

boolean isOriginal = Boolean.valueOf(String.valueOf(req.getAttribute("isOriginalFile")));

The getAttribute returns an Object, and the Boolean.valueOf method takes a String parameter. So, first convert the returned value to String and then parse it.

https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#valueOf(java.lang.String)