上QQ阅读APP看书,第一时间看更新
How to do it...
- 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
}
- 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.
- 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");
}
- 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);
}
- 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>");
}
}
- And we finally have a web page to call our servlet:
<body>
<a href="<%=request.getContextPath()%>/UserServlet">
<%=request.getContextPath() %>/UserServlet</a>
</body>