Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

How can I retain HTML form field values in JSP after submitting form to Servlet?

After submitting data in the HTML from, a servlet adds these data to my DB and forwards a result message to a JSP page. I want to retain the initially submitted values in the form after the forward.

Is it sensible to make an object in a servlet and add all the parameters I receive and send it with a request to JSP? Is there another better way?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could access single-value request parameters by ${param}.

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="foo" value="${fn:escapeXml(param.foo)}">
<textarea name="bar">${fn:escapeXml(param.bar)}</textarea>
...
<input type="radio" name="faz" value="a" ${param.faz == 'a' ? 'checked' : ''} />
<input type="radio" name="faz" value="b" ${param.faz == 'b' ? 'checked' : ''} />
<input type="radio" name="faz" value="c" ${param.faz == 'c' ? 'checked' : ''} />
...
<select name="baz">
    <option value="a" ${param.baz == 'a' ? 'selected' : ''}>label a</option>
    <option value="b" ${param.baz == 'b' ? 'selected' : ''}>label b</option>
    <option value="c" ${param.baz == 'c' ? 'selected' : ''}>label c</option>
</select>

Do note that JSTL's fn:escapeXml() is necessary in order to prevent XSS attacks. See also XSS prevention in JSP/Servlet web application.

You could access multi-value request parameters by ${paramValues} and EL 3.0 streams.

<input type="checkbox" name="far" value="a" ${paramValues.far.stream().anyMatch(v->v == 'a').get() ? 'checked' : ''} />
<input type="checkbox" name="far" value="b" ${paramValues.far.stream().anyMatch(v->v == 'b').get() ? 'checked' : ''} />
<input type="checkbox" name="far" value="c" ${paramValues.far.stream().anyMatch(v->v == 'c').get() ? 'checked' : ''} />
...
<select name="boo" multiple>
    <option value="a" ${paramValues.boo.stream().anyMatch(v->v == 'a').get() ? 'selected' : ''}>label a</option>
    <option value="b" ${paramValues.boo.stream().anyMatch(v->v == 'b').get() ? 'selected' : ''}>label b</option>
    <option value="c" ${paramValues.boo.stream().anyMatch(v->v == 'c').get() ? 'selected' : ''}>label c</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...