huzefa biyawarwala
huzefa biyawarwala

Reputation: 657

Use of the Service method in Servlet while there is already doGet and other 6 methods present

I was coding a simple servlet . which just prints the values passed by user , or in the respective URL parameters. Now when implementing the doGet method , i saw that the same function can also be performed by service method . The code for it below :

protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {


    PrintWriter o = resp.getWriter();
    String user = req.getParameter("username");

    HttpSession session = req.getSession();
    ServletContext context = req.getServletContext();

    if (user != "" && user != null) {

        session.setAttribute("myhuzu", user);
        context.setAttribute("myhuzu", user);
    }

    o.println("request parameter has value " + user);
    o.println("session parameter  has user name as "
            + session.getAttribute("myhuzu"));

    o.println("context parameter  has user name as "
            + context.getAttribute("myhuzu"));

    o.println("init parameter  has user name as "
            + getServletConfig().getInitParameter("default"));


}

}

So my question is , why do we need the doGet or doPOST methods , when service method itself is taking care of all that thing.As the above code runs perfect , it also runs perfect if kept in doGet method , so why they din't kept only one out of them ? Note : I very well know the servlet life cycle and other related concepts , so please don't explain all that concepts.

Upvotes: 1

Views: 2776

Answers (4)

Kennedy Oliveira
Kennedy Oliveira

Reputation: 2261

The service method in the HttpServlet class check which method is in the head request and redirect to a specified method like when its a get request the doGet method will be called, its used when your servlet will answer with diferrent purpose for diferent methods, like in a REST service, when you have a GET request, you'll return an information, but when you have a PUT request, you'll update an information, so the servlet provide this method for you.

Plus it guarantee that you servlet won't answer to the wrong request, using the service method like you did, i can call your servlet even with a strange request like "request method TEST" and the servlet will responde, and keep your code cleaner.

See the original service code:

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long errMsg;
        if(method.equals("GET")) {
            errMsg = this.getLastModified(req);
            if(errMsg == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince = req.getDateHeader("If-Modified-Since");
                if(ifModifiedSince < errMsg) {
                    this.maybeSetLastModified(resp, errMsg);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if(method.equals("HEAD")) {
            errMsg = this.getLastModified(req);
            this.maybeSetLastModified(resp, errMsg);
            this.doHead(req, resp);
        } else if(method.equals("POST")) {
            this.doPost(req, resp);
        } else if(method.equals("PUT")) {
            this.doPut(req, resp);
        } else if(method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if(method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if(method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg1 = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg1 = MessageFormat.format(errMsg1, errArgs);
            resp.sendError(501, errMsg1);
        }

    }

It reacts diferrent based on what request method is used.

If you do a custom http request, you can set the method you want, instead of GET or PUT or DELETE you could send TEST and your service would throw a "Method not implementation" exception, but if you override the service method it simple will answer, your servlet code will be executed anyway.

Upvotes: 4

Ghayth
Ghayth

Reputation: 972

The service method can serve both Get and Post requests.

But let's assume that there is a scenario where you want to insure no one calls your servlet except using POST requests, e.g.: when submitting a Login request

if you allow anyone to use GET in such scenario; you will be making serious security vulnerabilities (as the GET requests will reveal all Login information within the URL)

So you implement the POST method as an assurance.

Upvotes: 0

Sharp Edge
Sharp Edge

Reputation: 4192

There might be scenarios like you want to respond the GET request in a specific way and the POST request in a way.GET requests are generally meant for just fetching the data and giving it back.And POST request is for updating some thing in the backend.That's why it is called idempotent. But if you had overridden the service method instead,you will have only one way of responding.

Upvotes: 1

DaveH
DaveH

Reputation: 7335

You have doGet and doPost so that the servlet can react in different ways depending upon the HTTP verb that is used when accessing it.

The spec also defines doHead, doOptions etc.

Upvotes: 1

Related Questions