Implementing service method or doGet/doPost
24 March 2007“Whether to implement ’service’ method or ‘doGet/doPost’ in Http Servlet ?” ,Is question often heard at least in the beginners columns.
Actually the answer depends on the requirement.
First we should know that the purpose of servlet is to accept an HTTP request from a Web browser, and return an HTTP response. This is done by “service”, “doGet\ doPost” methods. Each of these include request object (HttpServletRequest) to receive data from client (browser) and also response object (HttpServletResponse) to send data to client (browser).
If you want to handle all the requests from a single method, then we should implement “service” method.
If you want to reply only to POST requests, then implement “doPost” method and if you want to reply only to GET requests, then implement “doGet” method.
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType( “text/html” ); // setting MIME type PrintWriter out = res.getWriter(); // output stream for writing data on the client side out.println(“ ); out.println( ”“ ); // Generating Client Side Code out.println( ”“ ); out.println( ”“ ); out.println( ”“ ); out.println( ” <h1>Welcome</h1> “ ); out.println( ”“ ); out.println( ”“ ); out.close(); } // assuming that we want to handle Post and Get requests separately public void doPost(ServletRequest req, ServletResponse res) throws ServletException, IOException { // code goes here } public void doGet(ServletRequest req, ServletResponse res) throws ServletException, IOException { // code goes here }
I hope this helps.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Implementing service method or doGet/doPost
Once we send request, servlet sevice method will be called. Now if I implement only doGet method who will call this method when i do a request of type GET. Does it implemented in default implementation of service method??
This is my big doubt.. please give detailed clarification..
Servlet Container will call that methods. Actually Servlet Container knows which method is used by the user as there is “request.getMethod()”. So Servlet Container will detect that and that proper methods are invoked.