因此,我有一個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