我不知道如何创建你的链接,但它看起来像你会做一个GET请求,你的servlet。知道这一点,每个servlet都应该管理页面的计数器命中,并且由于每个用户都应该知道这个值,所以最好将它保存在应用程序范围中,而不是请求或会话中。更多这here和How do servlets work? Instantiation, sessions, shared variables and multithreading。
我将发布一个处理单个链接计数器的jsp和servlet样本。你应该可以使用它来处理你的链接。在不同的浏览器
的index.jsp(其它元素,如<head>
和<html>
是例子wortheless)
<body>
Hit the button to add a value to the application counter
<br />
<form action="HitCounterServlet" method="GET">
<input type="submit" value="Add counter hit" />
</form>
<br />
Total hits: ${applicationScope['counter']}
</body>
HitCounterServlet
@WebServlet(name = "HitCounterServlet", urlPatterns = {"/HitCounterServlet"})
public class HitCounterServlet extends HttpServlet {
private static final Object counterLock = new Object();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = request.getServletContext();
updateHitCounter(context);
String originalURL = "index.jsp";
//in case you want to use forwarding
//request.getRequestDispatcher(originalURL).forward(request, response);
//in case you want to use redirect
response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/" + originalURL));
}
private void updateHitCounter(ServletContext context) {
//since more than a request can try to update the counter
//you should protect the update using a synchronized block code
synchronized(counterLock) {
Integer counter = (Integer)context.getAttribute("counter");
if (counter == null) {
counter = 0;
}
counter++;
context.setAttribute("counter", counter);
}
}
}
试试这个,你会看到柜台如何保持相同的状态跨越他们。
为了保存在数据库中击中柜台,你应该改变在updateHitCounter
功能的代码,代码将连接到数据库,并执行UPDATE语句到你的数据库字段。
我该如何使用它?你能给我任何示例代码吗? – 2013-02-13 03:43:07
这是一个不好的例子。OP正在学习正确的方式,并且您正在引导他/她使用脚本。请阅读[如何避免JSP文件中的Java代码?](http://stackoverflow.com/a/3180202/1065197) – 2013-02-13 06:13:18
好吧4我指出,我将审查代码并使用OP的最佳解决方案进行更新正在寻找.. – Lucky 2013-02-13 13:10:17