因此,我有一个JSP表单,它只是接收一个查询字符串,将它传递给一个servlet,然后设置一些HttpServletRequest属性并转发给另一个jsp。出于某种原因,在最终的jsp中,所有的属性都返回null,就好像它们没有被设置一样。从JSP到Servlet到JSP的传递属性
CatQuery.jsp
<html>
<head>
<title>Category Query</title>
<meta http-equiv="Content-Type" content="text/html' charset=iso-8859-1">
</head>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<form name="queryForm" method="post" action="CategoryRetrieve">
<td><div align="left">Query:</div></td>
<td><input type="text" name="queryStr"></td>
<td><input type="Submit" name="Submit"></td>
</form>
</td>
</tr>
</table>
</body>
</html>
它调用这个servlet,CategoryRetrieveServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String queryStr = request.getParameter("queryStr");
CategoryIndex catIndex = new CategoryIndex(indexDir);
Map<String, Float> weights = catIndex.queryCategory(queryStr, numTopWords, numTopDocs, numCategories);
if(weights!=null){
request.setAttribute("CATWEIGHTS", weights);
request.setAttribute("HASRESULTS", "true");
}
else {
request.setAttribute("HASRESULTS", "false");
}
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(target);
dispatcher.forward(request, response);
}
,反过来,转发到该JSP页面,CatDisplay.jsp
<%@ page import="java.util.*" %>
<html>
<head>
<title>Category Search Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<table width="1000" border="5" cellspacing="0" cellpadding="0">
<% Map<String, Float> catweights = null;
catweights=(Map<String,Float>)request.getAttribute("CATWEIGHTS");
%>
hasResults is
<%= request.getAttribute("HASRESULTS") %>
<% if (catweights==null){ %> Catweights is null
<% }
else {
for (Map.Entry<String,Float> e : catweights.entrySet()){
%>
<tr><td>
<%= e.getKey()%>
</td><td>
<%= e.getValue()%>
</td></tr>
<% }
}
%>
</table>
</html>
当我提交查询字符串时,结果页面显示“hasResults is null Catweights is null”。任何人都可以告诉我为什么我的属性没有设置?
仔细检查代码;方法'catIndex.queryCategory'返回null。 – adatapost 2012-08-09 01:55:30
您应该发布'catIndex.queryCategory(...){}'方法的定义。 – Prateek 2012-08-09 04:11:45
为什么你使用'ServletContext'来获得'RequestDispatcher'?你可以通过'request.getRequestDispatcher(target)'直接访问它。 – Logan 2012-08-09 06:11:52