ankit servlet ques

Embed Size (px)

Citation preview

  • 8/3/2019 ankit servlet ques

    1/27

    Q What does web server do?

    ANS A web server takes a client request,which is done bythe web browser at the client side,process the request and

    return the required resources back to the client.Thisresource can be the html page,picture,text file,sound file anything.

    Q What does web client do?

    ANS A web client lets the user request something on the

    server, and show the user the result of the request.Client is the piece of the software called as browser thatknows how to communicate with the server,it interprets thehtml code and show the web page to the user.

    Q What is HTML and HTTP?

    ANS HTTP is the protocol client and server use on web tocommunicate .It allows simple request and responseconversation.The client sends the an HTTP requests andserver answers with an HTTP response.HTTP runs on thetCP/IP port no 80.

    HTTP tells the browser how to display content to the user.

    Q What is get and post method of html?

    ANS Get is the simplest method its main job is to ask theserver to get a resource and send it back,that resource maybe anything.Total no of characters in get is limited.The data

  • 8/3/2019 ankit servlet ques

    2/27

    that is sent with get is appended to the url so it is exposed.soget request can be bookmarked."?" separate the path andparamenter in the url in case of get method.It is used for justgetting things.

    Get method is called in following caseswhen address is typed in the url.

    when user is requsting the page by clicking hyperlink.

    when method written is get in the method attribute of theform tag.

    when you forgot to write the method attribute in the formtag,it is default method.

    Post is more powerful request.With post you can requestsomething and at the same time send form data to theserver.It is designed to make the complex request to theserver.For sending large data to the server post method isused.post has the body.It can not be bookmarked.It is usedfor posting things on the server.Post method is called in following cases

    when method written is post in the method attribute of theform tag.

    when data sent is too big then automatically get methodbecomes post.

    Q What is url?ANS

    http://www.yahoo.com:80/project/resource/index.html

    http- protocol-tells the server which protocol it is.www.yahoo.com- server-unique name of server,it ismapped into the ip address of that server80- port no-it is optional and default,each server

  • 8/3/2019 ankit servlet ques

    3/27

    supports multiple ports,it identified the server applicationproject/resource- the path to the location on the server.index.html- the name of content being requested,it canbe of any type.

    and optional query string in case of get method

    Q What is MIME type?ANSMIME type tells the browser what kind of data browser isabout to receive.

    Q What is CGI script?ANSMost cgi programs are written in perl language and manyother languages for generating dynamic web pages and forprocessing the user request of any resources at the serverside.

    Q Comparision of cgi and servlet?ANS

    Cgi program is written in perl language

    servlet is written in java.

    In cgi server launch a heavy weight process for eachrequest.

    In servlet server launch a new thread for each request.

    Efficient

    PowerfulConvienient

    Portable

    Secure

    Inexpensive

  • 8/3/2019 ankit servlet ques

    4/27

    Q What is request and response header?

    ANSRequest field

    in case of both get and post1 Request Line-get/post/index.html

    http1.02 Requset header-name:value

    empty linein case of post3 Requst body-encrypted data

    Response field1 Response Line-http1.2 status code description

    http1.2 404 ok2 Response header-response format,serverversion,size,cookie

    3 Response body-response data

    Q what is container?

    ANSServer dont have main method.They are under the control ofanother java application called a container.When a webserver gets a request for the servlet the server hands therequest not directly to the servlet but to the container inwhich the servlet is deployed.Its the container that gives theservlet HTTP request and response and calls the service

    method.container performs following functions

    Communication support

    Life cycle management

    Multithreading support

  • 8/3/2019 ankit servlet ques

    5/27

    Declarative security

    Jsp support

    Q How the container handles the request?

    ANS

    User clicks to the link that has a url to a servlet.

    Container sees that the request is for servlet,so thecontainer creates two objects-HttpServletResponse andHttpServletRequest.

    The container finds correct servlet based on the url in the

    request,creates or allocates a thread for that requestand passes the request and response object to theservlet thread.

    The container calls the servlet service method,then servicemethod depending on the type of request calls thedoGet or doPost method.

    Respective method generates the dynamic page and stuffsthe page into the response object.

    After the thread completes, the container converts theresponse object into an HTTP response,sends it backto the client,then delete the request and responseobject.

    Q What is servlet?

    ANSServlet is simply a java program which runs on server.servlet performs the following task

    Read the explicit data sent by the client.

    Read the implicit HTTP request data sent by the

  • 8/3/2019 ankit servlet ques

    6/27

    browser.

    Generate the results.

    Send the explicit data (i.e., the document) to the client.

    Send the implicit HTTP response data.

    A servlet can have 3 names

    Deployment name-known by who deploy the server

    Actual File name{classpath/filename.class}-known by theoriginal developer

    URL name-the name the client knows about.

    Q what is deployment descriptor?

    ANS

    When you deploy your servlet into web container,you willcreate a fairly simple XML document called the deploymentdescriptor to tell the container how to run your jsp.It use toXML element to map url to servlet -one to map client knownpublic url name to your own internal name and one to mapyour internal name to a fully qualified class name.They are

    ---maps your internal name to a fully qualified classname.

    ---map client known public url name toyour own internal name

    internal name{logical}

  • 8/3/2019 ankit servlet ques

    7/27

    actual file name

    internal name{logical}/public name

    Q what are servlet debugging methods?

    ANS

    Use print statements.

    Use an integrated debugger in your IDE.

    Use the log file.

    Use Apache Log4J

    Write separate classes.

    Q what is MVC architecture?working of MVCarchitecture?

    ANS 69

    Q what is the servlet hierarchy and servlet life cycle?

    ANS

    Servlet Interface-----level 0

    javax.servlet.Servlet

    It has declared 5 methods

  • 8/3/2019 ankit servlet ques

    8/27

    service(ServletReaquest,ServetResponse)init(ServletConfig)destroy()

    getServletConfig()getServletInfo()

    Generic Servlet Class-----level 1

    javax.servlet.GenericServlet

    It is abstract class

    service(ServletReaquest,ServetResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()

    init()getInitParemeter(String)getInitParameterNames()getServletContext()log(String)log(String,throwable)

    HttpServlet class----level 2

    javax.servlet.http.HttpServlet

    It is an abstract class

    service(ServletReaquest,ServetResponse)

  • 8/3/2019 ankit servlet ques

    9/27

    service(HttpServletReaquest,HttpServetResponse)doGet(HttpServletReaquest,HttpServetResponse)doPost(HttpServletReaquest,HttpServetResponse)

    Life cycle

    Initially servlet is in does not exist stateAt the first request the container looks for the deployed

    webapps and start searching the servlet class file.Then servlet moves from the does not exist to the

    initialized state beginning with the default constructorprovided by the jvm but the constructor makes only an objectnot servlet.

    Then container makes the object of ServletConfigWhen an object becomes the servlet,it gets all unique

    privilages like ability to use its ServletContext reference toget info from container.

    Then container calls init method it initializes your

    servlet before your servlet handles any client request.Thismethod calls only once in a life time of any servlet.When the clients request comes servlet creates a new

    thread and calls the servlets service method,this methodlooks the request and calls the respective get or postmethod.

    Then after completing the clients request containerdestroy the thread.

    At last servlet calls the servlets destroy method.

    Q what is difference between ServletConfig andServletContext ?

    ANS

  • 8/3/2019 ankit servlet ques

    10/27

    ServletConfig-One servlet config object per servletUsed to pass the deploy time information to

    the servletUse it to access ServletContext

    parameters are configured in deploymentdescriptor

    ServletContext-One servletContext object per webapplication

    Use it to access the web applicationparameters

    Use it to put a message that other parts of

    application can accessUse it to get servet info.

    Q Methods of HttpServletRequest andHttpServletResponse?

    ANS

    Request

    String param=request.getParameter("parametername");

    String[]paramlist=request.getParameterValues("parameter name");

    String client=request.getHeader("User agent");

    Cookie[] cookie=request.getCookies();

    Session session=request.getSession();

  • 8/3/2019 ankit servlet ques

    11/27

    String theMethod=request.getMethod();

    InputStream input=request.getInputStream();

    Response

    response.setContentType("String");

    Printwriter out= response.getWriter();out.println("")// write text data to character stream

    ServletOutputStream out=response.getOutputStream();out.write("");//write anything

    Q what is redirecting and forwarding?

    ANSBoth invites other servlet or other resource for handling yourrequest

    response.sendRedirect("resource servlet");

    When servlet does a redirect its like asking client to callsomeone else instead.In this case client is browser not theuser.The browser makes new call on the user's behalf.Theuser can see the new url in the browser.

    RequestDispatcher

    view=response.getRequestDispatcher("resource servlet");view.forward(request,response)

    when servlet does a request dispatch its like asking acoworker to take over working with a client then coworkerresponds to the client.The client never knows some one else

  • 8/3/2019 ankit servlet ques

    12/27

    took over because url in the browser never changes.

    Q how to access the init parameter?

    ANS

    param 1value 1

    getServletConfig().getInitParameter("paramname");

    you can not use init parameters untill the servlet isinitialized.

    param 1value 1

    getServletContext().getInitParameter("param name");

    used by the whole application.

    Q what is ServetContextListener?

    ANSwe can make a separate class that can listen for two keyevents in servlet contexts life initialization and destruction

  • 8/3/2019 ankit servlet ques

    13/27

    this class implements javax.servlet.ServletContextListener

    this class get notified when the context is initialized

    get the context init parmeter from the ServletContextUse the init parameter look up names to create the databaseconnectionstore the database connection as a attribute so that allparts of webapp can access it

    get notified when context is destroyedclose the database connection

    import javax.servlet.ServletContextListener

    class MyServetContextListener implementsServetContextListener{

    public voidcontextInitialized(ServletContextEvent event){

    }

    public voidcontextDestroyed(ServletContextEvent event){

    }}

    package.MyServletContextListener

  • 8/3/2019 ankit servlet ques

    14/27

    Q what is session?Why it is needed?How it works?

    ANS

    An HttpSessionObjects hold conversational state acrossmultiple requset from the same client.In other words it persist for an entire session with a specificclient.

    An http protocol uses stateless connection.The clientbrowser makes a connection to the server,sends arequest,gets the response and closes theconnection,because the connection does not persist thecontainer doesnt recognize that the client making a secondrequest is the same client from previous request forcontainer each request is from a new client.

    On the clients first request,the container generates a uniquesession id and gives it back to the client with theresponse.The client sends back the id with every subsiquentrequest.The container sees the id finds the matching sessionand associates the session with the request.This exchangeof id or info is done through cookie.

    That is you do have to tell the container that you want to

    create or use a session,but the container takes care ofgenerating the session into the cookie as a part ofresponse,And on the subsequent request ,container gets thesession id from a cookie in the request,matches the sessionid with the existing session and associate that session withthe current request.

  • 8/3/2019 ankit servlet ques

    15/27

    HttpSession session=request.getSession();if (session.isNew())

    {// new session

    }else

    {// welcome back

    }

    HttpSession session=request.getSession(false);passing false means it always returns preexisting sessionotherwise null

    20{min}

    orsession.setMaxInactiveInterval(20*60){sec}

    Q What is jsp?What is its life cycle?

    ANS

    Jsp is a full fledged servlet running in your application,Its lotlike any other servlet,except that the servlet class is writtenfor you by the container.The container takes what you have written in your

    jsp,translates it into a servlet class source file and thencompiles that into a java servlet class

  • 8/3/2019 ankit servlet ques

    16/27

    Need of Jsp

    It is hard to write and maintain the HTML

    You cannot use standard HTML tools.

    The HTML is inaccessible to non-Java developers.

    Life cycle

    Scriptlets // enter into the

    service method

    Expressions

    // enter into theservice method in System.out.printlnDeclarations

    // enterinto the class outside the service methodDirectives

    Q what is a directive?

    ANS

    A directive is a way for you to give a special instructions tothe container at page translation time.directive are of 3 typespage ,include, taglib written between

  • 8/3/2019 ankit servlet ques

    17/27

    page directiveIt defines the page specific properties such as characterencoding,the content type for this page's response and

    wheather this page should have the implicit object.A pagedirective can use up to 13 different attributestag lib directiveDefines a tag libraries available to jsp.

    include directivedefines text and code that gets added into the current pageat translation time.

    The include directive. This construct lets you insert JSPcode into the main page before that main page is translatedinto a servlet. Its main advantage is that it is powerful: theincluded code can contain JSP constructs such as fielddefinitions and content-type settings that affect the main

  • 8/3/2019 ankit servlet ques

    18/27

    page as a whole. Its main disadvantage is that it is hard tomaintain: you have to update the main page whenever anyof the included pages change.

    Think of the include directive as a preprocessor: the includedfile is inserted character for character into the main page,then the resultant page is treated as a single JSP page. So,the fundamental difference between jsp:include and theinclude directive is the time at which they are invoked:

    jsp:include is invoked at request time, whereas the includedirective is invoked at page translation time.

    What does basic syntax look like?

    When does inclusion occur? Request timePage translation time

    What is included? Output of pageActual content of file

    How many servlets result? Two (main page andincluded page each become a separate servlet)

    One (included file isinserted into main page, then that page is translated into aservlet)

    Can included page set response headers that affect themain page?

    No Yes

    Can included page define fields or methods that main page

  • 8/3/2019 ankit servlet ques

    19/27

    uses?

    No Yes

    Does main page need to be updated when included page

    changes?

    No Yes

    What is the equivalent servlet code?

    include method ofRequestDispatcher

    None

    jsp actionsuseBean

    Bean law

    the bean class must have public zero argumentconstructor.

    public getter and setter method must be named startingwith set and get followed by the same word.

    the setter argument type and getter return type must besame.

    it will create the object if object does not exist otherwisereturn the existed one.

  • 8/3/2019 ankit servlet ques

    20/27

    if you put your setter code inside the bodyof the property setting is conditional that isproperty will only set when new bean is created.

    type attribute is optional if we want that object referenceshould belong to some other class type.

    default value of scope attribute is page.param attribute is for passing the request parameter to

    the bean.if both value and param attribute is not specified thenyou are telling the container to get the value from a requestparameter with a matching name of property name.

    if property="*" is used then all the set property matchget their attribute by matching name with request parameter.

    This is the default value; you get the same behavior if

    you omit the scope attribute entirely. The page scopeindicates that, in addition to being bound to a localvariable, the bean object should be placed in thePageContext object for the duration of the currentrequest. Storing the object there means that servletcode can access it by calling getAttribute on the

  • 8/3/2019 ankit servlet ques

    21/27

    predefined pageContext variable.

    Since every page and every request has a differentPageContext object, using scope="page" (or omitting

    scope) indicates that the bean is not shared and thus anew bean will be created for each request.

    This value signifies that, in addition to being bound to alocal variable, the bean object should be placed in theHttpServletRequest object for the duration of thecurrent request, where it is available by means of the

    getAttribute method.Although at first glance it appears that this scope alsoresults in unshared beans, two JSP pages or a JSPpage and a servlet will share request objects when youuse jsp:include, jsp:forward , or the include or forwardmethods of RequestDispatcher .

    Storing values in the request object is common whenthe MVC (Model 2) architecture is used.

    This value means that, in addition to being bound to alocal variable, the bean will be stored in theHttpSession object associated with the current request,where it can be retrieved with getAttribute.

    Thus, this scope lets JSP pages easily perform the type

    of session tracking .

    This value means that, in addition to being bound to alocal variable, the bean will be stored in theServletContext available through the predefined

  • 8/3/2019 ankit servlet ques

    22/27

    application variable or by a call to getServletContext.The ServletContext is shared by all servlets and JSPpages in the Web application. Values in theServletContext can be retrieved with the getAttribute

    method.

    include

    The jsp:include action. The jsp:include action lets youinclude the output of a page at request time. Its mainadvantage is that it saves you from changing the main pagewhen the included pages change. Its main disadvantage isthat since it includes the output of the secondary page, notthe secondary page's actual code as with the includedirective, the included pages cannot use any JSP constructsthat affect the main page as a whole. The advantagesgenerally far outweigh the disadvantages, and you willalmost certainly use it much more than the other inclusionmechanisms.

    The included page uses the same request object asthe originally requested page. As a result, theincluded page normally sees the same requestparameters as the main page. If, however, you wantto add to or replace those parameters, you can usethe jsp:param element (which has name and value

    attributes) to do so. For example, consider thefollowing snippet.

  • 8/3/2019 ankit servlet ques

    23/27

    plugin

    The jsp:plugin element is used to insert applets that usethe Java Plug-in into JSP pages. Its main advantage is that itsaves you from writing long, tedious, and error-proneOBJECT and EMBED tags in your HTML. Its maindisadvantage is that it applies to applets, and applets arerelatively infrequently used.

    jsp forward

    You use jsp:include to combine output from the main pageand the auxiliary page. Instead, you can use jsp:forward toobtain the complete output from the auxiliary page. Forexample, here is a page that randomly selects either

    page1.jsp or page2.jsp to output.

    0.5) {destination = "/examples/page1.jsp";

    } else {destination = "/examples/page2.jsp";

    }

    %>

    To use jsp:forward, the main page must not have any output.This brings up the question, what benefit does JSP provide,then? The answer is, none! In fact, use of JSP is a hindrancein this type of situation because a real situation would be

  • 8/3/2019 ankit servlet ques

    24/27

    more complex, and complex code is easier to develop andtest in a servlet than it is in a JSP page. We recommend thatyou completely avoid the use of jsp:forward. If you want toperform a task similar to this example, use a servlet and

    have it call the forward method of RequestDispatcher.

    Q what is translation process?

    ANS

    Look at the directives,for information it might need duringtranslation.

    Creates an HttpServlet subclass it extends HttpJspBase

    If their is a page directive with an import attribute,it writesthe import statement at the top of the class file,justbelow the package statement

    If there are declarations,it writes them into the class file,justbelow the class declaration and before the service

    methodBuilds the service method.The service method's actual

    name is _jspService then the container declares andinitializes all the implicit objects

    combine all the html,scriptlet ,and expressions into theservice method formating and writting into the responseoutput

    Implicit objects

    JspWriter-out

    This variable is the Writer used to send output to theclient. However, to make it easy to set response headers at

  • 8/3/2019 ankit servlet ques

    25/27

    various places in the JSP page, out is not the standardPrintWriter but rather a buffered version of Writer calledJspWriter.

    HttpServletRequest-request

    This variable is the HttpServletRequest associated withthe request; it gives you access to the request parameters,the request type (e.g., GET or POST), and the incomingHTTP headers (e.g., cookies).

    HttpServletResponse-response

    This variable is the HttpServletResponse associatedwith the response to the client. Since the output stream (seeout) is normally buffered, it is usually legal to set HTTPstatus codes and response headers in the body of JSPpages, even though the setting of headers or status codes isnot permitted in servlets once any output has been sent tothe client.

    HttpSession-sessionThis variable is the HttpSession object associated with

    the request. Recall that sessions are created automatically inJSP, so this variable is bound even if there is no incomingsession reference. The one exception is the use of thesession attribute of the page directive to disable automaticsession tracking.

    ServletContext-appliction

    This variable is the ServletContext as obtained bygetServletContext. Servlets and JSP pages can storepersistent data in the ServletContext object rather than ininstance variables. ServletContext has setAttribute and

  • 8/3/2019 ankit servlet ques

    26/27

    getAttribute methods that let you store arbitrary dataassociated with specified keys. The difference betweenstoring data in instance variables and storing it in theServletContext is that the ServletContext is shared by all

    servlets and JSP pages in the Web application, whereasinstance variables are available only to the same servlet thatstored the data.

    ServletConfig-config

    This variable is the ServletConfig object for this page. Inprinciple, you can use it to read initialization parameters, but,in practice, initialization parameters are read from jspInit, notfrom _jspService.

    JspException-exception

    PageContext-context

    JSP introduced a class called PageContext to give asingle point of access to many of the page attributes. The

    PageContext class has methods getRequest, getResponse,getOut, getSession, and so forth. The pageContext variablestores the value of the PageContext object associated withthe current page. If a method or constructor needs access tomultiple page-related objects, passing pageContext is easierthan passing many separate references to request,response, out, and so forth.

    Object-pageThis variable is simply a synonym for this and is not

    very useful. It was created as a placeholder for the timewhen the scripting language could be something other thanJava.

  • 8/3/2019 ankit servlet ques

    27/27

    in web.xmlfile.jspScripting element can be made invalid for the jsp file

    *.jsp{disable

    scripting element for all jsp}

    true

    true

    339