gpt4 book ai didi

java - Servlet session 不是持久的

转载 作者:行者123 更新时间:2023-12-02 06:37:23 24 4
gpt4 key购买 nike

我有一个如下所示的 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

我希望它按照状态机中定义的状态移动,但它总是返回相同的行

user: John

current state: null

new state: NEW

售票机很简单

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

我在这里做错了什么?

最佳答案

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

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

关于java - Servlet session 不是持久的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com