Tuesday, February 4, 2014

Servlets Introduction

  • Servlets run on a single process using threads 
  • Overhead of additional requests are small as it run on single process 
  • Servlets requires java programming skills 
  • JSP and servlets enables to develop modular ,maintainable ,scalable and portable applications 
  • Servlets run on a web containter or servlet egine 
  • Servlets can generate HTML response object 
  • Servlets are compiled into byte code.Servlets are java class file.On requests this byte codes are loaded into the memory 
  • Serlets talk to the client using web server 
  • Client request first go to the web server and webserver re-direct the requests to the container . Containter calls the generic servlet interface which calls HTTPServlet class and My Servlet class 
  • The response from Servlet again go back to the container and from there to web server and finally to the browser 
  • Most of the containter implementations are in java 
  • Servlet container instatiate the objects that encapsulate request or response .
  • Servlet containter do initialization,processing of the request and response,unloading and finalization of servlets 
  • Container creates ServletContext object through which the servlet can log events ,set and store attributes at application or session level and grab file paths.



package view;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(name = "Servlet1", urlPatterns = { "/servlet1" })
public class Servlet1 extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

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

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Servlet1</title></head>");
        out.println("<body>");
        out.println("<p>The servlet has received a GET. This is the reply.</p>");
        out.println("</body></html>");
        out.close();
    }

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

    }
    public void destroy() {
        //Clean up resources
    }
}



No comments: