[java] What does request.getParameter return?

// index.jsp

<form method="post" action="backend.jsp">
<input type="text" name="one" />
<input type="submit value="Submit" />
</form>

In backend.jsp what does request.getParameter("one"); return?

request.getParameter("one").getClass().getName();

returns java.lang.String, so it must be a String right?

However I cannot do

String one = request.getParameter("one");
if (!"".equals(one)) {}

or

if (one != null) {}

This is obvious, because variable one does not return null. Is

if (one.length() > 0) {}

only way to go, or are there better solutions or a better approach? I am considering both solutions to be on jsp. Using a servlet (although jsp is a servlet) is a different use case in this scenario.

This question is related to java jsp

The answer is


Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

<c:if test='${not empty param.foo}'>
    This page code gets rendered.
</c:if>

Per the Javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").


String onevalue;   
if(request.getParameterMap().containsKey("one")!=false) 
{
onevalue=request.getParameter("one").toString();
}