将属性从JSP传递到Servlet到JSP

时间:2012-08-09 00:19:53

标签: jsp servlets attributes setattribute getattribute

所以,我有一个JSP表单,它只接受一个查询字符串,将它传递给一个servlet,然后设置一些HttpServletRequest属性并转发到另一个jsp。出于某种原因,在最终的jsp中,所有属性都返回null,就好像它们尚未设置一样。

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为null Catweights为null”。谁能告诉我为什么我的属性没有被设置?

1 个答案:

答案 0 :(得分:2)

已解决:属性正确传递,但我的tomcat实例需要重新启动才能更新servlet代码中的更改。一种herp-derp。与任何html页面一样,JSP页面将自动更新,但您必须在更改servlet后重新编译并重新启动Tomcat实例。