我的目的只是通过servlet调用dialogationscoped bean。 bean本身应该将其属性ticketnumber
增加到4。
这是servlet:
@WebServlet
public class ConversationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Inject
private GreetingTicket ticket;
@Override
public void init() throws ServletException {
System.out.println("Init");
ticket.beginConversation();
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("DoGet");
PrintWriter writer = response.getWriter();
response.setContentType("text/html");
ticket.addTicketNumber();
System.out.println(ticket.getTicketNumber());
writer.println("<h1>" + ticket.getTicketNumber() + "</h1>");
if (ticket.getTicketNumber() == 4) {
System.out.println("END!");
ticket.endConversation();
}
writer.flush();
writer.close();
}
}
类GreetingTicket
是对话框CDI-Bean:
@ConversationScoped
public class GreetingTicket implements Serializable {
@Inject
Conversation conversation;
private static final long serialVersionUID = 1L;
private int ticketNumber;
public GreetingTicket() {
System.out.println("greeting Ticket");
}
public int getTicketNumber() {
return ticketNumber;
}
public void setTicketNumber(int ticketNumber) {
this.ticketNumber = ticketNumber;
}
public void addTicketNumber() {
ticketNumber++;
System.out.println("TicketNumber increased to "+ticketNumber);
}
public void beginConversation() {
if (conversation.isTransient()) {
System.out.println("Conversation Begin!");
conversation.begin();
}
}
public void endConversation() {
if (!(conversation.isTransient())) {
System.out.println("Conversation End!");
conversation.end();
}
}
}
现在的结果是,ticketnumber
的{{1}}始终只计入每个请求1个 - 为什么?
答案 0 :(得分:2)
@John Ament的评论是正确的。您需要将cid
参数从客户端传递到服务器。
因为使用以下代码,您总是开始新的对话:
@Override
public void init() throws ServletException {
System.out.println("Init");
ticket.beginConversation();
}
您需要传递名为cid
的请求参数,例如:
@WebServlet
public class ConversationServlet extends HttpServlet {
@Inject
private GreetingTicket ticket;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final String cid = request.getParameter("cid");
// TODO: pass above cid to the conversation
// ...
}
}