這個學期在公司做后臺相關的開發,決定將一些開發的要點和解決bug的過程記錄下來,每個星期一篇敦促自己進步
0309
今天遇到的問題是這樣的,在本地進行調試完成的一個Servlet應用,放在公司的服務器上就報錯
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getServletContext()Ljavax/servlet/ServletContext;
因為負責人也沒有對我開發的工具進行規定,我使用的是tomcat1.7,公司的服務器還是tomcat1.6,于是出現了這樣的問題
request.getServletContext()
ServletRequest的getServletContext方法是Servlet3.0添加的,這個可以看一下官方文檔
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getServletContext() 而Tomcat6只支持到Servlet2.5
對于老版本的tomcat應該先獲取到Session再獲取ServletContext或者通過Servlet自身拿到ServletConfig之后再獲取ServletContext
0310
今天一上午沒怎么做事。刷了幾道LeetCode,下午的時候leader給了一點點小需求讓我完成,需求是這樣的,需要給前端的網頁做一個計數,做一個用戶計數的功能,類似于產品已經為用戶提供了多少多少次服務,因為因為是內測階段,只是做一個樣子,于是嘿嘿嘿就是做點假(leader要求的)
于是我用servlet實現這樣的需求
- 一開始的時候想的就是在servlet
init
的時候在context中放一個數并且獲取一下時間,然后在post
方法中再次獲取時間兩個時間相減然后乘以一個隨機數,更新context中的計數,具體的代碼類似
@Override
public void init(ServletConfig config) throws ServletException {
config.getServletContext().setAttribute("adCount", 99L);
Date start = new Date();
System.out.println(start.getTime());
config.getServletContext().setAttribute("startTime",start.getTime());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long adCount = (Long) request.getSession().getServletContext().getAttribute("adCount");
long startTime = (Long) request.getSession().getServletContext().getAttribute("startTime");
long duration = (new Date().getTime() - startTime)/1000;
adCount += duration*new Random().nextInt(3);
System.out.println(adCount);
request.getSession().getServletContext().setAttribute("adCount", adCount);
response.getWriter().write(String.valueOf(adCount));
}
但是這樣的弊端就是服務器的時間開久了,數變化的太快了,要換一種方法
- 采用一個線程進行count的更新,這個線程要在服務器啟動的時候就創建并進行計數,于是就采用了監聽器,監聽context的創建,代碼見下面
public class AdCountListener implements ServletContextListener, Runnable {
private ServletContext context = null;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("context Destroyed");
}
@Override
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
context.setAttribute("adCount", 100L);
new Thread(this).start();
}
@Override
public void run() {
// long i = 100;
long adcount = 0;
Random random = new Random();
while (true) {
try {
int seek = random.nextInt(5);
adcount = (Long) this.context.getAttribute("adCount") + seek;
// System.out.println(adcount);
this.context.setAttribute("adCount", adcount);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
基本完成了這個任務,又混過去了一天,接著看書學習,最近需要補一點Nginx的知識,順便看一下公司里面的基礎類庫,現在真的覺得這種后臺的基礎類庫真是學習的好資料
本周畢.