2010-11-16 54 views
1

我在JSP上练习了一下,想要创建一个简单的表达式字段。下面的代码工作正常。现在我希望最后的输入保留在表单字段中。所以当我输入一个值“password”和一个“名称”时,无论if-else语句的结果如何,这两个值都应该保留在表单字段中。

例如我输入“用户”和“1234”,然后按提交表格字段得到清除,我不想这样做。提交后这两个值应留在那里。很抱歉,我不知道如何解决这个问题。

我的建议是使用application.setAttribute(“”,)和application.getAttribute(“”),但我不知道如何。我很乐意提供任何建议。谢谢!

不要使用JSP重置表单字段中的输入

<?xml version="1.0" encoding="iso-8859-1"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de"> 

<head> 
    <title>Practice</title> 
</head> 

<body> 

<h2>Practice</h2> 
<h3>Please enter your name and the password.</h3> 
<form method="post" action=""> 
    <table> 
<tr><td style="text-align:center">Name</td> 
<td><input type="text" name="name" size="80" /></td> 
</tr> 
<tr><td style="text-align:center">Password</td> 
<td><input type="text" name="password" size="80" /></td> 
</tr> 
<tr><td><input type="submit" value="Send" /></td> 
<td><input type="reset" value="Reset" /></td> 
</tr> 
</table> 
</form> 

<%-- Testing name and password. --%> 
<% String name = request.getParameter("name"); 
    String password = request.getParameter("password"); 
    if (name != null && name.equals("user") && password != null && password.equals("1234")) 
    { 
%> 
     <p>Your Input is correct!</p> 
<% } 

    else 
    { 
%> 
     <p>Your input is not correct!</p> 
<% } 
%> 

</body> 


</html> 

回答

2

只需填写自己的value属性与提交的值。在正常 JSP EL这将是:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> 
... 
<input type="text" name="username" value="${fn:escapeXml(param.username)}" /> 
<input type="password" name="password" value="${fn:escapeXml(param.password)}" /> 

${param.username}做基本相同,以下丑陋的scriptlet<% if (request.getParameter("username") != null) { out.print(request.getParameter("username")); } %>,只有在一个更干净和consice方式。

JSTL fn:escapeXml()功能是有防止你从XSSattacks。否则,用户将能够输入"><script>alert('xss');</script>作为名称并执行它(当然,使用更恶意的JavaScript将cookie发送到另一个服务器,而不是简单的警报)。

+0

这是一个非常简单和很好的解决方案。非常感谢你。 – Ordo 2010-11-16 19:36:08