- Jakarta EE Cookbook
- Elder Moraes
- 264字
- 2021-06-24 16:12:44
How to do it...
You need to perform the following steps to complete this recipe:
- 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
}
- 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.
- 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");
}
- 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);
}
- 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>");
}
}
- Finally, we have a web page so that we can call our servlet:
<body>
<a href="<%=request.getContextPath()%>/UserServlet">
<%=request.getContextPath() %>/UserServlet</a>
</body>
推薦閱讀
- Python快樂(lè)編程:人工智能深度學(xué)習(xí)基礎(chǔ)
- Maven Build Customization
- 控糖控脂健康餐
- Web Scraping with Python
- Mastering macOS Programming
- Windows Forensics Cookbook
- Go并發(fā)編程實(shí)戰(zhàn)
- UML 基礎(chǔ)與 Rose 建模案例(第3版)
- Cybersecurity Attacks:Red Team Strategies
- Java Web開(kāi)發(fā)就該這樣學(xué)
- 用戶體驗(yàn)可視化指南
- INSTANT Yii 1.1 Application Development Starter
- Kubernetes進(jìn)階實(shí)戰(zhàn)
- Web App Testing Using Knockout.JS
- 零基礎(chǔ)學(xué)HTML+CSS