I’m learning servlets 3.0 through a set of code examples and the purpose of many of the methods is not making any sense to me. Except the service method.
The output is “Hello from MyServlet”. But, what’s with all the other methods?
@WebServlet(name = "MyServlet", urlPatterns = { "/my" })
public class MyServlet implements Servlet {
What is the line below trying to do?
private transient ServletConfig servletConfig;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
@Override
public ServletConfig getServletConfig() {
return servletConfig;
}
@Override
public String getServletInfo() {
return "My Servlet";
}
//This is the only method that makes sense to me. All the others, I have no
idea why they are in here.
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
String servletName = servletConfig.getServletName();
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.print("<html><head></head>" + "<body>Hello from " + servletName
+ "</body></html>");
}
@Override
public void destroy() {
}
}
I’m not sure what tutorials/examples you’ve read, but you should rather be extending the
HttpServletabstract class, not implementing theServletinterface. You indeed don’t directly need any of them. TheHttpServlethas already implemented all the necessary boilerplate for you.All with all, this is what you minimally need:
(even though I understand that this is just a learning exercise, I’d like to note that emitting HTML in a servlet this way is a poor practice, there JSP should be used for)
As to what they all did, well, the
init()offers you the possibility to perform initialization based on servlet configuration during servlet’s construction. Thedestroy()offers you the possibility to perform cleanup during servlet’s destroy. The property and those getter methods are just necessary in order to satisfy theServletinterface’s contract. Note that none of them are explicitly specific to Servlet 3.0. They existed already in older versions.See also: