Q. How would you get the browser to request for an updated page in 10 seconds from the server?
response.setHeader(“Refresh”, 10);
Refresh does not stipulate continual updates. It just specifies in how many seconds the next update should take place.
So, you have to continue to supply “Refresh” in all subsequent responses. The “Refresh” header is very useful because it
lets the servlet display a partial list of items or an introductory image to be displayed while the complete results or real
page is displayed later (say in 10 seconds). You can also specify another page to be reloaded as follows:
respose.setHeader(“Refresh”, “10;URL=http://localhost:8080/myCtxt/crm.do”);
The above setting can be directly set in the section of the HTML page as shown below as opposed to setting it
in the servlet. This is useful for static HTML pages.
Q. How would you get the browser to request for an updated page in 10 seconds from the server?
A: response.setHeader(“Refresh”, 10);
Refresh does not stipulate continual updates. It just specifies in how many seconds the next update should take place.
So, you have to continue to supply “Refresh” in all subsequent responses. The “Refresh” header is very useful because it
lets the servlet display a partial list of items or an introductory image to be displayed while the complete results or real
page is displayed later (say in 10 seconds). You can also specify another page to be reloaded as follows:
respose.setHeader(“Refresh”, “10;URL=http://localhost:8080/myCtxt/crm.do”);
The above setting can be directly set in the section of the HTML page as shown below as opposed to setting it
in the servlet. This is useful for static HTML pages.
Q. What are the two objects a servlet receives when it accepts a call from its client?
A: “ServletRequest”, which
encapsulates client request from the client and the “ServletResponse”, which encapsulates the communication from the
servlet back to the client.
In addition to both HTTP request and response, HTTP headers are informational additions that convey both essential and
non-essential information. For example: HTTP headers are used to convey MIME (Multipurpose Internet Mail Extension)
type of an HTTP request and also to set and retrieve cookies etc.
Content-Type: text/html
Set-Cookie:AV+USERKEY=AVSe5678f6c1tgfd;expires=Monday, 4-Jul-2006 12:00:00; path=/;domain=.abc.com;
response.setContentType(“text/html”);
response.addCookie(myCookie);
Q. What can you do in your Servlet/JSP code to tell browser not to cache the pages?
A:Another useful header is the
Cache-Control as shown below:
response.setHeader(“Cache-Control”,“no-cache”); //document should never be cached. HTTP 1.1
response.setHeader(“Pragma”, “no-cache”); //HTTP 1.0
response.setDateHeader(“Expires”, 0);
Q. What are the different scopes or places where a servlet can save data for its processing?
A: 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”);
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”);
}
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”);
Q. Which code line should be set in a response object before using the PrintWriter or the OutputStream?
A: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”);
Q : HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests?
A : This is a commonly asked interview question. The “http protocol” is a stateless request/response based protocol.
You can retain the state information between different page requests as follows:
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: CO
HttpSession session = request.getSession(true); //returns a current session or a new session
//To put/get a value in/from the session
Name name = new Name(“Peter”);
session.setAttribute(“Firstname”, name); //session.putValue(…) is deprecated as of 2.2
session.getAttribute(“Firstname”);//get a value. session.getValue(…) is deprecated
//If a session is no longer required e.g. user has logged out, etc then it can be invalidated.
session.invalidate();
//you can also set the session inactivity lease period on a per session basis
session.setMaxInactiveInterval(300);//resets inactivity period for this session as 5 minutes
Q. Session tracking uses cookies by default. What would you do if the cookies are turned off?
A: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 the following methods:
response.encodeURL(givenURL) to associate a session ID with a given URL and if you are using redirection
then 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("Sample encoded URL -->purchase");
}
}
//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("Item to purchase is --> " + value +"");
}
}
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
Q. What is the difference between using getSession(true) and getSession(false) methods?
A:getSession(true): This method will check whether there is already a session exists for the user. If a session
exists, it returns that session object. If a session does not already exist then it creates a new session for the user.
getSession(false): This method will check whether there is already a session exists for the user. If a session
exists, it returns that session object. If a session does not already exist then it returns null.
Sessions can be timed out (configured in web.xml) or manually invalidated.
Hidden Fields on the pages can maintain state and they are not visible on the browser. The server treats both
hidden and non-hidden fields the same way.
The disadvantage of hidden fields is that they may expose sensitive or private information to others.
URL re-writing will append the state information as a query string to the URL. This should not be used to maintain
private or sensitive information.
Http://MyServer:8080/MyServlet?Firstname=Peter&Lastname=Smith
Cookies: 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:
�� 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.
�� 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.
Servlet Interview Questions
Monday, July 20, 2009
|
digg it
No comments
Posted by Sitesh Gupta