首先,感謝您閱讀我的問題..我在servlet中編程新手,我想出了這個問題:在我的web應用differrent用戶在相同的變量訪問這是我不想發生的事情。我有這樣的感覺,我沒有構建我的web應用程序,所以我會介紹它。在我的JSP頁面時,我想調用servlet做一些處理,我總是這樣稱呼它:Diffrerent用戶都可以訪問相同的變量在我的servlet
<a href="MyServlet?check">Some Html Code</a>
<a href="MyServlet?show">Some Html Code</a>
我選擇了這條路,因爲我想通過從JSP到servlet的參數(在這種情況下,「檢查」,以通知servlet「嗨,用戶點擊按鈕檢查」) - (我可以用另一種方式做到這一點?)無論如何!所以,在MyServlet我寫了這個:
MyServlet
import javax.servlet.http.HttpServlet
//i import and many others..
public class MyServlet extends HttpServlet{
private int count1; //these are the variables that see all the users
private String Title;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
if(request.getQueryString().equals("check")){
//do some stuff and then put a value (its not random) in the count1
count1 = 10; //lets say this value its 10 for a user1.
request.setAttribute("count", count1);
RequestDispatcher disp = getServletContext().getRequestDispatcher("/page1.jsp");
disp.forward(request, response);
}
else if (request.getQueryString().equals("show")){
//do some stuff and then put a value in the count1
title = "title"; //same here
request.setAttribute("title", title);
RequestDispatcher disp = getServletContext().getRequestDispatcher("/page2.jsp");
disp.forward(request, response);
}
}
所以在MyServlet我有嵌套的if-else語句在我的JSP中的所有鏈接。正如我在開始時所說的,我的應用程序中的所有用戶都可以訪問相同的變量。因此,如果user1點擊按鈕後檢查變量count1取值10,然後其他用戶2單擊相同的按鈕,變量取另一個值(例如20),那麼user1也具有值20 ...
我試圖把方法processRequest中的變量的定義,但然後我必須首先初始化變量,因爲我使用IDE環境,提醒我在行中我使用這些變量,變量可能尚未初始化。但我不想初始化變量,因爲每次我調用servlet時,所有變量init和i都會丟失之前的值。
我應該怎麼做?非常感謝!