0
我有一個像下面servlet會話不是持久的
public class Ticket extends HttpServlet {
private static final long serialVersionUID = 1L;
public Ticket() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// check cookies
Cookie[] receivedCookies = request.getCookies();
if(receivedCookies != null){
Cookie user = receivedCookies[0];
response.getWriter().println("user: " + user.getValue());
response.addCookie(user);
// check session
HttpSession session = request.getSession(true);
Object atribVal = session.getAttribute(user.getValue()); // get a current state
if(atribVal == null){
response.getWriter().println("current state: null");
}
else{
response.getWriter().println("current state: " + atribVal.toString());
}
String newState = TicketMachine.getNextState(atribVal); // get a new state based on the current one
response.getWriter().println("new state: " + newState);
if(newState == "COMPLETED"){ // ticket completed, destroy session
session.invalidate();
return;
}
else{ // move to the next state
session.setAttribute(user.getValue(), newState);
}
}
}
}
一個servlet我想存儲售票機的狀態誰請求票每個用戶。我的Oracle WebLogic Server上運行此和測試它使用捲曲GET請求看起來像下面
curl --cookie "user=John" 127.0.0.1:7001/myApp/Ticket
我希望它通過狀態,因爲它們是在狀態機定義爲移動,但它總是返回同樣的思路
用戶:約翰
當前狀態:空
新狀態:新
售票機很簡單
public class TicketMachine {
public static String getNextState(Object currentState){
if(currentState == null)
return "NEW";
switch(currentState.toString()){
case "NEW":
return "PAYMENT";
case "PAYMENT":
return "COMPLETED";
}
return null;
}
}
我在做什麼錯在這裏?
還可以閱讀關於cookies的部分在捲曲使用--cookie-JAR選項,並檢查來自服務器的響應可能是一個好主意。 – Nishan
那麼你如何確保'Cookie user = receivedCookies [0];'是你正在尋找的cookie,它將是服務器'sessionid'或其他任何東西,還要注意將字符串與'=='比較,使用'等於()'而不是。 – 2013-10-21 10:50:18
@ user2511414這僅僅是一個點servlet的證明,所以我並不需要確保它。 –