View RSS Feed

My Java Tips

Implementing service method or doGet/doPost

Rate this Entry
by , 11-08-2011 at 05:37 PM (1333 Views)
"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.

Java Code:
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( ”
Welcome


“ );

	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.

Submit "Implementing service method or doGet/doPost" to Facebook Submit "Implementing service method or doGet/doPost" to Digg Submit "Implementing service method or doGet/doPost" to del.icio.us Submit "Implementing service method or doGet/doPost" to StumbleUpon Submit "Implementing service method or doGet/doPost" to Google

Tags: None Add / Edit Tags
Categories
Servlet

Comments