You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:14:06