1

I want a Servlet to perform always the same tasks. Regardless of if it is a GET or POST. At the moment I just call the doGet() from doPost(), which works fine.

Then I tried overriding the service() method, and I thought it would just work the same way. But it does not!

The code somehow gets executed, but the response does not generate the webpage:

response.getWriter();
response.println(string); 

This code works for the doGet/doPost methods, but not for the service. Why?

Servlet:

class MyWebServlet extends HttpServlet {
    @Override
    public void service(ServletRequest request, ServletResponse response) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String string = "teststring";
        out.println(string);
    }
}
4

3 に答える 3

3

Change the public void service(ServletRequest request, ServletResponse response) to public void service(HttpServletRequest request,HttpServletResponse response) and it should work.

于 2012-09-28T09:31:37.543 に答える
2

You overrided the wrong method.

So why your compiler hasn't complained since you wrote the @Override annotation?

Actually, your servlet inherits two service methods but without the same parameters => method overloads.

  • public void service(ServletRequest request, ServletResponse response) is implemented by the GenericServlet class, meaning your servlet's first parent class.

  • public void service(HttpServletRequest request, HttpServletResponse response) is implemented by HttpServlet class.
    It is this one that you need to override.

You could effectively override the first instead, but you'd loose the http process and nothing will be written to your browser. It explains your issue.

GenericServlet defines a generic, protocol-independent servlet, and so hasn't a direct relation with the http protocol.

于 2012-09-28T09:24:36.380 に答える
-1

Look at the below example. When the user performs GET the doGet will be called, if they perform Post, it will call doPost which intern calls doGet.

   //Sample Code:
    @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      PrintWriter writer = resp.getWriter();
      writer.println("Hello World");
      writer.close();
   }

   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
   }
于 2012-09-28T09:36:43.280 に答える