如何在jsp页面中显示servlet结果?

如何在jsp页面中显示servlet结果?,jsp,servlets,Jsp,Servlets,我编写了一个简单的计数器servlet应用程序来显示访问页面的用户数量。我想在jsp页面中显示这个结果。但是我该怎么做呢?下面是我的代码 public class ServerClass extends HttpServlet { int counter = 0; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletExcepti

我编写了一个简单的计数器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();
    }
}

您应该执行
doGet
(如果您发出
POST
请求,则应执行
doPost
)。除非从其中一个调用,否则不会调用
processRequest

通过请求属性公开变量:

// Convention would name the variable localCount, not local_count.
request.setAttribute("count", local_count);
Since loading, this servlet has been accessed ${count} times.
转发到JSP:

getServletContext()
    .getRequestDispatcher("/WEB-INF/showCount.jsp")
    .forward(request, response);
使用JSP EL(表达式语言)显示属性:

// Convention would name the variable localCount, not local_count.
request.setAttribute("count", local_count);
Since loading, this servlet has been accessed ${count} times.

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

您应该实现
doGet
(如果发出
POST
请求,则应实现
doPost
)。除非从其中一个调用,否则不会调用
processRequest

通过请求属性公开变量:

// Convention would name the variable localCount, not local_count.
request.setAttribute("count", local_count);
Since loading, this servlet has been accessed ${count} times.
转发到JSP:

getServletContext()
    .getRequestDispatcher("/WEB-INF/showCount.jsp")
    .forward(request, response);
使用JSP EL(表达式语言)显示属性:

// Convention would name the variable localCount, not local_count.
request.setAttribute("count", local_count);
Since loading, this servlet has been accessed ${count} times.

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

谢谢。。但它显示count变量的空值。我检查了web.xml。我不知道该怎么办。。我对servlet很新奇。@Rosh现在您正在使用
processRequest
,您应该使用
doGet
来处理HTTP
GET
请求。如果在实现
doGet
后仍显示
null
,您需要发布更多详细信息。谢谢Dave。。但它显示count变量的空值。我检查了web.xml。我不知道该怎么办。。我对servlet很新奇。@Rosh现在您正在使用
processRequest
,您应该使用
doGet
来处理HTTP
GET
请求。如果在实现
doGet
后仍显示
null
,则需要发布更多详细信息。