Sunday 9 August 2015

Servlets interview question and answer ?

Servlets (version 2.4) A Server-Side-Component, which extends functionality of any Java-enabled Server, but most commonly used to produce dynamic web pages. Once loaded Servlets stay resident in server. Servlets do not have user interface, UI is provided by HTML.


Servlet Interface: Declares methods that manage the servlet and its communications with clients.
Http is a stateless protocol i.e. server don’t retain track of client.
URL is subclass of URI (Universal Resource Identifiers).
GET method passes information in query string. Append data to URL. Max 255 chars.
POST for complex and lengthy data. Directly writes to port.
HEAD when you want to get info about the document but do not want document.
PUT Request server to store the body of the request at a specified URL.

DELETE Request the removal of data at a URL.

OPTIONS Requests the information about the communications options available.
TRACE used for debugging. The HTTP body is simply returned by the server.
MIME (Multipurpose Internet Mail Extensions) used to describe format of the response.
            text/html text/plain image/gif application/pdf.

 Servlet Container: provides system level services to servlet like maintaining servlet life cycle, registering servlet with URL, security, threads(Concurrency problems), Coding/Decoding MIME request/response.

  • getInitParameter (String name) //provided in deplymnt descriptr (web.xml)
  • Public Enumeration getInitParameterNames () // ---do----
  • Public ServletContext getServletContext ()  

Res.sendRedirect() will change the url
ServletContext().getRequestDispatcher().forward(req,res) will not change url.Catch{
            Res.sendError(int sc)
Res.sendError(int sc,String msg) to send error number and msg to client.
Res.sendRedirect() to redirect control.}

Session: page requests originated from same browser during a specified period of time.
            GetId(), getLastAccessedTime(),getCreationTime(), get/setAttribute,invalidate()
Get/SetMaxInactiveInterval()  returns/sets time in seconds.
If  –ve time set session will never timeout never expires.

Res.encodeURL() will add sessionId with response.
Filters introduced by Servlet 2.3: is a special type of servlet that dynamically intercepts requests and responses and manipulate the information contained in them.Is a servlet extends HttpServlet implements Filter DoFilter() method contains filtering code. ServletContext may be accessed through FilterConfig() passed in init(). Filters may be connected in a chain.P V ilter(ServletRequest req,ServletRes, FilterChain chain) io,
Serlvet   {Chain.doFilter(req,res)//al next filter in chain}
            in case it is last filter it will invoke servlet.

Servlet Threads: in 2.3 version, an interface SingleThreadModel was used to resolve multithread problems. But it could not be implemented on objects in session and context so the use of SingleThreadModel is deprecated.

ServletSandBox : is an area where servlets are given restricted access to the server. Servlet running in sandbox can be constrained from accessing the file system and network. It is similar to how browser controls applets.                                               

Servlets

Servlet Interface

  • Public void init (ServletConfig) // called by container after making instance
  • Public void service (ServletRequest, ServletResponse) //by contner fr each req
  • Public void destroy () // by container on unloading
  • Public ServletConfig getServletConfig ()
  • Public String getServletInfo ()
ServletConfig Interface
  • Public getInitParameter (String name) //provided in deplymnt descriptr (web.xml)
  • Public Enumeration getInitParameterNames () // ---do----
  • Public ServletContext getServletContext ()  
  • Public String getServletName () // name of servlet provided in web.xml
Public abstract class GenericServlet implements Servlet, ServletConfig, Serializable
  • Public init ()
  • Public void log  (String msg)
  • Public void log (String msg, Throwable t)
Public interface SingleThreadedModel
A marker-interface, with no methods. Uses Instance Pooling or Request Serialization. Practically combination of two.

Public abstract class HttpServlet extends GenericServlet implements Serializable

  • Public void service(SerRq,ServRes)
  • Protected void service(HttpSerReq,HttpServRes)
  • Protected void doGet/Post/Head/Delete/Options/Put/Trace(HttpSerReq,HttpServRes)
  • Protected long getLastModified(HttpSerReq)

Public interface ServletRequest

  • Public void getMethod() //returns type of Http method i.e. post /get /head
  • Public getProtocol() //returns protocol
  • Public .. getServerName/ServerPort/RemoteAddr/RemoteHost/Attribute/Parameter..

Public class ServletRequestWrapper implements ServletRequest

Provides default imlementation of all methods of ServletRequest interface

Public class HttpServletRequestWrapper implements HttpServletRequest

Public interface HttpServletRequest extends ServletRequest
            getSession/Cookies/QueryString/ContextPath
Servlet Exceptions
            Public class ServletException extends java.lang.Exception
Public class UnavailableException extends ServletException
Servlet Life Cycle
            Instance—init()—service()—destroy()---marked garbage
SessionTracking
  URL rewriting, Hidden Fields, Cookies, using  SecureSoketLayer.
            Based upon exchanging a token b/w client and server.
HttpServletRequest interface
Public HttpSession getSession(boolean create)//creates(if no session) only if yes else null
Public HttpSession getSession()       //creates if no session
Filter  A servlet-like container-managed object that can be declaratively inserted within the HTTP request-response process. May be used for :
  • Validating HTTP request. (decouple the logic from servlet)
  • To preprocess the HTTP request parameters.
  • Cheking client’s authenticity for resourse requested.
NOTE: All talks are possible by servlet but with some difficulty.
Jar vs War
            The purpose of jar file is to package classes and their related resources into a compressed archive file.
            A war file represents a web application, not just a class archive.
War file is not appropriate at development stage as frequent recompilation is needed so at this stage server’s auto-reloading feature may be used.0
           

Directory Structure
            MyContext\
                        Index.html,login.jsp
                        Images\
                                    Logo.gif,banner.gif
                        Literature\
                                    Summary.jsp,one.pdf,two.pdf
                        WEB-INF\     //is must . is private
                                    Web.xml
                                    Classes\
                                                One.class,two.class…
                                    Lib\
                                                One.jar,two.jar

                                    

Web.xml file

<web-app>
            <welcome-file-list>
                        <welcome-file>            index.html</welcome-file>
                        <welcome-file>summary.jsp</welcome-file>
            </welcome-file-list>
            <context-param>
                                    <param-name>Admin_path</param-name>
                                    <param-value>/chat/servlet/chatAdmin</param-value>
            </context-param>
<filter>
<filter-name>counter</filter-name>
<display-name>counter</display-navme>
<filter-class>CounterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>counter</filter-name>
                        <url-pattern>*.html</url-pattern> //will work for all html files only
</filter-mapping>
            <servlet>
                        <servlet-name>catalog</servlet-name>
                        <servlet-class>bookstore.catalog</servlet-class>
                        <init-param>
                                    <param-name>author</param-name>
                                    <param-value>Harjeet Singh</param-value>
</init-param>
            </servlet>
//Servlet tag one for each servlet with maching mapping tag
            <servlet-mapping>
                        <servlet-name>catalog</servlet-name>
                        <url-pattern>/catalog</url-pattern>
            </servlet-mapping>

<error-page>
                        <exception-type>javax.servlet.UnavailableException</exception-type>
            <location>/unavailable.html</location>
</error-page>
<welcome-file-list>
            <welcome-file>myIndex.html</welcome-file>
</welcome-file-list>
<session-config>
            <session-timeout>300</session-timeout>
</session-config>
//doubt
<listener>
<listener-class>MySessionListener</listener-class>
</listener>
</web-app>


Problems

            Init(config) init() if provided functionality in init() how wd it work. Two init methods wd be called?
            Service methods
            How session is tracked
            Technique used in session tracking how decided
GetSession():getSession(boolean)

            Session timeout secs/min

getSession(boolean) v/s getSession()
forward(handed over/responsibility transferred)include(hired for service/responsibility lies) within same context
sendRedirect user send to new url
URL on forward redirect sendRedirect will get changed?
Filter vs servlet
If more than one files in welcome list which will be executed when.

No comments:

Post a Comment