Friday, January 30, 2009

JSP & Servlet questions

1. The method getWriter returns an object of type PrintWriter. This class has println methods to generate output. Which of these classes define the getWriter method? Select the one correct answer.

A. HttpServletRequest
B. HttpServletResponse
C. ServletConfig
D. ServletContext
Ans: B. The class HttpServletResponse defines the getWriter method.
2. Name the method defined in the HttpServletResponse class that may be used to set the content type. Do not include parenthesis after the method.

setContentType

3. Which of the following statements is correct. Select the one correct answer.
A. The response from the server to a HEAD request consists of status line, content type and the document.
B. The response from the server to a GET request does not contain a document.
C. The setStatus method defined in the HttpServletRequest class takes an int as an argument and sets the status of Http response
D. The HttpServletResponse defines constants like SC_NOT_FOUND that may be used as a parameter to setStatus method.
D. The response from the server to a HEAD request does not contain the document, whereas the response to GET request does contain a document. So A and B are incorrect. C is incorrect because setStauts is defined in HttpServletResponse.
4. The sendError method defined in the HttpServlet class is equivalent to invoking the setStatus method with the following parameter. Select the one correct answer.
A. SC_OK
B. SC_MOVED_TEMPORARILY
C. SC_NOT_FOUND
D. SC_INTERNAL_SERVER_ERROR
E. ESC_BAD_REQUEST
C. sendError(String URL) is equivalent to sending SC_NOT_FOUND (404) response code.
5. The sendRedirect method defined in the HttpServlet class is equivalent to invoking the setStatus method with the following parameter and a Location header in the URL. Select the one correct answer.
A. SC_OK
B. SC_MOVED_TEMPORARILY
C. SC_NOT_FOUND
D. SC_INTERNAL_SERVER_ERROR
E. ESC_BAD_REQUEST
B. sendRedirect(String URL) is equivalent to sending SC_MOVED_TEMPORARILY (302) response code and a location header in the URL.

6. Which of the following statements are correct about the status of the Http response. Select the one correct answer.
A. A status of 200 to 299 signifies that the request was succesful.
B. A status of 300 to 399 are informational messages.
C. A status of 400 to 499 indicates an error in the server.
D. A status of 500 to 599 indicates an error in the client.
A. The following table specifies the specific the status code of Http response.
Status Code Purpose
100-199 Informational
200-299 Request was succesful
300-399 Request file has moved.
400-499 Client error
500-599 Server error.
7. To send binary outptut in a response, the following method of HttpServletResponse may be used to get the appropriate Writer/Stream object. Select the one correct answer.
A. getStream
B. getOutputStream
C. getBinaryStream
D. getWriter
B. The getOutputStream method is used to get an output stream to send binary data. The getWriter method is used to get a PrintWriter object that can be used to send text data.
8. To send text outptut in a response, the following method of HttpServletResponse may be used to get the appropriate Writer/Stream object. Select the one correct answer.
A. getStream
B. getOutputStream
C. getBinaryStream
D. getWriter
D
9. Is the following statement true or false. URL rewriting may be used when a browser is disabled. In URL encoding the session id is included as part of the URL.
ans :true. The statement about URL encoding is correct.
10. Name the class that includes the getSession method that is used to get the HttpSession object.
A. HttpServletRequest
B. HttpServletResponse
C. SessionContext
D. SessionConfig
A. The class HttpServletRequest defines the getSession method.


11. Which of the following are correct statements. Select the two correct answers.
A. The getRequestDispatcher method of ServletContext class takes the full path of the servlet, whereas the getRequestDispatcher method of HttpServletRequest class takes the path of the servlet relative to the ServletContext.
B. The include method defined in the RequestDispatcher class can be used to access one servlet from another. But it can be invoked only if no output has been sent to the server.
C. The getRequestDispatcher(String URL) is defined in both ServletContext and HttpServletRequest method
D. The getNamedDispatcher(String) defined in HttpServletRequest class takes the name of the servlet and returns an object of RequestDispatcher class
A, C.

12. How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:

<%@ page errorPage="error.jsp" %>

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.

Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the error page via the exception implicit object.


Note: You must always use a relative URL as the value for the
errorPage attribute.

13. How do I perform browser redirection from a JSP page?

You can use the response implicit object to redirect the browser to a different resource, as:

response.sendRedirect("http://www.foo.com/path/error.html");

14. Applet Servlet Communication

You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

15. How do I connect to my Java server with a socket when the client applet/application runs behind a proxy/firewall?

I tried it with an applet, but it throws the "host unreachable" exception, among others.

You cannot connect because the client's proxy/firewall prevents most
socket connections. Most firewalls prevent any kind of communication, except for HTTP. This is done to protect the internal infrastructure; users can still browse the Web, but cannot connect to other networked
applications.
However, there are ways to connect your Java applications to Java servers through HTTP. This is sometimes called firewall tunneling. To do this easily, create servlets on the server side and wrap all client messages in HTTP requests.

On the client side, your code should use the URLConnection to send
data to the server:


//connect
URL url = new URL("http://www.myserver.com/servlets/myservlet");

URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/octet-stream");

//Open output stream and send some data.
OutputStream out = conn.getOutputStream();
//I am not going to send anything on "out," but you can fill this in.

out.flush();
out.close();

//Open input stream and read the data back.
InputStream in = conn.getInputStream();

//Here you would read the data back.

in.close()


On the server side, when the client says openConnection(), the servlet's doPost() method will be called. In that method, you can read the data and write back to the client.

16. HTTP Tunneling
HTTP tunneling is a general technique whereby data may be sent via an HTTP connection to and from Java Servlets on a Web server. This is done by serializing the data to be transmitted into a stream of bytes, and sending an HTTP message with content type "application/octet-stream". HTTP tunneling is also referred to as Firewall tunneling.

17. What is inter-servlet communication?
As the name says it, it is communication between servlets. Servlets talking to each other. There are many ways to communicate between servlets, including
Request Dispatching
HTTP Redirect
Servlet Chaining
HTTP request (using sockets or the URLConnection class) Shared session, request, or application objects (beans)

Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.

e.g. ServletContext.getRequestDispatcher(HttpRequest,HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.

18 what is Servlet Filtering?
A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource. Filters can act on dynamic or static content. These dynamic and static contents are referred to asweb resources.

Among the types of functionality available to the filter author are
• The accessing of a resource before a request to it is invoked.
• The processing of the request for a resource before it is invoked.
• The modification of request headers and data by wrapping the request in cus-tomized versions of the request object.
• The modification of response headers and response data by providing custom-ized versions of the response object.
• The interception of an invocation of a resource after its call.
• Actions on a servlet, on groups of servlets or static content by zero, one or more filters in a specifiable order.

Examples of Filtering Components
• Authentication filters
• Logging and auditing filters
• Image conversion filters
• Data compression filters
• Encryption filters
• Tokenizing filters
• Filters that trigger resource access events
• XSL/T filters that transform XML content
• MIME-type chain filters
• Caching filters

19. JSP to Servlet communication -Vice Versa

From JSP to Servlet:
When we want to pass a object to Servlet from a JSP page You insert that object you need in the request scope with request.setAttribute()
Then use to the servlet.
In the servlet you use request.getAttribute() to get the object back !

From Servlet to JSP
You insert the object with request.setAttribute(),then use RequestDispatcher ,to forward to the JSP page In the JSP page you use request.getAttribute() to get the object back.
This is the way of communication i do in my projects,Any new :) idea of communication is available than this ?]

20. What is the diffrent between seesion and cookies
session in short lived,and cookies is long lived !
First of all session and cookies should not be compared for differences. To create a session a cookie that stores a session ID is required, so that for every subsequent calls the app server could distinguish between various sessions. Cookies can be used to store additional information, but there primary cause is to store the session ids. Point to note: A server cannot track user sessions if cookies are disabled in the browser. There are other methods like URL Rewritting. But then the true essence of session tracking is lost. All i want to say, is sessions should not be understood as server side cookies or cookies should not be understood as client side sessions. Both were created to facilitate user connection identification. Which means that they should not be compared, since they were made for made to solve different purposes. As far as long lived and short lived is concerned, both have a expiration time which can be set as per will..

21. Whats the difference between using tag and request.sendRedirect

tag is
* Functions only within the single servlet context
* Location/addrs in the borwser doesnt changes when used

1. Using request.sendRedirect u can redirect the browser to diffrent location

2. forwarding is done within the server, and limited in scope to where you can forward. Redirections are done on the client and thus don't have these limitations.

Redirect sends a HTTP redirect code to the user-agent(Browser).Hence it involves a full roundtrip.If we use forward,we can avoid this traffic
22. When a JSP page is compiled, what is it turned into?
A.
Applet
B.
Servlet
C.
Application
D.
Mailet
Answer (B): Compiled JSP pages are turned into Servlets. See JSP Architecture for more information on this translation phase.

23 . Which of the following is not a standard method called as part of the JSP life cycle?
A.
jspInit()
B.
jspService()
C.
_jspService()
D.
jspDestroy()
Answer (B): The standard service method for JSP has an _ in its name
24. If you want to override a JSP file's initialization method, within what type of tags must you declare the method?
A.
<@ @>
B.
<%@ %>
C.
<% %>
D.
<%! %>
Answer (D): Declarations are placed within a set of <%! %> tags.
25. Which of the following can not be used as the scope when using a JavaBean with JSP?
A.
application
B.
session
C.
request
D.
response
E.
page
Answer (D): Response is not a valid object scope for JavaBeans (or anything else).
26. The implicit JSP objects like request, response, and out are only visible in the _jspService() method.
A.
True
B.
False
Answer (D): Response is not a valid object scope for JavaBeans (or anything else).
27. What is the key difference between using a and HttpServletResponse.sendRedirect()?
A.
forward executes on the client while sendRedirect() executes on the server.
B.
forward executes on the server while sendRedirect() executes on the client.
C.
The two methods perform identically.
Answer (B): When you forward a request, the forwarding is done within the server, and limited in scope to where you can forward. Redirections are done on the client and thus don't have these limitations.
28.. Which of the following statements makes your compiled JSP page implement the SingleThreadModel interface?
A. <%@ page isThreadSafe="false" %>
B. <%@ page isThreadSafe="true" %>
Answer (A): If you flag the JSP page as not being thread safe, it will implement the interface.
29. Of the following four valid comment styles that can be used within JSP pages, which can the end user see?
A. <%-- My comments <% out.println("Hello World"); %>
--%>
B.
C. <% // For Loop for (int i=1; i<=4; i++) { %>
<%=i%>>Hello<%=i%>>
<% } %>
D. <% /** yet another comment */ JavaDoc Rules %>
Answer (B): Only the JavaScript comment can be seen from the generated page. The other comments will be buried in the source for the generated servlet.
30 . How can a servlet call a JSP error page?
A.
This capability is not supported.
B.
When the servlet throws the exception, it will automatically be caught by the calling JSP page.
C.
The servlet needs to forward the request to the specific error page URL. The exception is passed along as an attribute named "javax.servlet.jsp.jspException".
D.
The servlet needs to redirect the response to the specific error page, saving the exception off in a cookie.
Answer (C): D will get the browser to display the appropriate page, it just doesn't preserve the state information requiring an unnecessary round trip to the browser. C is the direct approach.
31. When using a JavaBean to get all the parameters from a form, what must the property be set to (??? in the following code) for automatic initialization?



A.
*
B.
all
C.
@
D.
=
Answer (A): The * character is used for this.

32 . IsThreadSafe.. how it works?
By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state is effectively synchronized. There are a couple of different ways to ensure that the service methods are thread-safe. The easy approach is to include the JSP page directive:
<%@ page isThreadSafe="false" %>
This causes the JSP page implementation class to implement the SingleThreadModel interface, resulting in the synchronization of the service method, and having multiple instances of the servlet to be loaded in memory. The concurrent client requests are then distributed evenly amongst these instances for processing in a round-robin fashion, as shown below:

The downside of using this approach is that it is not scalable. If the wait queue grows due to a large number of concurrent requests overwhelming the processing ability of the servlet instances, then the client may suffer a significant delay in obtaining the response.
A better approach is to explicitly synchronize access to shared objects (like those instances with application scope, for example) within the JSP page, using scriptlets:
<% synchronized (application) { SharedObject foo = (SharedObject) application.getAttribute("sharedObject"); foo.update(someValue); application.setAttribute("sharedObject",foo); } %>


33. session.getValue("name") has been deprecated, what method do I call instead?

Use session.getAttribute("name").toString() to accomplish the same thing as the deprecated getValue method.

34. What is the difference between request.getAttribute() and request.getParameter()?

In a request object you can store, on the server side, some object that can be useful during the processing of your pages. This uses request.setAttribute() and request.getAttribute(). Remember that the life of the request object lasts through all the include and forwards, and ends when the page has been sent back to the browser.The getParameter() method, instead, will return you the specific parameter that has been passed to the page through GET or POST.

35. What is a Servlet Context?
A servlet conatiner can have several servlet context Each Servlet context share the common resources

36. Internatilization?
means making it easier for an application to adapt to different regions and languages. The main purpose here is to see that it is not necessary to compile ur programs to make it work with different languages and regions. Things like lables,messages etc need to be separated from ur program code.

37. Can scriptlets contain methods?
the answer is no. Any code included within the scriptlet will finally be part of
_jspService method. Since java does not support nested methods scriptlets cannot contain and methods.
Is JSP Single Threaded?

38. By default JSP Is multi threaded

However u can make it act as single thread as making the isThreadSafe to True


39. Diff in <%@ page isThreadSafe="true" %> or <%@ page isThreadSafe="false" %>

It is required to set the isthreadsafe to false if u want singlethreadmodel.

The default value is true,which means that the JSP container can send multiple, concurrent client requests
to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.

40. difference between Generic servlets and http servlets.
Consider we are having two servlets A and B. Syntax for calling a method in servlet A from B.

41. when we use only doget()
goGet() method is to rerieve data from server by supplying minimal data inputs.Thats why max data size is 255 chars in doGet().

42. Difference between Container and Server

Web container provides runtime environment for Web components (a Web component is a Servlet or a JSP) and services for these components:
security, oncurrency, life cycle management, transaction, deployment, etc. A Web server is software that provides services to access the nternet; it hosts Web sites. It also performs certain functions for the Web container (such as message handling) and hosting.

43. How many instances wil be created for a servlet if thousand users access a servlet

Only one instance ,since servlet is Multithreaded Arch So only one instance wil be created

44. But the interviewer said not exactly the only one instance It may increase its instance and not limited ONE ,On what criteria the instance will be increaed

For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a
servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize
requests to a particular instance. In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per virtual machine (VM). However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each VM of the container.
45. What is the Diff between RequestDispatcher.forward() or HttpServletResponse.sendRedirect()
Two Types of dispatching are available.Forwarding is achieved through the javax.servlet.RequestDispatcher interface.And redirecting is available through the javax.servlet.http.HttpServletResponse interface. When you forward the web container makes a direct call to the target resource without the browsers knowledge.Therefore the url in the browsers window does not change.If users refresh the page to reload , they get the page you forwarded from,not the page you forwarded to.To forward a request you can call the javax.servlet.RequestDispatcher.forward(),passing the request and response objects as parameters.You obtain a reference to RequestDispatcher either from the ServletContext or the HttpServletRequest.ie
ServletContext ctx=this.getServletContext();
RequestDispatcher dispatcher=ctx.getRequestDispatcher("/registerServet");
dispatcher.forward(request,response);
//or....
RequestDispatcher dispatcher=request.getRequestDispatcher("/registerServet");
dispatcher.forward(request,response);
The difference between these two methods is in the ServletContext version the path you provide for the RequestDispatcher must begin with a / and is always relative to Context root.In the HttpServletRequest version,you can omit the leading /,in which case the path is interpretted to be relative to servlet doing forwarding. Redirecting on the otherhand,forces the browser to issue a completely new request to the target page,as if the users had requested it themselves.
response.sendRedirect("/home.html");
46. Choosing Between Forward and Redirect ?

If you want to pass the control from one page to another, you can either forward to the other page, as described above, or redirect to the new page (using the sendRedirect() method of the implicit response object).

There's an important difference between a forward and a redirect. When you forward, the target page is invoked by the JSP container through an internal method call; the new page continues to process the same request and the browser is not aware of the fact that more than one page is involved. A redirect, on the other hand, means that the first page tells the browser to make a new request to the target page. The URL shown in the browser therefore changes to the URL of the new page when you redirect, but stays unchanged when you use forward. A redirect is slower than a forward because the browser has to make a new request. Another difference is that request scope objects are no longer available after a redirect because it results in a new request. If you need to pass data to the page you redirect to, you have to use a query string and pass them as request parameters (or save the data as session or application scope objects).

So how do you decide if you should use forward or redirect? I look at it like this: Forwarding is always faster, so that's the first choice. But since the URL in the browser refers to the start page even after the forward, I ask myself what happens if the user reloads the page (or just resizes the window; this often reloads the page automatically). If the start page is a page that updates some information, such as adding an item to the shopping cart or inserting information in a database, I don't want it to be invoked again on a reload. To show the result of the processing, I therefore redirect to a page with a confirmation message, instead of using forward.

47. Diff between and <%@ include file="relativeURL" %> ?
adds the content of the page at runtime.
<%@i...> include the page when the jsp file gets compiled.

compiles the files sperately and includes into the JSP page
<%@ include file="relativeURL" %> compiles as part of the current JSP like #include in C

48. why there is no constructors in Servlets?can we have constructor in servlets?if we can how is differed from init() method in servlets?

There is at any time only one instance of a servlet running so you do not need constructors. For passing any values to a servlet on creation you can add parameters to the deployment-descriptor-file. and for performing any tasks on initialising the servlet you can perform them in the servlets init() method. so there is no need for constructors

49. how to view the servlet file that is generated from JSP??? And how find the exact location of the Exception that occured in JSP during runtime.??????
If the appserver that you are using is Websphere please add in a new attribute KeepGenerated with value true in the applications ibm-web-ext.xmi. file .you can find this in the applications deployed directory. this will save the intermediary servlet.java files that are generated
50 if u r using tomcat 3.3.1 we can see the servlet file in the following directory.
In the "tomcat" main directory.
go for "work" directory.
go for " default" directory.
go for the directory were u have placed JSP file like
if u have placed ur jsp file in "webapps/example"
directory then go for "example" directory.
go for "jsp" directory.
here u can see all the servlet files generated for ur JSP files.

51. What is the capacity of parameters that can be sent to servlet thru doGet method?
it depends on the capacity of your environment variable. e.g. for windows it is 2048 characters.

52. How to know in servlet/jsp whether browser accepts cookies or not?
in HttpRequest, there is a method, isRequestedSessionIdFromCookie
which returns true if browser accepts cookie.

53. How to disable back button in browser?
You can disable back button in browser by setting the history to "0".

54. How many cookies(maximum numbers) you can set in a website.
The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

55. If there are 2 entries for a servlet in web.xml then there will be 2 instances?

56. There is a text box in my JSP page. User is allowed to fill any characters like & % etc. How will you send this information in Query string?

57. I m having 2 forms in my page. If I click submit button on my page what will happen? Both the form s will be submitted or not?


0 Comments: