2011-12-08 117 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

相關問題