2011-12-08 50 views
0

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

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(); 
    } 
} 

回答

3

你应该实施doGet(和doPost如果你正在做POST请求)。除非从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修订版。

+0

感谢戴夫..但它显示计数变量的空值。我检查了web.xml。不知道该怎么办.. Iam novel to servlet .. – Rosh

+0

@Rosh现在你正在使用'processRequest',你应该为'GET'请求使用'doGet'。如果它在实现'doGet'后仍然显示'null',则需要发布更多细节。 –

+0

谢谢戴夫..它现在的作品.. :) – Rosh

相关问题