2010-11-16 51 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