How to do it...

  1. Let's create a User class for our recipe:
public class User {    private String name;    private String email;    //DO NOT FORGET TO IMPLEMENT THE GETTERS AND SETTERS}
  1. And then our servlet:
@WebServlet(name = "UserServlet", urlPatterns = {"/UserServlet"})public class UserServlet extends HttpServlet {        private User user;        @PostConstruct    public void instantiateUser(){        user = new User("Elder Moraes", "elder@eldermoraes.com");    }   ...
We use the @PostConstruct annotation over the instantiateUser() method. It says to the server that whenever this servlet is constructed (a new instance is up), it can run this method.
  1. We also implement the init() and destroy() super methods:
    @Override    public void init() throws ServletException { System.out.println("Servlet ...

Get Java EE 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.