Perform the following steps to complete this recipe:
- First, we create a User Plain Old Java Object (POJO):
public class User implements Serializable{
private Long id;
private String name;
public User(long id, String name){
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- Then, we create a slow UserBean object to return User:
@Stateless
public class UserBean {
public User getUser(){
long id = new Date().getTime();
try {
TimeUnit.SECONDS.sleep(5);
return new User(id, "User " + id);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
return new User(id, "Error " + id);
}
}
}
- Finally, we create our asynchronous servlet:
@WebServlet(name = "UserServlet", urlPatterns = {"/UserServlet"}, asyncSupported = true)
public class UserServlet extends HttpServlet {
@Inject
private UserBean userBean;
private final Jsonb jsonb = JsonbBuilder.create();
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException {
AsyncContext ctx = req.startAsync();
ctx.start(() -< {
try (PrintWriter writer =
ctx.getResponse().getWriter()){
writer.write(jsonb.toJson(userBean.getUser()));
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
ctx.complete();
});
}
@Override
public void destroy() {
try {
jsonb.close();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}