Feeds:
Posts
Comments

JSP

Introduction about http

What does WebServer do:
A WebServer takes the clients request and gives something back to the client.

Server responds with the status code.

a.    404 – Not found error. – The server cannot find the thing what the client asked.
b.    200 – OK. Server successfully send the response to the client what it is expecting.

What does Web Client do:
A Web Client lets the user request something on the server, and shows the user the result of the request.

Key points:

  • Both Clients and Server know HTML and HTTP.
  • HTML (HyperTextMarkupLanguage) tells the browser how to display the content to the user
  • The server uses HTTP to send HTML to the client
  • HTTP (HyperTextTransportProtocol) is the protocol clients and server use on the web to communicate.
  • The client sends an HTTP request, and the Server answers with an HTTP response.
  • HTTP:

    HTTP runs on top of TCP/IP. (Transmission Control Protocol/Internet Protocol).
    HTTP depends upon TCP/IP to get the complete request/ response from one place to another.

    TCP

    It is responsible for making sure that a file sent from one network node to another ends up as a complete file at the destination, even though the file is split into chuncks when it’s sent.

    IP

    It moves/routes the chunks from one host to another on their way to the destination.

    WebServer    -> Apache
    WebBrowser -> Mozilla

  • HTTP protocol has serveral method, but we most often are GET and POST.
  • GET is the simple method, is to ask the server to get a resource and send back to client.
  • POST is powerful method. It is GET ++.  Request + send data to server.
  • HTTP Methods:
    GET, POST, HEAD, TRACE, PUT, DELETE, OPTIONS, CONNECT

    HEAD: Ask for only header part of whatever GET would return. GET with no body.
    TRACE: Ask for loopback of request message.so client can see what being received on the other end for testing or troubleshooting
    PUT: put the enclosed info(Body) at the requested URL
    DELETE: delete the thing(resource/file) at the requested URL.
    OPTIONS: Ask for list of http methods to which the thing requested URL can respond
    CONNECT: say connect for the purpose of tunneling.

    Difference Between GET and POST
    ===============================================================
    Attribute | GET | POST
    ===============================================================
    Amout of data | We can send only limted amount | We can send more data
    Transfer. | of data |
    URL | Data sent will be appended to the | Data will not be visible in
    | URL. So data is visible | the URL.
    Bookmark | We can bookmark the page | we cant bookmark a form
    | | submission.
    ===============================================================

    POST is meant for sending data to be processed. It is like update, to change something on the server.

    GET,PUT,HEAD are idempotent. PUT is not idempotent.
    Once transaction don’t by POST cant be reversed. So not idempotent.

    Idempotent: can run multiple times without causing side effects on the server.

    In form submittion if method=”POST/GET” is not mentioned means by default GET will be sent to the server.

    If we want to handle both in server then

    Public void doPost(…)throws…{
    DoGet(request,response);
    }

    URL -> Uniform Resource Locators

    http

    WebServer gives static page. MIME type tells the browser what kind of data the browser is about to receive.

    WebSever alone wont do
    1.    Dynamic content.
    2.    Saving data on the server.

    So to do the above both things server can use separate helper application to do the things.

    Some of Helper app is CGI, Servelts

    CGI ->  Common Gateway Interface

    Difference between CGI and Servlets

    a.    CGI scripts in Perl, but Servlets are in Java
    b.    Perl (server) launches a heavy-weight process for each request, but Servlet are handled as separate threads which reduce overhead of JVM,loading classes etc,

    Servlet uses printwrtier object to build html code in the server side
    E.g
    PrintWriter out = response.getWriter();
    Out.println(“<html>”+”<body>”+….”<html>” );

    Instead of putting html code in java, we use JSP which is putting java code in HTML that makes HTML dynamic.

    Servlet life cycle

    Servlet Life Cycle:
    init()
    service()
    destroy()

    §    container load the servlet class.
    §    Container Instantiate servlet. It runs the constructor. The constructor is default one given by compiler.
    §    Container calls the init() method after Servlet Instance is created. It will be called only once in servlet lifecycle, must complete before container call the service().
    §    Then container call the service() method.
    §    Container calls to give the servlet a  chance to clean up before the servlet is killed(garbage collection). It is called only once as like init().

    init() method we can override . If we have intialization code like getting database connection or registering object, tghen we can override init() method.

    service() method we should not override. We have to override doGet() or doPost() and service() will call either doGet() or doPost() depends upon the request.

    doGet()/doPost() always we have to override it.

    servlet

    By the above figure, one thread per request will be created.For every incoming request means a new thread/stack.

    And for single JVM there will be only one instance will be created for a servlet.

    First container finds the servlet class. Then it loads the class. Loading the class depends, it can be loaded while container startup or first client use.

    When Object become Servlet:
    After the constructor call the init() method called. In that time Object become Servlet. Because constructor is makes an Object, not Servlet. When Object become Servlet it get all unique privileges like ability to use its ServletContext to get information about the Container.

    ServletConfig Object:
    §    One ServletConfig Object per Servlet
    §    Use it to pass deploy-time information to servlet(like DB name, lookup for EJB)
    §    Use it to access the ServletContext
    §    Parameters are configured in Deplyoment Descriptor(DD).

    ServletContext:
    §    One ServletContext per web app.
    §    Use it to access web app parameters(also configured in DD).
    §    Can be useful to store and share the data across web applicaion
    §    Use it to get server info, including name and version of container.

    Request:

    Who implements Interface of HttpServletRequest and HttpServletResponse:
    Container implements. These are not part of API, there are left to vendor specific.

    Using Request object we can use many methods to get data;s.
    request.getParameter(“string”);         è return string.
    request.getParameterNames(“string”);     è return array of string
    request.getHeader(“User-Agent”);        è return string
    request.getgCookies();             è return array of Cookies[].
    request.getSession();                è return HttpSession.
    request.getInputStream();            è return InputStream.

    request.getInputStream:
    Used to get the raw bytes of everything that comes in the request, both header information and body.

    getHeader():
    String forwards = request.getHeader(“max-forwards”);
    Int forwardNum = Integer.parseInt(forwards);
    getIntHeader():
    int forwardNum = request.getIntHeader(“max-forwards”);

    getRemotePort():
    gives the client port number. For server, client is the remote.

    getServerPort():
    The port where the request are sent to server.

    getLocalPort():
    after the request sent to server, the server turns around and finds different local port for each thread.

    Response:
    Response is just send data back to the client. Important methods of response are
    a.    setContentType()
    b.    getWriter()
    c.    getOutputStream()

    some of the other methods are
    a.    sendError();
    b.    addCookies()
    c.    addHeader()
    d.    encodeURL();

    response.setContentType(“application/jar”); is used to send the jar.
    ServletContext ct = getServletContext();
    InputStream is = ct.getResourceAsStream(“/bookcode.jar”);
    Int read =0;
    Byte[] bytes = new byte[1024];
    OutputStream os = response.getOutputStream();
    While((read = isread((bytes))!=-1){
    os.write(bytes,0,read);
    }
    os.flush();
    os.close();

    bookcodejar will be search in webapps/project/bookcode.jar. It will be placed in the same place where WEB-INF is placed.

    PrintWriter:
    PrintWriter writer = response.getWriter();
    Writer.println(“ some txt”);
    It is for character steam/data.

    OutputStream:
    ServletOutputStream out = response.getOutputStream();
    Out.write(ByteArray);
    It is for bytes.

    SetHeader(“bar”,”bar”)        è overwite the existing value
    AddHeader(“add”,”add”)        è adds an additional value

    SendRedirect():
    Response.sendRedirect(www.google.com); it takes only string not the URL object. We cant call sendRedirect after the response is committed.

    Using relative URL in sendRedirect():

    Client originally typed in:
    http://www.wicked.com/myApp/cool/bar.do
    sendRedirect:
    sendRedirect(“foo/stuff.html”);
    note this is without  “/” forward start in the starting. So container builds the URL
    http://www.wicked.com/myApp/cool/foo/stuff.html

    Client originally typed in:
    http://www.wicked.com/myApp/cool/bar.do
    sendRedirect:
    sendRedirect(“/foo/stuff.html”);
    note this is with  “/” forward start in the starting. So container builds the URL
    http://www.wicked.com/myApp/foo/stuff.html
    forward slash at the beginning means “relative to the root of this web app”

    Difference between redirect and request dispatch:
    a.    redirect makes the client do the work, while request dispatch makes something else on the server do the work.
    b.    In request dispatch, the browser location bar didn’t change. So user does not know that the jsp generated the response. But in redirect the user see new URL in the browser.

    Web app Architecture

    Container:

  • Container helps servlets.
  • It instantiate the servlet or make a thread to handle the request
  • It calls the servlet’s doGet() or doPost() method
  • It create HTTP request and response object to the servlet.
  • It manages the life cycle of servlet.
  • It finds the URL in DD to find the correct servlet for the request.
  • Delete the request and response object once thread completes
  • It calls the service method.
  • Tomcat is the example of Container.

    Container provides

  • Communication support:
  • It build serversocket,listen on port,create stream etc.
  • It knows the protocol between itself and webserver.
  • b.    Lifecycle Management:

  • Control the life and death of servlet
  • Loading class, instantiate and intialize servlet.
  • Making servlet instance eligible for garbage collection.
  • c.    Multithreading support

  • It creates new thread for each and every request it receives
  • d.    Declarative Security

    e.    JSP Support

    Steps how container handles the request
    1.    get the HTTP request from the client
    2.    create HTTPServlet request and response.
    3.    Finds the correct servelt based on the URL and creates thread for each request.
    4.    Container calls the servlet’s Service() method, Depending upon type of request service method calls doGet() or doPost() method.
    5.    doGet() method generate the dynamic page and stuff in response object.
    6.    The thread completes the container converts response object to HTTP response and send to client and then delete the request and response object which it creates (in step 2).

    Webserver do :
    It gets the response from the container and converts the response object to an HTTP response.
    It uses HTTP to talk to the client browser.
    It knows how to forward the dynamic content to the container.

    Servlet do:
    It add the html to the response object
    It has a name that matches the <Servlet-class> element in the DD.

    Application server:
    It will have/acts as web container and EJB container. J2EE, Weblogic, JBOSS,Websphere

    Webserver:
    Handles only HTTP request/response. Apache

    Container:
    It handles both HTTP and servlets and JSP. Tomcat.

    How to pass the control to jsp from servlet:
    a.    RequestDispatcher
    b.    SendRedirect
    Examples:
    a.    RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
    View.forward(request, response);

    b.    response.sendRedirect(“www.google.com”); (it should have string as parameter).

    java_img

    java_img1

    class Singleton{

    private static Singleton singletonObject;
    private static int single;

    /** A private Constructor prevents any other class from instantiating. */
    private Singleton(){
    // Optional Code
    single++;
    System.out.println(“Singleton Zero ARGS Constructor:”+single);
    }

    public static synchronized Singleton getSingletonObject()
    {
    if (singletonObject == null){
    singletonObject = new Singleton();
    }
    return singletonObject;
    }

    public Object clone()throws CloneNotSupportedException
    {
    throw new CloneNotSupportedException();
    }
    }

    public class SingletonObjectDemo {
    public static void main(String args[]){
    // Singleton obj = new Singleton(); Compilation error not allowed

    //create the Singleton Object..
    Singleton obj = Singleton.getSingletonObject();

    //create a copy of the Object by cloning it using the Object’s clone method
    // Since its overrided
    // SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

    // Second instance will not invoke constructor since already object is created.
    System.out.println(“Singleton object obtained”);
    Singleton obj2 = Singleton.getSingletonObject();

    }
    }

    JVM, JRE, JDK

    JVM is interpreter.

    JVM is an instance of JRE comes into action when a java program is executed.

    JVM + API JRE

    JVM may use Just in time compiler for interpreting or uses set of JVM instructions set.

    JIIT is the part of the JVM that is used to speed up the execution time. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.

    JDK contains a Java compiler and a number of other important development tools as well as a full copy of the Java Runtime Environment.

    the “JVM” is the definition of the abstract, stack-based computational engine used to execute Java bytecodes

    a JRE is a specific implementation of the the JVM, including the core libaries.

    Java platform independent – bytes codes(.class file)

    Java source code is “compiled” to an intermediate-language bytecode which is then interpreted by an interpreter, the JVM, which then interfaces that program with the Java software libraries.

    Interpreter and compile

    The name “compiler” is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine language). A compiler is likely to perform many or all of the following operations: lexical analysis, preprocessing, parsing, semantic analysis, code generation, and code optimization.

    A compiler first takes in the entire program, checks for errors, compiles it and then executes it. Whereas, an interpreter does this line by line, so it takes one line, checks it for errors and then executes it.

    Compiled code does the work much more efficiently, because it produces a complete machine language program, which can then be executed. The interpreter translates instructions one at a time, and then executes those instructions immediately.

    • Webserver serves pages for viewing in web browser, application server provides exposes business logic for client applications through various protocols

    • Webserver exclusively handles http requests.application server serves business logic to application programs through any number of protocols.

    • Webserver delegation model is fairly simple,when the request comes into the webserver,it simply passes the request to the program best able to handle it(Server side program). It may not support transactions and database connection pooling.

    • Application server is more capable of dynamic behaviour than webserver. We can also configure application server to work as a webserver.Simply application server is a superset of webserver.

    Think of the include directive as a header file of languages like C/C++. When using the include directive, the combined contents of the original JSP page and all its included resources are translated into the same implementation servlet i.e. the contents of the included resource is copy pasted before translation to a servlet. The important thing here is that all this happens during translation time and only static content is supported.

    The include action <jsp:include> is almost similar to the include directive except for a few subtle differences. The include action is executed at request time as opposed to translation time. Thus instead of the content of the include file being included in the calling JSP, the output of the JSP is included or passed to the JSPWriter of the calling page. This allows us to include both static and dynamic content into the JSP page. Using the jsp action also allows you to explicitly pass parameters to the included page.

    http://www.daniweb.com/forums/thread105695.html

    « Newer Posts - Older Posts »