我无法使用doPost
和我的方法post
的形式从一个 jsp 页面检索任何类型的参数到另一个 jsp 页面。请注意,下面是一个最小示例。
首先,我有两页:
这是search.jsp
:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
还有我的search_results.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
现在我有一个名为SearchServlet.java
的类:
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
无论我输入什么,结果(movie.title)最终总是空的,所以我search_results.jsp
world
。为什么我的参数没有传递给search_results.jsp
?
如果你绕过servlet,它就不会发生
查看表单操作
<form name="search" method="post" action="search_results.jsp">
您将 post 请求直接发送到 search_results.jsp
:您应该将其发送到 servlet(映射 @/search)
<form name="search" method="post" action="search">
然后从servlet中,您应该将请求转发到search_result.jsp
,您实际上这样做了。
除此之外,当您调用request.getParameter时,您必须记住,重要的是输入字段的名称,而不是id。应将id
属性更改为name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
最后,希望:)的"."(点)可能会导致问题:
session.setAttribute("movie.title", searchTitle);
检索属性时,点表示法表示您正在访问名为 movie 的对象中的字段
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
但是你没有那个...你有一个电影标题,大概是一个字符串。将属性名称更改为不带点的电影标题之类的名称,并以相同的方式在 jsp 中检索它。上面的行将变为:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
这应该可以解决问题。