Translate

Sunday, December 29, 2013

Servlets

Q1. What is the super class of all servlets and jsp
Ans.
Servlets: javax.servlet.GenericServlet
JSP: JspPage Interface.

Q2. Servlets life cycle and how do servlets work.
Ans. All Servlets must implement the javax.servlet.Servlet interface directly or indirectly. Most applications extend HTTPServlet class which extends GenericServlet class which in turn implements Servlet interface.

a.) This interface defines the init() method to match the initialization phase of a Servlet life cycle. When a container loads a Servlet, it invokes the init() method before servicing any requests.

b.) The Servlet interface matches service() method to the service phase of the Servlet life cycle. The service phase represents all interactions with requests until the Servlet is destroyed. Its invoked once per a request and is responsible for generating the response to that request. It takes two parameters - javax.servlet.ServletRequest and a javax.servlet.ServletResponse object.

By default a Servlet is multi-threaded, meaning that typically only one instance of a Servlet is loaded by a container at any given time. Initialization is done once, and each request after that is handled concurre
ntly by threads executing the Servlet's service() method.

c.) The Servlet interface defines the destroy() method to correspond to the destruction life cycle phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method, allowing the Servlet to gracefully terminate and tidy up any resources it might have created.

Q3. How does a Servlet differ from an Applet?
Ans.
1. Applets execute on a browser whereas Servlets execute within a web container in an Application Server.
2. Applets have a graphical user interface whereas Servlets do not have a graphical user interface.


Q4. What exactly is a webserver. Why do we deploy servlets in a webserver?
Ans. A Web server handles HTTP protocol. When Web server receives an HTTP request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs including Servlets, generate a response, most often in HTML, for viewing in a Web browser. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. Web server is nothing but program written in Java etc. Ex:Tomcat server.

The webserver/Tomcat is exactly running in the JVM. So whatever the program is written for Tomcat is running in JVM and displaying.


Q5. What is application server.
Ans. An application server exposes business logic to client applications through various protocols, possibly including HTTP. The application program can use this logic just as it would call a method on an object (or a function in the procedural world). 
Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.

Such application server clients can include GUI's running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. 

Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.

Q6. What is the difference between an application server and a Web server?
Ans: A Web server serves pages for viewing in a Web browser, while an application server provides methods that client applications can call. In other words, A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

Q7. Approaches for web applications
Ans.
Page Controller: One controller for each page. Ex: Tapestry
Front Controller: Single controller for each page. Ex: Spring MVC

Q8. Does the order of elements in WEB-INF matter.
Ans. The arrangement of elements must match the given listing with the Web Application Deployment Descriptor schema i.e. the XML schema that defines what can appear in web.xml. The current complete schema can be found in the Servlet 2.4 specification. The element ordering is defined by the root WEB-INF element and is as follows: icons, display-name, description, distributable, context-param, filter, filter-mapping, listener, servlet, servlet-mapping, session-config, mime-mapping, welcome-file-list, error-page, jsp-config, resource-env-ref, message-destination-ref, resource-ref, security-constraint, login-config, security-role, env-entry, ejb-ref, ejb-local-ref., message-destination, and locale-encoding-mapping-list.


Understanding the order is not difficult, but it is a problem quite a few new Servlet developers ask about. It is well worth mentioning it now to avoid causing any confusion later. Keep in mind that this order also applies to multiple elements of the same name. If two Servlets are deployed, both of the servlet elements must be listed before any of the servlet-mapping elements. It does not matter what order a group of the same elements are in, but it does matter that they are properly grouped.

Q9. Why is it compulsory to call super.init(config) in servlets, when overriding init (config)( NOTE: It’s not init() )
Ans. Since the Servlet interface defines a method called getServletConfig(),you should either save the servletConfig object and implement the getServletConfig() method yourself or pass the object to the parent class using super.init().

However this is done for backward compatibility(before version 2.1).In version 2.1 you don't require to call that super.init(config)

As an alternative, instead of overriding this method it is better to override init(). init() will be called from init(ServletConfig), and you won't need to to call super.init(config). init(ServletConfig) is called once after instantiating servlet.

Q10. Why can’t we have constructors in servlets instead of passing initialization parameters.

Ans. Constructors for dynamically loaded Java classes (such as servlets) couldn't accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet's init() method and pass along an object that implements the ServletConfig interface. Also, Java doesn't allow interfaces to declare constructors. This means that javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter. It has to declare another method, like init(). It's still possible, of course, for you to define constructors for your servlets, but in the constructor you don't have access to the ServletConfig object or the ability to throw a ServletException.

Q11. Servlet config object and Servlet Context objects.
Ans. This ServletConfig object supplies a servlet with information about its initialization (init) parameters. These parameters are particular to a servlet, not associated with any request and are specified in the web.xml. They can specify initial values, such as where a counter should begin counting, or default values. In the Java Web Server, init parameters for a servlet are usually set during the registration process.

The ServletContext parameters, on the other hand, are specified for the entire Web application. The parameters are specified in the web.xml (i.e. deployment descriptor). Servlet context is common to all Servlets. So all Servlets share information through ServletContext.


Q12. Can we call destroy() method on servlets from service method?
Ans. Destroy method is a method where we can provide the actions (to free up the resources) to be performed while the servlet is getting unloaded. In general when a servlet is getting destroyed, servlet container calls this method and also does many other things. So if you want to unload a servlet, you have to do all the things the servlet container does including calling the destroy method.

When you directly call the destroy() method from service() method, the method will be successfully called as you are calling the method from same object but you are not doing all the other things the servlet does to unload the servlet. So the servlet will not be unloaded but the destroy method will be called as any other non life cycle method.


Q13. What are different types of Servlets?
Ans. The different types of servlets are there i.e. many user defined servlets. Mostly used and important servlets are of two types:
1) Generic servlet
2) HttpServlet


Q14. What is the difference between HttpServlet and GenericServlet?
Ans: Both these classes are abstract but:

Generic Servlet
HTTP Servlet
A GenericServlet has a service() method to handle requests.
The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc. All client requests are handled through the service() method. The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request. HttpServlet also has methods like doHead(), doPut(), doOptions(), doDelete(), and doTrace()
Protocol independent. It is for servlets that might not use HTTP or FTP service.
Protocol dependent (i.e. HTTP).
 
Q15. HTTP Request
Ans. An HTTP request in its simplest form is nothing more than a line of text specifying what resource a client would like to retrieve. The line of text is broken into three parts: 1. Type of action, or method, that the client would like to do;
2. Resource the client would like to access;
3. Version of the HTTP protocol that is being used.

For example: GET /index.html HTTP/1.0 


Q16. What is the difference between request parameters and request attributes?
Ans.


Request Parameters
Request Attributes
Parameters are form data that are sent in the request from the HTML page. These parameters are generally form fields in an HTML form like:
<input type=”text” name=”param1” />
<input type=”text” name=”param2” />

Form data can be attached to the end of the URL as shown below for GET requests or sent to the sever in the request body for POST requests. Sensitive form data should be sent as a POST request.
http://MyServer:8080/MyServlet?param1=Peter&param2=Smith
Once a servlet gets a request, it can add additional attributes, then forward the request off to other servlets or JSPs for
processing. Servlets and JSPs can communicate with each other by setting and getting attributes.

  request.setAttribute(
      “calc-value”, new Float(7.0));
  request.getAttribute(“calc-value”)
You can get them but cannot set them.
request.getParameter("param1");
request.getParameterNames();
You can both set the attribute and get the attribute. You can also get and set the attributes in session and application scopes.

Q17. How to access Request Parameters.
Ans. Perhaps the most commonly used methods of the HttpServletRequest object are the ones that involve getting request parameters: getParameter() and getParameters(). Anytime an HTML form is filled out and sent to a server, the fields are passed as parameters. This includes any information sent via input fields, selection lists, combo boxes, check boxes, and hidden fields, but excludes file uploads. Any information passed as a query string is also available on the server-side as a request parameter. The HttpServletRequest object includes the following methods for accessing request parameters.

1. getParameter(String parameterName): The getParameter() method takes a String as parameter name and returns a String object representing the corresponding value. A null is returned if there is no parameter of the given name.

2. getParameters(.String parameterName): The getParameters() method is similar to the getParameter() method, but it should be used when there are multiple parameters with the same name. Often an HTML form check box or combo box sends multiple values for the same parameter name. The getParameter() method is a convenient method of getting all the parameter values for the same parameter name returned as an array of strings.

3. getParameterNames(): The getParameterNames() method returns a java.util.Enumeration of all the parameter names used in a request. In combination with the getParameter() and getParameters() method, it can be used to get a list of names and values of all the parameters included with a request.

Q18. How to access Request Headers.
Ans. HTTP headers set by a client are used to inform a server about what software the client is using and how client would prefer a server to send back requested information. From a Servlet, HTTP request headers can be accessed by calling the following methods:

1. getHeader(String name): The getHeader() method returns the value of the specified request header as a string if available or null otherwise. The header name is case insensitive. You can use this method with any request header.


2. getHeaders(String name): The getHeaders() method returns all the values of the specified request header as an Enumeration of String objects. Some headers, such as Accept-Language, can be sent by clients as several headers, each with a different value rather than sending the header as a comma-separated list. If the request did not include any headers of the specified name, this method returns an empty Enumeration object. The header name is case insensitive. You can use this method with any request header.

3. getHeaderNames(): The getHeaderNames() method returns an Enumeration of all the names of headers sent by a request. In combination with the getHeader() and getHeaders() methods, getHeaderNames() can be used to retrieve names and values of all the headers sent with a request. Some containers do not allow access of HTTP headers. In this case null is returned.

4. getIntHeader(java.lang.String name): The getIntHeader() method returns the value of the specified request header as an int. If the request does not have a header of the specified name, this method returns 1. If the header cannot be converted to an integer, this method throws a NumberFormatException.

5. getDateHeader(java.lang.String name): The getDateHeader() method returns the value of the specified request header as a long value that represents a Date object. The date is returned as the number of milliseconds since the epoch. If the request did not have a header of the specified name, this method returns 1. If the header cannot be converted to a date, the method throws an IllegalArgumentException.

Q19. What is the difference between forwarding a request and redirecting a request?
Ans. Both methods send you to a new resource like Servlet, JSP etc.


redirecting - sendRedirect()
Forward
Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information. Need to provide absolute URL path.
Forward action takes place within the server without the knowledge of the browser. Accepts relative path to the servlet or context root.
Has an overhead of extra remote trip but has the advantage of being able to refer to any resource on the same or different domain and also allows book marking of the page.
No extra network trip.

Response Redirection Translation Issues
However, there is a specific bug that tends to arise when using relative response redirection. For instance, response.sendRedirect("../foo/bar.html") would work perfectly fine when used in some Servlets but would not in others. The trouble comes from using the relative back, "../", to traverse back a directory. Relative re-directions are not always safe; " . . /" can be bad. The solution is to always use absolute redirections. Either use a complete URL such as response.sendRedirect("http://127.0.0.1/foo/bar.html") or use or an absolute URL from the root, "/", of the Web Application.

In cases where the Web application can be deployed to a non-root URL, the HttpServletRequest getContextPath() method should be used in conjunction:
        response.sendRedirect(request.getContextPath()+"/foo/bar.html");

Q20. When to forward and when to redirect?
Ans. In there has been any change in state, whether it be application state, or data state etc, don't use forward. Always use redirection in such a case.

This is because, in case of forward, refresh results in duplicate form submission, as you still see original URL in browser. However, in case of redirect, as you see redirected URL in browser, refresh doesn't result in duplicate form submission.

Also, forward doesn't receive headers from original request whereas redirect does. Since cookies are headers, they are not visible in forwarded page but visible in redirected page.

Q21. Talk about GET AND POST methods
Ans. GET sends data encoded using the application/x-www-urlencoded MIME type. If application needs to send data in some other format, say XML, then this cannot be done using GET; POST must be used. For example, SOAP mandates the use of POST for SOAP requests to cover this exact problem.

There are in total seven HTTP methods that exist: GET, PUT, POST, TRACE, DELETE, OPTIONS, and HEAD. In practice only two of these methods - GET and POST are used. The other five methods are not very helpful to a Web developer. 

1. The HEAD method requests only the headers of a response.
2. PUT is used to place documents directly to a server.
3. DELETE does the exact opposite to PUT.
4. TRACE method is meant for debugging. It returns an exact copy of a request to a client.
5. Lastly, the OPTIONS method is meant to ask a server what methods and other options the server supports for the requested resource.


Q22. What is the difference between doGet () and doPost () or GET and POST?
Ans: Prefer using doPost() because it is secured and it can send much more information to the server. With GET, you can send only limited information.

Difference between GET and POST methods
● Visibility - GET request is sent via the URL string (appended to the URI with a question-mark as separator), which is visible whereas POST request is encapsulated in the body of the HTTP request and can't be seen.

Length - Since, GET request goes via URL, so it has a limitation for its length. It can't be more than 1024 characters long (though this is browser dependent, but usually the max is 1024 characters only). Whereas no such maximum length limitation holds for the POST request for the obvious reason that it becomes a part of the body of the HTTP request and there is no size limitation for the body of an HTTP request/response.

Performance - GET request is comparatively faster as it's relatively simpler to create a GET request and the time spent in the encapsulation of the POST request in the HTTP body is saved in this case. In addition, the maximum length restriction facilitates better optimization of GET implementation.

Type of Data - GET request is sent via URL string and as we all know that URL can be text-only, so GET can carry only text data whereas POST has no such restriction and it can carry both text as well as binary data.
● Data Set - GET requests are restricted to use ASCII characters only whereas POST requests can use the 'enctype' attribute with a value "multipart/form-data" to use the Universal Multiple-Octet Coded Character Set (UCS). 

Caching/Bookmarking - Since a GET request is nothing but an URL, hence it can be cached as well as Bookmarked. No such luxuries with a POST request.

● FORM Default - GET is the default method of the HTML FORM element. To submit a FORM using POST method, we need to specify the method attribute and give it the value "POST".

When to use what? 
The "get" method should be used when the form is idempotent (i.e., multiple calls cause no side-effects). Many database searches have no visible side-effects and make ideal applications for the "get" method. If the service associated with the processing of a form causes side effects (for example, if the form modifies a database or subscription to a service), the "post" method should be used. 

Q23. How to declare initialization parameters in servlets and jsp and how to access them.
Ans.
Servlets:
<web-app>
       
<servlet>
              <servlet-name>MyServletName</servlet-name>
              <servlet-class>com.mycompany.MyServlet</servlet-class>
              <init-param>
                     <param-name>param1</param-name>
                     <param-value>value1</param-value>
              </init-param>
       </servlet>
</web-app>


Parameter can be accessed as

       String value = getServletConfig().getInitParameter("param1");

JSP:
<web-app>

       <servlet>
              <servlet-name>InitializationJSP</servlet-name>
              <jsp-file>/initialization.jsp</jsp-file>
              <init-param>
                     <param-name>testParam</param-name>
                     <param-value>hello from web.xml</param-value>
              </init-param>
       </servlet>       
       <servlet-mapping>
              <servlet-name>InitializationJSP</servlet-name>
              <url-pattern>/Initialization</url-pattern>
       </servlet-mapping>
</web-app>

Just defining the servelt-name and jsp-file doesn't solve the purpose. You need to define a URL mapping also. Also, only if you access the jsp via URL pattern, initialization will happen. If you access the JSP directly, initialization won't happen.


Passing parameters while forwarding a request from JSP
<jsp:forward page="accessingParameters.jsp">

       <jsp:param name="myParam" value="John Doe"/>
</jsp:forward>

This page had a parameter forwarded to it and accessed as

       <%= request.getParameter("myParam") %>

Q24. How to provide initialization parameters across application ie. multiple servlets.
Ans.
<context-param>

       <param-name>user</param-name>
       <param-value>Mishu Garg</param-value>
</context-param>

Parameter is accessed as

      pageContext.getServletConfig().getServletContext().getInitParameter("testParam")

Each Servlet has a ServletConfig object accessible by the getServletConfig() method of the Servlet. A ServletConfig object includes methods for getting initial parameters for the particular Servlet, but it also includes the getServletContext() method for accessing the appropriate ServletContext instance. A ServletContext object implements similar getInitParam() and getInitParamNames() methods demonstrated for ServletConfig. The difference is that these methods do not access initial parameters for a particular Servlet, but rather parameters specified for the entire Web Application.

Note: Application scope should be used sparingly. Objects bound to a ServletContext object will not be garbage collected until the ServletContext is removed from use, usually when the Web Application is turned off or restarted. Placing large amounts of unused objects in application scope does tax a server's resources and is not good practice. Another issue is that the ServletContext is not truly application-wide. If the Web Application is running on multiple servers (say, a Web farm), then there will be multiple ServletContext objects; any updates to one ServletContext on one server in the farmer will not be replicated to the other ServletContext instances.

Q25. How to call init method in servlets at the deployment time (i.e when server starts.)?
Ans: Use “load-on-startup” property on servlets. It initializes the servlet when the server starts. For example:

<servlet servlet-name='cron' servlet-class='test.DailyChores'>
      <init-param title='Daily Chores'/>
      <load-on-startup/>
      <run-at>3:00</run-at>
</servlet>

load-on-startup can specify an (optional) integer value. If the value is 0 or greater, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers. This is useful when you want to load multiple servlets on starting the server itself. If value >= 0, it means that the servlet is loaded when the web-app is deployed or when the server starts. And if value < 0, it means servlet is loaded whenever the container feels like.

Using same method in JSP’s
<servlet>

      <servlet-name>login</servlet-name>
      <jsp-file>/login.jsp</jsp-file>
      <load-on-startup>1</load-on-startup>
</servlet>

Q26. How to know whether we have to use jsp or servlet in our project?
Ans: Servlet is controller and JSP is of more a view. So when the project needs more on view part, we can add JSP otherwise both can do the same thing but in larger projects the servlet code becomes cluttered

Q27. What are the different scopes or places where a servlet can save data for its processing?
Ans.
Request Scope: Data saved in a request-scope goes out of scope once a response has been sent back to the client (i.e. when the request is completed).

//save and get request-scoped value
request.setAttribute(“calc-value”, new Float(7.0));
request.getAttribute(“calc-value”);

Session scope: Data saved in a session-scope is available across multiple requests. Data saved in the session is destroyed when the session is destroyed (not when a request completes but spans several requests).

//save and get session-scoped value
HttpSession session = request.getSession(false);
if (session != null)

{
    session.setAttribute(“id”, “DX12345”);
    value = session.getAttribute(“id”);
}

ServletContext/Application Scope: Data saved in a ServletContext scope is shared by all servlets and JSPs in the context. The data stored in the servlet context is destroyed when the servlet context is destroyed.

//save and get an application-scoped value
getServletContext().setAttribute(“application-value”, “shopping-app”);
value = getServletContext().getAttribute(“application-value”);


Q28. Talk about Request Scope
Ans. Request scope and the other scopes are not something officially labeled by the Servlet specification. The Servlet specification only defines a set of methods that allow objects to be bound to and retrieved from various containers (that are themselves objects) in the javax.servlet package. Since an object bound in this manner is referenced by the container it was bound to, the bound object is not destroyed until the reference is removed. Hence, bound objects are in the same "scope" as the container they are bound to. The HttpServletRequest object is such a container and includes such methods. These methods can be used to bind, access, and remove objects to and from the request scope that is shared by all Servlets to which a request is delegated. Request scope and other scopes are officially recognized in the JSP specification but not in Servlet specification.


Q29. How can we check if session is alive or not?
Ans:
getSession(true): Check if a session already exists for the user. If yes, returns that session object and otherwise, creates a new session for the user.

getSession(false): Check if a session already exists for the user. If yes, returns that session object and otherwise, returns null.

Q30. Talk about Cookies.
Ans. A cookie is a piece of text that a Web server can store on a user’s hard disk. Cookies allow a website to store information on a user’s machine and later retrieve it. These pieces of information are stored as name-value pairs. The cookie data moves in the following manner:

1. If you type the URL of a website into your browser, your browser sends the request to the Web server. When the browser does this, it looks on your machine for a cookie file that URL has set. If it finds it, your browser will send all of the name-value pairs along with the URL. If it does not find a cookie file, it sends no cookie data.

2. The URL’s Web server receives the cookie data and requests for a page. If name-value pairs are received, the server can use them. If no name-value pairs are received, the server can create a new ID and then sends name-value pairs to your machine in the header for the Web page it sends. Your machine stores the name value pairs on your hard disk.

Cookies can be used to determine how many visitors visit your site. It can also determine how many are new versus repeated visitors. The way it does this is by using a database. The first time a visitor arrives; the site creates a new ID in the database and sends the ID as a cookie. The next time the same user comes back, the site can increment a counter associated with that ID in the database and know how many times that visitor returns. The sites can also store user preferences so that site can look different for each visitor.

Q31. How can you set a cookie and delete a cookie from within a Servlet?
Ans.
//to add a cookie
Cookie myCookie = new Cookie(“aName”, “aValue”);
response.addCookie(myCookie);

//to delete a cookie
myCookie.setValue(“aName”, null);
myCookie.setMax(0);
myCookie.setPath(“/”);
response.addCookie(myCookie);

Q32. Statefull and Stateless protocol.
Ans. The difference b/w the two lies in the nature of the connection between client and server.

Telnet and FTP, for example are statefull protocols. The client connects to the server, conducts a series of operations via that connection, and then disconnects. Then server can associate all of the requests together and knows that thy all came from the same user. In internet jargon, the server associates a state with the connection. It remembers who the user is, and what it is that they are doing. For example, when you FTP to a server, you as a client request a file for download, FTP server can associate the request with previous ones and work out which file you requested,like sometimes it pops messages saying,"do u want to overwrite? or modify changes".It also creates a log file which u can easily view with the ws_ftp program.

On the other hand, a stateless server is a server that treats each request as an independent transaction that is unrelated to any previous request.  For ex: HTTP is a Stateless Protocol. It is concerned with requests and responses,which are simple isolated transactions. This is perfect for simple web browsing, where each request typically results in a file (an HTML document or a GIF image etc) being sent back to the client.The server does not need to know whether a series of requests come from the same, or from different clients, or whether those requests are related or distinct.

Q33. HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests? 

Ans.  This is a commonly asked interview question. HTTP is a stateless  request/response based protocol. However, it is often necessary to maintain state for the duration of all of a particular client's requests. You can retain the state information between different page requests using HTTP sessions. 

HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. In a Java servlet the session can be obtained as follows: 

// returns a current session or a new session 
HttpSession session = request.getSession(true); 

// To put/get a value in/from the session 
Name name = new Name(“Peter”);
session.setAttribute(“Firstname”, name);
session.getAttribute(“Firstname”);

// If a session is no longer required (ex: user has logged out), then it can be invalidated.
session.invalidate();

// Seting the session inactivity lease period on a per session basis, ex: 5 mins in this case
session.setMaxInactiveInterval(300);

Q34. Session tracking uses cookies by default. What would you do if the cookies are turned off? 
Ans. If cookies are turned off, you can still enable session tracking using URL rewriting. This involves including the session ID within the link as the name/value pair as shown below.

http://localhost:8080/myWebCtxt/purchase.do;jsessionid=4FB61319542B5D310B243E4BDD6DC64B

Adding session ID to each and every link is cumbersome and hence is simplified by methods response.encodeURL(givenURL) to associate a session ID with a given URL and if you are using redirection, then use response.encodeRedirectURL(givenURL).

// set a value in the session
public class CRMServlet extends HttpServlet

{
      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

      
            req.getSession().setAttribute("key", "ItemNo-1245"); 
            String url = resp.encodeURL("/myWebCtxt/purchase.do"); 
            PrintWriter pw = resp.getWriter(); 
            pw.println("<html>Sample encoded URL --><a href='" + url +"'>purchase</a></html>"); 
      }
}

// retrieve the previously set value from the session
public class PurchaseServlet extends HttpServlet

{       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
      
            String value = (String)req.getSession().getAttribute("key"); 
            PrintWriter pw = resp.getWriter(); 
            pw.println("<html>Item to purchase is --> " + value +"</html>"); 
      }
}

When you invoke the method encodeURL(givenURL) with the cookies turned on, then session ID is not appended to the URL. Now turn the cookies off and restart the browser. If you invoke the encodeURL(givenURL) with the cookies turned off, the session ID is automatically added to the URL as follows:

http://localhost:8080/myWebCtxt/purchase.do;jsessionid=4FB61319542B5D310B243E4BDD6DC64B

Sessions can be timed out (configured in web.xml) or manually invalidated. 


Q35. Compare different state keeping mechanisms.
Ans.
1. HttpSession: Application specific

  1. There is no limit on the size of the session data kept.
  2. The performance is good.
  3. This is the preferred way of maintaining state. If we use HTTP session with the application server’s persistence mechanism (server converts the session object into BLOB type and stores it in the Database), then the performance will be moderate to poor.
Note: When using HttpSession mechanism you need to take care of the following points:
a. Remove session explicitly when you no longer require it.
b. Set the session timeout value.
c. Your application server may serialize session objects after crossing a certain memory limit. This is expensive and affects performance. So decide carefully what you want to store in a session.

2. Hidden fields

  1. There is no limit on size of the session data.
  2. May expose sensitive or private information to others (So not good for sensitive information).
  3. The performance is moderate.
3. URL rewriting
  1. There is a limit on the size of the session data.
  2. Should not be used for sensitive or private information.
  3. Performance is moderate.
4. Cookies:
  1. There is a limit for cookie size.
  2. The browser may turn off cookies.
  3. The performance is moderate.
Cookies Vs Session
Cookies are by default application specific. It can be changed via setting domain and path. However, sessions are always application specific and can't be changed

Ex: http://localhost:8080/MyApp/first.jsp

domain -> localhost
path -> /MyApp

Changing the path to "/", cookies will be visible to all applications running on localhost. Cookies can be shared across multiple applications across same server, whereas sessions can't.

2. Cookies are not serializable but sessions are.
3. Cookies are stored on client and sessions on server.
4. Session is also stored as cookie value (_jsessionId)
5. Cookies can be secure (https) or unsecure (http).


Q36. Can we have JSP or servlet as welcome file name.
Ans. Yes. To have jsp as welcome file, just mention jsp file name in welcome-file list. Similarly to have servlet as welcome file, mention URL pattern in the welcome file list.

Q37. Which code line should be set in a response object before using the java.io.PrintWriter or the OutputStream?
Ans. You need to set the content type using the setContentType(…) method. 

//to return an html
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“…….”);

//to return an image
response.setContentType(“image/gif”);


Q38. Why would you need Request Delegation/RequestDispatcher?
Ans. Request delegation is a powerful feature of the Servlet API. A single client's request can pass through many Servlets and/or to any other resource in the Web Application. The entire process is done completely on the server-side and, unlike response redirection, does not require any action from a client or extra information sent between the client and server. Request delegation is available through the javax.servlet.RequestDispatcher object. An appropriate instance of a RequestDispatcher object is available by calling either of the following methods of a ServletRequest object: 

1. getRequestDispatcher(.String path): The getRequestDispatcher() method returns the RequestDispatcher object for a given path. The path value may lead to any resource in the Web Application and must start from the base directory, "/". 


2. getNamedDispatcher(String name): The getNamedDispatcher() method returns the RequestDispatcher object for the named Servlet. Valid names are defined by the servlet-name elements of web.xml. 

A RequestDispatcher object provides two methods for including different resources and for forwarding a request to a different resource. 
1. forward(ServletRequest, javax.servlet.ServletResponse): The forward() method delegates a request and response to the resource of the RequestDispatcher object. A call to the forward() method may be used only if no content has been previously sent to a client. No further data can be sent to the client after the forward has completed.
2. include(javax.servlet.ServletRequest, javax.servlet.ServletResponse): The include() method works similarly to forward() but has some restrictions. A Servlet can include() any number of resources that can each generate responses, but the resource is not allowed to set headers or commit a response.

Q39. What is the difference between the getRequestDispatcher(String path) method of “ServletRequest” interface and "ServletContext" interface?
Ans.
ServletRequest Interface: Accepts path parameter of the servlet or JSP to be included or forwarded relative to the request of the calling servlet as well as current context root. If the path begins with a “/” then it is interpreted as relative to current context root, otherwise it'll be a relative to the request of the calling servlet. Thus path cannot extend outside the current servlet context.

ServletContext Interface: Does not accept relative paths and all path must start with a “/” and are interpreted as relative to current context root. It can use getContext(String uripath) method to obtain RequestDispatcher for resources in foreign contexts.


Q40. How do servlets communicate with each other? Or How will you pass the argument from one servlet to another servlet?
Ans. Servlet API offers a new way of sharing named objects between all the Servlets in a Servlet context by binding the objects to the ServletContext object which is shared by several Servlets. Methods provided by ServletContext interface allow one servlet to know about the another. The ServletContext class has several methods for accessing the shared objects like (set/get/remove)Attribute, getAttributeNames().

Ex: ServletContext context = getServletContext(); 

// set the attribute for this context
context.setAttribute(“name=veeru”);

//get the context in another servlet/resource
context.getAttibute(name);

Every web application has one and only one ServletContext and is accessible to all active resource of that application. In most cases, ServletContext object can be considered as a reference to the entire Web Application. This holds true for single machine servers running one JVM for the Web Application. However, J2EE applications run on multiple servers (distributed environment) to share the burden and it should be noted that application scope and initial parameters will not be the same in a distributed environment. Different servers and JVM instances usually do not share direct access to each other's information. If developing for a group of servers, do not assume that the ServletContext object will be the same for every request.

Other methods of ServletContext are:
1. getServlets()
2. getServletNames()
3. getServlet("MyServlet"): After getting servlet, you can also get a list of method names supported by the new servlet and call that method and do whatever you want.

To access active server resources: requestDispatcher method.


To access passive server resources: (e.g. static HTML pages which are stored in local files). They are not accessed with RequestDispatcher objects. The ServletContext method getResource(String path) returns a URL object for a resource specified by a local URI (e.g. "/" for the server's document root) which can be used to examine the resource. If you only want to read the resource's body you can directly ask the ServletContext for an InputStream with the getResourceAsStream(String path) method.

To access servlet resources: A Servlet may need to access additional resources like configuration files whose locations should not be specified in init parameters. Those resources can be accessed with the methods getResource(String name) and getResourceAsStream(String name).
       InputStream config = getClass().getResourceAsStream("myservlet.cfg");


Q41. In which conditions we have to use the ServletContext?
Ans.
1. For communication b/w different servlets.
2. Accessing request dispatcher object.
3. Global variables

Q42. What information ServletRequest interface allows the servlet access to?
Ans. ServletRequest gives access to information such as the names of the parameters, attributes passed in by the client, the protocol  being used by the client, and the names of the remote host that made the request and the server that received it. Servlets use the input stream facilitated by ServletInputStream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

Q43. What information ServletResponse interface gives the servlet methods for replying to the client?

Ans. ServletResponse allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

Sending back custom content requires using either the getWriter() or getOutputStream() method to obtain an output stream for writing content. These two methods return suitable objects for sending either text or binary content to a client, respectively. Only one of the two methods may be used with a given HttpServletResponse object. Attempting to call both methods causes an exception to be thrown.

Compared to using the getWriter() method, the getOutputStream() method is used when more control is needed over what is sent to a client. The returned OutputStream can be used for sending text, but is usually used for sending non-text-related binary information such as images. The reason for this is because the getOutputStream() method returns an instance of a javax.servlet.ServletOutputStream object, not a PrintWriter. The ServletOutputStream object directly inherits from java.io.OutputStream and allows a developer to write raw bytes. The PrintWriter objects lack this functionality because it always assumes you are writing text.


Q44. Can I invoke a JSP page/servlet from a servlet?
Ans.
1.) Forwarding to a JSP page from a servlet
try
{
      ......

catch(Exception ex)
{
      //store the exception as a request attribute
      req.setAttribute("javax.servlet.ex",ex);
      ServletContext sContext = getServletConfig().getServletContext(); 

      // forward the request with exception stored as an attribute to the “ErrorPage.jsp”.
      sContext.getRequestDispatcher("/jsp/ErrorPage.jsp").forward(req, resp);
      ex.printStackTrace();
}

2.) Forwarding to/Including a servlet from a servlet

// relative path of the resource
RequestDispatcher rd = sc.getRequestDispatcher(“/nextServlet”).forward(request,response);

// includes the content of the resource such as Servlet,JSP, HTML, Images etc
rd.include(request, response);

B.) Forward from a JSP Page:


3.) Forwarding/including a servlet from JSP 
You can invoke a Servlet from a JSP through the jsp:include and jsp:forward action tags

<%-- forward with parameters passed --%>
<jsp:forward page=”/servlet/crm.do”>
      <jsp:param name=”userName” value=”Peter” />
</jsp:forward>

And similar is include.
<jsp:include page=”/servlet/MyServlet” flush=”true” />

Q45. Generally you would be invoking a JSP page from a Servlet. Why would you want to invoke a Servlet from a JSP?
Ans. JSP technology is intended to simplify the programming of dynamic textual content. If you want to output any binary data (e.g. pdfs, gifs etc), then JSP pages are poor choice for the following reasons and we should use Servlets instead:
• There are no methods for writing raw bytes in the JspWriter object.
• During execution, the JSP engine preserves whitespace. Whitespace is sometimes unwanted (for example in a .gif file), making JSP pages a poor choice for generating binary data. In the following example, the browser receives unnecessary newline characters in the middle or at the end of the binary data depending on the buffering of your output. “out” is a JspWriter implicit object.

<% out.getOutputStream().write(...some binary data...) %>


Q46. Talk about different response codes 
Ans. Response codes themselves are three-digit numbers that are divided into groups. Each group has a meaning as shown here:
● 1xx: Informational: Request received, continuing process.
● 2xx: Success: The action was successfully received, understood, and accepted.
● 3xx: Redirection: Further action must be taken in order to complete the request.
● 4xx: User-Agent Error: The request contains bad syntax or cannot be fulfilled.
● 5xx: Server Error: The server failed to fulfill an apparently valid request.


Q47. Servlet Event Listeners 
Ans. In many situations it is desirable to be notified of container-managed life cycle events. An easy example to think of is knowing when the container initializes a Web Application and when a Web Application is removed from use. Knowing this information is helpful because you may have code that relies on it, perhaps a database that needs to be loaded at startup and saved at shutdown. Another good example is keeping track of the number of concurrent clients using a Web Application. 

This functionality can be done with Servlet event listeners mechanism. All of the Servlet event listeners are defined by interfaces. There are event listener interfaces for all of the important events related to a Web Application and Servlets like life cycle events, request attribute binding. Various listeners are: 
● javax.servlet.ServletRequestListener
● javax.servlet.ServletRequestAttributeListener
● javax.servlet.ServletContextListener
● javax.servlet.ServletContextAttributeListener
● javax.servlet.http.HttpSessionListener
● javax.servlet.http.HttpSessionAttributeListener
● javax.servlet.http.HttpSessionAttributeListener 


Q48. Virtual Path Translation.
Ans. A Web Application's virtual directory is helpful because it allows fictitious paths to link to real resources located in the Web Application. The only downside to the functionality is that Web Application developers cannot directly use virtual paths to obtain the location of a physical resource. To solve this problem, the ServletContext object provides the following method: 

1. getRealPath(String path): Again, be aware that a Servlet container is free to load Web Applications from places other than the file system (for example, directly from WAR files or from a database); in that case this method may return null. It returns a String containing the real path for a given virtual path. 


2. getResourcePaths(String path): The getResourcePaths() method returns a set of all the resources in the directory specified by the path. The path must start from the root of the Web Application, "/". 

3. getResourceAsStream(String path): The getResourceAsStream() method returns an instance of an InputStream to the physical resource of a Web Application. This method should be used when a resource needs to be read verbatim rather than processed by a Web Application. 

4. getResource(String path): The getResource() method returns a URL to the resource that is mapped to a specified path. This method should be used when a resource needs to be read as it would be displayed to a client.

It is important to remember that a Web Application is designed to be portable. Hard coding file locations in Servlet code is not good practice because it usually causes the Servlet not to work when deployed on a different server or if the Web Application is run directly from a compressed WAR file. The correct method for reading a resource from a Web Application is by using either the getResource() or getResourceAsStream() methods. These two methods ensure the Servlet will always obtain access to the desired resource even if the Web Application is deployed on multiple servers or as a compressed WAR


Q49. Cookies in detail
Ans. Cookie is small piece of textual information saved by a website/domain on user’s browser. Basic use of cookie is to identify user or any user related information in future and serve content accordingly. For example, if you select “Stay signed in” checkbox while login to your mailbox, it would take you directly to your inbox when you access it in future. It is simply because of cookie placed in your browser. They are usually stored at %userprofile%\AppData\Roaming\Microsoft\Windows\Cookies ie. C:\Users\Mishu\AppData\Roaming\Microsoft\Windows\Cookies

Cookie consists of name-value pair where name is used to identify cookie on the server. It is set by the web-server in users’ browser through HTTP header using server side scripts like ASP, C#, JSP, Perl, PHP etc. or client-side script like JavaScript. Cookie is sent with every users’ request made to web-server.

Here we have to understand that a cookie, set by a web-server, can be accessed only by the same web-server. It can’t be taken as disadvantage since it protects user’s information being used by unauthorized domain. But in some cases, it required to access a cookie by domain which is set by another domain. 

Google is the best example for understanding this concept. Google uses different sub domains for their applications such as mail,search,plus. Since Google uses same login information for all or their applications they need to keep the login data between all of the applications. Normally login data is kept in browser session. Since each sub domain creates a different session, its not possible to keep the login data using sessions. Thats where cookies comes to save us. We can set cookie values for multiple sites and keep the data we want to show in each application. PHP allows us to share cookies across multiple domains.

For example, a shopping cart is hosted on domain example.com. For login and cart item, the domain has created cookie(s) in user’s browser. Now for payment process, the user is directed to another domain, let’s say payment.com, which is integrated with payment gateway. If you want to access the cookie set by example.com, it would not be possible. It is only possible by a way around it.


There are various types of cookies as explained below:
1. Session cookie: A session cookie only lasts for the duration of users using the website. A web browser normally deletes session cookies when it quits. A session cookie is created when no Expires directive is provided when the cookie is created.

2. Persistent cookie: A persistent Cookie will outlast user sessions. If a persistent cookie has its Max-Age set to 1 year, then, within the year, the initial value set in that cookie would be sent back to the server every time the user visited the server. This could be used to record a vital piece of information such as how the user initially came to this website. For this reason, persistent cookies are also called tracking cookies.

3. Secure cookie: A secure cookie is only used when a browser is visiting a server via HTTPS, ensuring that the cookie is always encrypted when transmitting from client to server. This makes the cookie less likely to be exposed to cookie theft via eavesdropping.

4. HttpOnly cookie: The HttpOnly cookie is supported by most modern browsers. On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other, non-HTTP APIs (such as JavaScript). This restriction mitigates but does not eliminate the threat of session cookie theft via Cross-site scripting. This feature applies only to session-management cookies, and not other browser cookies.

5. Third-party cookie: First-party cookies are cookies set with the same domain (or its subdomain) in your browser's address bar. Third-party cookies are cookies being set with different domains than the one shown on the address bar i.e. the web pages on that domain may feature content from a third-party domain. For ex: An advertisement run by www.advexample.com showing advert banners. Suppose a user visits www.example1.com, which sets a cookie with the domain ad.foxytracking.com. When the user later visits www.example2.com, another cookie is set with the domain ad.foxytracking.com. Eventually, both of these cookies will be sent to the advertiser when loading their ads or visiting their website. The advertiser can then use these cookies to build up a browsing history of the user across all the websites this advertiser has footprints on.

6. Supercookie: A "supercookie" is a cookie with a public suffix domain, like .com, .co.uk or k12.ca.us. Most browsers, by default, allow first-party cookies—a cookie with domain to be the same or sub-domain of the requesting host. For example, a user visiting www.example.com can have a cookie set with domain www.example.com or .example.com, but not .com. A supercookie with domain .com would be blocked by browsers; otherwise, a malicious website, like attacker.com, could set a supercookie with domain .com and potentially disrupt or impersonate legitimate user requests to www.example.com.

7. Zombie cookie: A zombie cookie is any cookie that is automatically recreated after a user has deleted it. This is accomplished by a script storing the content of the cookie in some other locations, such as the local storage available to Flash content, HTML5 storages and other client side mechanisms, and then recreating the cookie from backup stores when the cookie's absence is detected.

Q50. How to share share cookies across subdomain?
Ans. A sub-domain is a subset of the main domain that has a separate IP. For example, if you purchase the domain myserver.com, you can break it down into sub domains like the following:
● www.myserver.com
● smtp.myserver.com
● client1.myserver.com
● secure.myserver.com

You can issue a cookie on the www.myserver.com domain as below:
       <% Response.Cookies("UID")=1 %>

This cookie will only last for the length of the user session, defined by the amount of time that browser stays open. The cookie's scope is just "www.myserver.com" domain. If you request this cookie on other sub domains within the same domain, you will not be able to get the value associated to UID. You can solve this problem by substituting above code as below:

<%
Response.Cookies("UID")=1
Response.Cookies("UID").Domain = ".myserver.com"
%>

By setting the Domain property of the cookie to the sub domain, you instruct the browser to send the cookie to all sub domains. Notice the period before the domain name, this is very important. RFC 2109 specifies that the domain setting on cookies must have two periods.

Steps to access cookie across domain:
The secret to sharing cookies easily is redirection. Here is the general procedure:
1. A user hits siteA.com
2. If user does not have cookie for siteA.com, then redirect the user to siteB.com
3. If user has a cookie for siteB.com, then redirect back to siteA.com with a special identifier (explained below), else, just send user back to siteA.com
4. Write cookie on siteA.com

Let's expound a bit: siteA.com and siteB.com share the same set of users, and therefore if someone has a cookie (and is registered) at siteB.com, then siteA.com wants to be able to view those cookies as well, and provide whatever features the cookies allow. This way, visitors to siteA.com will have a similar experience to those at siteB.com. The key to this checking should be done in a "cookies.inc" file that you include on your pages on siteA.com. Let's take a look at the code on siteA.com:

Table 1.1
'SiteA.com

'Check for a cookie
If Request.Querystring("Checked") <> "True" then
        If not Request.Cookies("SiteA_Cookie").Haskeys then
                  'redirect to siteB.com
                  Response.Redirect("http://www.siteB.com/cookie.asp")
        End if
End if


If the user already has a cookie for siteA.com, then we don't need to do anything - simply process the rest of the page. The first if statement is used to eliminate infinite loops, and doesn't really make sense by itself. Let's look at cookie.asp on siteB.com to gain a better understanding.

Table 1.2
'SiteB.com

'Check for a cookie
If not Request.Cookies("SiteB_Cookie").Haskeys then
        'redirect to siteA.com
        Response.Redirect("http://www.siteA.com/index.asp" _
                  & "?checked=True")
Else
        'grab username
        strUsername = Request.Cookies("SiteB_Cookie")("Username")
        'send back to siteA.com with unique identifier
        Response.Redirect("http://www.siteA.com/index.asp" _
                  & "?checked=True&identifier= & strUsername)
End if


If user doesn't have a cookie on siteB.com also, then send them back to siteA.com and let the application know that you've already checked for the cookie by supplying a variable called "checked" in the query string. Otherwise, it will send the user right back to siteB.com, and you'll end up with an infinite loop.

Note: You can be sneaky here and redirect the user back to a registration page, or something similar.
However, if the user does have a cookie on siteB.com, we need to send the user back and let siteA.com know about it. Hence, we attach a variable that uniquely identifies this user in our database, their username. Now, let's expand upon the code on siteA.com. The following code goes below what is already there in table 1.1.

Table 1.3
'SiteA.com
...
...

'Check for an identifier
If Request.Querystring("identifier") <> "" then
        strUsername = Request.Querystring("identifier")
       
        'perform some database stuff here (optional)   
        Response.Cookies("SiteA_Cookie").Expires = Date + 365
        Response.Cookies("SiteA_Cookie").Domain = "siteA.com"
        Response.Cookies("SiteA_Cookie")("Username") = strUsername
End if


Finally, we're back on siteA.com. The first part of this file (as written in table 1.1) would check to see whether the cookie check has been accomplished, and, since it obviously has (as indicated by the "checked" parameter in the querys tring), we move onto the second part of the code displayed in table 1.3. If there is a specified identifier, then we can now build the cookie on siteA.com. Using the identifier (in this case - user name), we could query a database or perform whatever manipulation we may need, if any at all. Then we set the cookie, and display the rest of the page. If there is no identifier specified, then we don't worry about any of this, and simply display the rest of the page as you would normally. SiteA.com now has the same cookie as siteB.com, and you didn't even have to break a sweat.

NOTE: If you have an aggressive customization scheme going, you can do interesting things by displaying different message (for instance, "special deals" for an e-commerce site) based on the cookie information.

1 comment:

  1. Thanks for telling us about Servlets and it's functioning... Also check Super Gadget Factory

    ReplyDelete