【问题标题】:How to show servlet results in jsp page?如何在jsp页面中显示servlet结果?
【发布时间】:2011-12-08 02:15:42
【问题描述】:

我编写了一个简单的计数器 servlet 应用程序来显示访问页面的用户数量。我想在 jsp 页面中显示这个结果。但是我该怎么做呢?以下是我的代码...

public class ServerClass extends HttpServlet {
int counter = 0;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
int local_count;
synchronized(this) {
local_count = ++counter;
}
out.println("Since loading, this servlet has been accessed " +
        local_count + " times.");
out.close();
    }
}

【问题讨论】:

    标签: jsp servlets


    【解决方案1】:

    您应该实现doGet(如果您提出POST 请求,则应该实现doPost)。除非从 normal servlet doXxx methods 之一调用,否则不会调用 processRequest

    通过请求属性公开变量:

    // Convention would name the variable localCount, not local_count.
    request.setAttribute("count", local_count);
    

    转发到 JSP:

    getServletContext()
        .getRequestDispatcher("/WEB-INF/showCount.jsp")
        .forward(request, response);
    

    使用JSP EL(表达式语言)显示属性:

    Since loading, this servlet has been accessed ${count} times.
    

    如果本地计数变量未出现,请确保您的 web.xml 文件已配置为最新的 servlet 修订版。

    【讨论】:

    • 感谢 Dave.. 但它显示计数变量的值为空。我检查了 web.xml。不知道该怎么办..我对servlet很新颖..
    • @Rosh 现在你使用的是processRequest,你应该使用doGet 来处理HTTP GET 请求。如果在实施doGet 后仍然显示null,则需要发布更多详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2013-11-25
    相关资源
    最近更新 更多