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", "[email protected]");
}

...
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 " + this.getServletName() +
" has started");
}

@Override
public void destroy() {
System.out.println("Servlet " + this.getServletName() +
" has destroyed");
}
  1. And we also implemented 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 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. And we finally have a web page to call our servlet:
    <body>
<a href="<%=request.getContextPath()%>/UserServlet">
<%=request.getContextPath() %>/UserServlet</a>
</body>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.158.134