我是网络技术的新手。我正在尝试做一个简单的程序,要求用户输入名称,如果有效,页面将重定向到另一个 jsp 文件 "RedirectIfSuccessful.jsp"
,如果无效,页面将重定向到 "RedirectIfFailed .jsp”
。我正在使用 response.sendRedirect()
方法来执行此操作。
重定向工作正常。但是,我希望从 RedirectIfSuccessful
和 RedirectIfFailed
文件中访问用户在表单中输入的名称,以便在输入有效名称时向用户显示:欢迎, nameEntered 失败时,消息将是 nameEntered 无效。请返回并重试。
我尝试从两个文件中使用 request.getParameter("name")
,但它返回了一个 null
值。我该怎么做才能访问它?
这是我的代码:这是 RedirectingPage.jsp
<%@ page
language="java"
import="java.util.regex.*"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String name = request.getParameter("name");
final String NAME_PATTERN = "^[a-zA-Z]{3,15}$";
Pattern pattern = Pattern.compile(NAME_PATTERN);
Matcher matcher = pattern.matcher(name);
if (matcher.matches() == true){
response.sendRedirect("RedirectIfSuccessful.jsp");
} else {
response.sendRedirect("RedirectIfFailed.jsp");
}
%>
这是我有表单的 HTML 文件:FormSubmit.html
<html>
<head>
<title> Welcome </title>
</head>
<body BGCOLOR="#FDF5E6">
<p> <i> This program redirects to a page if the name entered is valid and to another one if name
entered is invalid... This uses response.sendRedirect() </i> </p>
<form action="RedirectingPage.jsp" method="post">
<font size=6 face="Georgia"> <strong> Enter your name: </strong> </font> <input type="text" name="name"> <br> <br>
<input type="submit" name="btn" value="Submit" >
</form>
</body>
</html>
这是成功的页面:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Successful Submit </title>
</head>
<body>
<font face="Georgia" size="6"> Hello, <% request.getParameter("name"); %> </font>
</body>
</html>
我希望你能提供帮助,我的问题很清楚。谢谢:)
最佳答案
重定向包括向浏览器发送一个响应,说“请转到以下 URL:RedirectIfSuccessful.jsp”。
当它收到这个响应时,浏览器发送一个新的请求到RedirectIfSuccessful.jsp
,没有任何参数。所以得到参数name
来自 RedirectIfSuccessful.jsp
将返回 null。
如果你想访问重定向后的名字,你需要发送一个重定向到RedirectIfSuccessful.jsp?name=<the name the user entered>
关于html - 在 response.sendRedirect() 中传递参数 - JSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14020234/