• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JSP Parameters and HTML Form Values

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I pass a value from an HTML form to a JSP page and the user hasn't typed anything into one of the text fields, how do I test that it's null?
String name = request.getParameter("name");
if(name==null)
if(name=="")
Neither of these seem to work?! Yikes!
Thanks,
Drew
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There I go again trying to use if(name=="") where I should be using if(name.equals(""))
If I had a dime for everytime I've done that...shit!
Sorry,
Drew
 
Vlad Patryshev
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To avoid this kind of bugs forever, I am using this cheap and dirty solution:

/**
* checks whether a string is empty
* @param s
* @return true if empty
*/
public static final boolean isEmpty(String s) {
return (s == null) || (s.length() == 0) || "null".equals(s);
}
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i liked Vlad's solution to the problem but one should know,
- if query param is having NO value then we will have "" as a value when we do getParameter().
- if query param is NOT there(doesn't exists) in the request then we will have null as return of getParameter()
-else we will have some value.
hth,
maulin.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry..forgot to mention...
u gotta know == is not same as equals() method. == is just a reference equality check not the content check...
-maulin
 
lakshmi rajagopal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can directly give as follows
if (request.getParamter("name") != null)
name = request.getParameter("name")
 
Sean MacLean
author
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should decide if this is what you want, as well.
if( name != null && name.trim().length() != 0 ) {
// retrieve the parameter...
}
This will catch all white space.
Sean
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic