Previously, we configure our HelloWorld servlet by hooking up with url “/helloworld” in the web.xml. There is another way of configuring this and it is called the servlet annotation and specifically we are going to use @WebServlet.
Let’s start coding
Back in the HelloWorldServlet.java, before the class name, we simply put @WebServlet(“/helloworld”), that is with the url pattern within the parenthesis. Let’s remove the <servlet> and <servlet-mapping> tag inside the web.xml and restart the applciation. When the application has restarted, you should be able see the same result.
package com.davidcheah.webapplication.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/helloworld")
public class HelloServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello World</h1>");
out.println("<p>The time is " + new Date() + "</p>");
out.println("</body></html>");
out.close();
}
}
Source Code
https://github.com/tattwei46/FirstServletApplication/commit/2a08c4d01b993d1ac42f43002d3ea5bcd6781372