• Post Reply Bookmark Topic Watch Topic
  • New Topic

parameter values

 
John Gregory
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a jsp form with a few check boxes. It's not mandatory that
any of them are checked. But if they are, I need to process them.
Using the example in the HFJSP book I have something like:


Now if a user doesn't like beer and doesn't check any of them and I get a
NullPointerException.

SO, I changed things around by surrounding the above with a try/catch block with
the following in the catch:



Still same result. Any ideas on how I can fix this?

Thanks,

John
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65522
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If no check boxes are checked there's no parameters submitted. Your code just needs to account for the fact that a null may be returned, which means that no boxes were checked.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65522
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S. getParameterValues() always returns a String[]. It's bad form to have the unnecessary cast.
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Gregory wrote:


Now if a user doesn't like beer and doesn't check any of them and I get a
NullPointerException.
You can impossibly get a NPE in the mentioned code line. Maybe you just mean that it returns null. This can indeed happen if nothing is checked. You know, it only returns values which are actually been checked.

SO, I changed things around by surrounding the above with a try/catch block with
the following in the catch:

A bad practice. Just do a nullcheck. E.g. if (beerBrands != null) { doSomethingWithBeerBrands(); }.
 
Mohamed Inayath
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John,

If the user doesn't select any checkbox obviously the String array will be null. And you are casting that. So the Null Pointer Exception.

Better as suggested have a Null check then cast it or can use ternary operator.

If its not null process the String array...
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65522
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohamed Inayath wrote: then cast it or ...

Casting will not cause the NPE, referencing a null causes the NPE. And again, the cast is not necessary and just makes the code look foolish.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!