JSP中如何为HTML隐藏域赋值含空格的内容?
Ah, I spot the problem right away! You didn't wrap the value attribute content in quotes. When browsers parse HTML, they treat spaces as attribute value separators—so when your q variable is "what is 2 +2?", the browser only reads "what" as the value and ignores everything after the first space.
The fix is simple: just wrap the value in single or double quotes. Here's your modified JSP code:
<% String q = request.getParameter("que"); out.print(q); out.print("<form action='postAns' method='post'>"+ "<input type='hidden' name='que' value='"+ q +"' >" + // Added single quotes around the value "<br>"+ "<input type='text' name='ans' >"+ "<input type='submit' value='post'>"+ "</form>"); %>
If your q string might contain single quotes (like "what's 2+2?"), using single quotes to wrap the value will break the HTML. In that case, switch to double quotes and escape any double quotes in the string. Even better, use JSTL's <c:out> tag—it automatically escapes special characters (quotes, <, >, etc.) to avoid parsing errors and XSS risks. Here's how that looks:
First, make sure you include the JSTL core taglib at the top of your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Then rewrite the form section:
<% String q = request.getParameter("que"); %> <%= q %> <form action='postAns' method='post'> <input type='hidden' name='que' value="<c:out value='${q}' />" > <br> <input type='text' name='ans' > <input type='submit' value='post'> </form>
This approach is more robust, especially if your input can include user-generated content.
内容的提问来源于stack exchange,提问作者Sophia

