Saturday, July 28, 2007

Good Servlet Bad Servlet

lest try to code the same servlet in good way and bad way


public class Bad_Servlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
// BAD : this line created one more java object to be GC

public void init(ServletConfig config)
throws ServletException
{
super.init(config);
System.out.println("LOG : Init called");
// BAD : using sop is bad it will require Servlet
// to synchronize disk actions and http response.
}

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
String output="<html>";
output+="<head><title>Bad Servlet</title></head>";
output+="<body>";
output+="<p>The servlet has received a GET. This is the reply.</p>";
output+="</body></html>";
// BAD : pat ur backs once if u judged using variable will create one
// more object for Garbage Colection PAT ur back many times if u judged
// that using + operator with "temp" will cr8 many temp string objects 4 GC

out.println(output);
out.close();
}

//BAD : overriding destroy() will help u freeing ur resources ..
// that will reduce burden on webServer GC cant go ahead until
// it is sure resources re free
}



now the same code in Good servlet


public class Good_Servlet extends HttpServlet {

public void init(ServletConfig config)
throws ServletException
{
super.init(config);
}

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Good Servlet</title></head>");
out.println("<body>");
out.println("<p>received a GET. This is reply.</p>");
for ( int i = 10; i > 0; i-- )
{
out.print( "<h1>" );
out.print( i );
out.println( "</h1>" );
out.flush();
// make sure the browser see the count
// another use of using println()
try
{
Thread.sleep( 1000 );
// this loop takes time
// BUT user wont experience difference
}
catch ( InterruptedException e ) { }
/*
If a page contains a number of graphics
(in a header, for example), each of those graphics
needs a separate HTTP request to be loaded.
If the servlet calls flush() after writing the
IMG tags for the graphics into the PrintWriter,
the browser can start loading the graphics
while the servlet is still processing the original request.
This reduces the amount of time required to display the
complete page in the browser because the separate requests
can be handled concurrently.
*/

}
out.println("</body></html>");
// The difference here is that all output is written directly
// to the PrintWriter, which does not require creating any
// intermediate objects
out.close();
}

public void destroy(){
}
}

No comments: