我写了一个简单的计数器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();
}
}
答案 0 :(得分:3)
如果您提出doGet
请求,则应该实施doPost
(和POST
。除非从normal servlet doXxx
methods之一调用processRequest
,否则无法调用// Convention would name the variable localCount, not local_count.
request.setAttribute("count", local_count);
。
通过请求属性公开变量:
getServletContext()
.getRequestDispatcher("/WEB-INF/showCount.jsp")
.forward(request, response);
转发到JSP:
Since loading, this servlet has been accessed ${count} times.
使用JSP EL(表达式语言)显示属性:
web.xml
如果未显示本地计数变量,请确保为最新的servlet修订版配置了{{1}}文件。