i'm unsure how to phrase my question. but I've got an html form submitting data to a java backend which handles the data and submits it to the database.
the java form grabs each of my values using the javax.servlet.http.HttpServletRequest
library
so in order to grab the value of:
<input type="text" name="firstName">
In the java page I would do:
String firstName = request.getParameter("firstName");
this works great, however if my input is two words, it will only return the first one.
so say i put in "John George" for my firstName, the java page will only receive "John".
I can't figure out why.
Form Code:
foot = "<form method='POST' actio开发者_JAVA百科n='Submit'>";
//path to java servlet
foot += "<input type='hidden' name='firstName' value="+firstName+">";
foot += "<input type='hidden' name='lastName' value="+lastName+">";
foot += "<input type='hidden' name='school' value="+school+">";
foot += "<input type='hidden' name='email' value="+email+">";
Each attribute value should be wrapped with quotes. Your attributes are wrapped in quotes (which most browsers can deal with) but your value attributes don't have any quote wrapping. So your output is looking something like this:
<input type='hidden' name='firstName' value=John George>
Because the value is not wrapped in quotes therefore the browser is interpreting "John" to be the value of the value attribute and "George" to be a new attribute without a value.
Wrapping your value attribute in quotes should fix this.
foot = "<form method=\"POST\" action=\"Submit">";
//path to java servlet
foot += "<input type=\"hidden\" name=\"firstName\" value=\""+firstName+"\">";
foot += "<input type=\"hidden\" name=\"lastName\" value=\""+lastName+"\">";
foot += "<input type=\"hidden\" name=\"school\" value=\""+school+"\">";
foot += "<input type=\"hidden\" name=\"email\" value=\""+email+"\">";
The reason is pretty simple: Look at the HTML source code in your browser and you'll see:
<input type='hidden' name='firstName' value=John George>
So you have an input
element with 4 attributes and the last attribute is George
.
Solution:
- Don't forget to quote your strings
- NEVER forget to HTML escape text values which you add to the HTML
The second point allows mischievous people to do very nasty things with your web site. See Cross-site scripting.
So the correct code would be:
foot += "<input type='hidden' name='firstName' value='"+StringEscapeUtils.escapeHtml(firstName)+"'>";
StringEscapeUtils
can be found in commons-lang.
Given that firstName = "John George"
this: "<input type='hidden' name='firstName' value="+firstName+">";
renders in HTML to
<input type='hidden' name='firstName' value=John George>
So "George" is interpreted as attribute. Please try to add the quotes correctly:
"<input type='hidden' name='firstName' value='" + firstName + "'>"
精彩评论