Servlet会话不是持久的

时间:2013-10-21 10:33:07

标签: java session servlets cookies curl

我有一个像以下

的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);                
        }           
    }
}
}

我正在尝试为每个请求票证的用户存储票证机器的状态。我在Oracle WebLogic Server上运行它并使用cURL get请求测试它,如下所示

curl --cookie "user=John" 127.0.0.1:7001/myApp/Ticket

我希望它会在状态机中定义,因为它们在状态机中定义,但它总是返回相同的行

  

用户:约翰

     

当前状态:null

     

新州:新

售票机非常简单

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;
    }
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

创建会话时,它会添加响应cookie会话参数,例如会话ID。您对cURL的命令不存储来自服务器的cookie。您必须按以下方式存储Cookie curl --cookie oldcookies.txt --cookie-jar newcookies.txt http://www.example.com

另请阅读有关http://curl.haxx.se/docs/httpscripting.html

的Cookie的部分