Jakarta EE Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

You need to perform the following steps to complete this recipe:

  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. Now, let's add 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 used the @PostConstruct annotation over the instantiateUser() method here. It says to the server that whenever this servlet is constructed (a new instance is up and running), it can run this method.
  1. We also need to implement the init() and destroy() super methods:
    @Override
public void init() throws ServletException {
System.out.println("Servlet " + this.getServletName() +
" has started");
}

@Override
public void destroy() {
System.out.println("Servlet " + this.getServletName() +
" has destroyed");
}
  1. We also need to implement doGet() and doPost():
    @Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doRequest(request, response);
}
  1. Both doGet() and doPost() will call our custom method, that is, doRequest():
    protected void doRequest(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet UserServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Servlet UserServlet at " +
request.getContextPath() + "</h2>");
out.println("<h2>Now: " + new Date() + "</h2>");
out.println("<h2>User: " + user.getName() + "/" +
user.getEmail() + "</h2>");
out.println("</body>");
out.println("</html>");
}
}
  1. Finally, we have a web page so that we can call our servlet:
    <body>
<a href="<%=request.getContextPath()%>/UserServlet">
<%=request.getContextPath() %>/UserServlet</a>
</body>