Missing Elements in HTTP Request - Null or Empty?
Solution 1
If a parameter is not specified at all like so,
http://example.com/context/servlet?x=foo
then it will return null
:
String x = request.getParameter("x"); // "foo"
String y = request.getParameter("y"); // null
If a parameter is specified, but does not have a value like so,
http://example.com/context/servlet?x=foo&y
then it will return an empty string:
String x = request.getParameter("x"); // "foo"
String y = request.getParameter("y"); // ""
Makes sense, right?
Solution 2
Tests if a parameter is present in the request
httpServletRequest.getParameter( "Y" ) == null
The following code tests the value of the parameter if it is present
if ( httpServletRequest.getParameter( "Y" ) != null )
{
String value = httpServletRequest.getParameter( "Y" );
// Put your test code here. Include a empty value check
}
Walls
Virginia Tech Computer Science grad, who programs in the Northern VA/DC area. I've been exposed to a number of technologies including: RESTful web services, API development, various WCMS, and database ETL. I love coding and the puzzles that it throws at me daily. Whenever I'm not solving code challenges, I can be found playing video games or board/card games.
Updated on June 18, 2022Comments
-
Walls almost 2 years
I have a HTTP Request
javax.servlet.http.HttpServletRequest
that is passing in a value to be used in some code being handled in a Java web service using JAX-RS. The POST function in Java is consumingapplication/json
. There are two possible values to be passed into the request, call oneX
and the otherY
, assume both are Strings. The request requires at least one of the two possible values to be considered 'valid'.When the request comes in, if
X
is provided andY
is left out of the request entirely, what is the proper way to check to see ifY
is there? Would you check to see ifY.isEmpty()
orY == null
? ProvidingX
doesn't guaranteeY
is present, and vice versa. -
G. Bach about 11 yearsYou should move the line
String value = httpServletRequest.getParameter( "Y" );
before the if-clause so the request doesn't have to be evaluated twice. -
mightyrick about 11 yearsThe code isn't intended to be a single block of code. I'm only pointing out how to check whether a parameter is passed. And then also how to use that to check the value of a parameter.
-
Walls about 11 yearsThanks for the clarification, this answer is exactly what I needed. Thanks again and I'll remember the servlets tag in the future. (will accept when it lets me)
-
G. Bach about 11 yearsOh I see, so requesting the parameter twice is more an didactic choice to show what to do with it; I agree, this makes the purpose of each line clearer.
-
Haagenti almost 9 years@G.Bach +1 for the condescending sarcasm
-
G. Bach almost 9 years@ScareCrow This was more than two years ago so I may be wrong, but I actually don't think I was being sarcastic. Doing superfluous stuff to elucidate something is sometimes a valid didactic approach.