1

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() {
}

}

AppSensei
  • 8,270
  • 22
  • 71
  • 99

1 Answers1

3

I'm not sure what tutorials/examples you've read, but you should rather be extending the HttpServlet abstract class, not implementing the Servlet interface. You indeed don't directly need any of them. The HttpServlet has already implemented all the necessary boilerplate for you.

All with all, this is what you minimally need:

@WebServlet("/my")
public class MyServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletName = getServletConfig().getServletName();
        response.setContentType("text/html");
        response.getWriter().print("<html><head></head>" 
            + "<body>Hello from " + servletName + "</body></html>");
    }

}

(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. The destroy() offers you the possibility to perform cleanup during servlet's destroy. The property and those getter methods are just necessary in order to satisfy the Servlet interface's contract. Note that none of them are explicitly specific to Servlet 3.0. They existed already in older versions.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555