1)What is the functionality of web server? What are servlets?
Answer 1) Web server that provides services to remote clients has two main responsibilities:- http://capptitudebank.blogspot.in/
The first is to handle network connections; the second is to create a response to be sent back.
The first task involves programming at the socket level, extracting information from request messages, and implementing client-server protocols, such as HTTP.
The second task, creating the response, they have to create the response dynamically, which may involve complicated tasks, such as retrieving data from the database, applying business rules and presenting the output in the formats desired by different clients.
Obviously, we cannot write a single program that handles all these tasks. Furthermore, what if a new functionality has to be added? What if the data format changes? Modifying the source files (especially after the developer has left!) to add new code is surely the last thing we want to do.
Well, there is a better design for these kinds of servers: divide the code into two executable parts—
One that handles the network -----that part is called as web server and one that provides the application logic------ that part is called as Servlet —and let the two executables have a standard interface between them. This kind of separation makes it possible to modify the code in the application logic without affecting the network module, as long as we follow the rules of the interface.
Servlets are the separate executable modules that can be loaded into its memory and initialized only once—when the server starts up. Each request can then be served by the already in-memory and ready-to-serve copy of the servlet. In java Servlets are written using servlet API.
2) Explain diff between static and dynamic programming with an example?
4) Why URL and port are required?
5) Explain servlet and jsp lifecycle?
Answer5) Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method can’t be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.
6)Identify the advantages of JSP over Servlet.
Answer 6:
a) Embedding of Java code in HTML pages
b) Platform independence
c) Creation of database-driven Web applications
d) Server-side programming capabilities
Answer :- Embedding of Java code in HTML pages
Write the following code for a JSP page:
<%@ page language = "java" %>
<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%
PrintWriter print = request.getWriter();
print.println("Welcome");
%>
</BODY>
</HTML>
Suppose you access this JSP file, Find out your answer.
a) A blank page will be displayed.
b) A page with the text Welcome is displayed
c) An exception will be thrown because the implicit out object is not used
d) An exception will be thrown because PrintWriter can be used in servlets only
Answer :- A page with the text Welcome is displayed
Explain MVC architecture with an example?
What is difference between socket programming and rmi?
What is the use of rmi registry?
Jsp Questions
Question:1 What is JSP Custom tags?
Answer:1 JSP Custom tags are user defined JSP language element. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tag for encapsulate both simple and complex behaviors in an easy to use syntax and greatly simplify the readability of JSP pages.
Question:2 What is JSP?
Answer:2 JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers
Question:3 What is the role of JSP in MVC Model?
Answer:3 JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.
Question:4 What do you understand by context initialization parameters?
Answer:4 The context-param element contains the declaration of a web application's servlet context initialization parameters.
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.
Question:5 Can you extend JSP technology?
Answer:5 JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions and tag libraries can be developed.
Question:6 What do you understand by JSP translation?
Answer:6 JSP translators generate standard Java code for a JSP page implementation class. This class is essentially a servlet class wrapped with features for JSP functionality. http://capptitudebank.blogspot.in/
Question:7 What you can stop the browser to cash your page?
Answer:7 Instead of deleting a cache, you can force the browser not to catch the page.
<%
response.setHeader("pragma","no-cache");//HTTP 1.1
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.addDateHeader("Expires", -1);
response.setDateHeader("max-age", 0);
//response.setIntHeader ("Expires", -1); //prevents caching at the proxy server
response.addHeader("cache-Control", "private");
%>
put the above code in your page.
Question8: What you will handle the runtime exception in your jsp page?
Answer:8 The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page.
For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered during request processing. Within "customerror.jsp", you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %>.
Question9:Diffrence between forward and sendredirect?
Answer:9 1)The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect kills the session variables.
Question 10:Define and explain in short jsp implicit objects?
Answer:10)Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
Variable
Class
Description
application
javax.servlet.ServletContext
The context for the JSP page's servlet and any Web components contained in the same application.
config
javax.servlet.ServletConfig
Initialization information for the JSP page's servlet.
exception
java.lang.Throwable
Accessible only from an error page.
out
javax.servlet.jsp.JspWriter
The output stream.
page
java.lang.Object
The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContext
javax.servlet.jsp.PageContext
The context for the JSP page. Provides a single API to manage the various scoped attributes.
request
Subtype of javax.servlet.ServletRequest
The request triggering the execution of the JSP page.
response
Subtype of javax.servlet.ServletResponse
The response to be returned to the client. Not typically used by JSP page authors.
session
javax.servlet.http.HttpSession
The session object for the client.
Question 11) What is the difference between <jsp:include page = ... > and <%@ include file = ... >?
Answer:11) Both the tag includes the information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed (the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.
<%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
Question 12)What types of comments are available in the JSP?
Answer:12) There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%> also called as jsp comment
Example of output comment:
<!-- This is output comment --> also called as html comment
Question 13) What do you understand by JSP Actions?
Answer:13 JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/>
Question 14)What is expression in JSP?
Answer: 14 Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is:
<%= expression %>
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The following expression tag displays time on the output:
<%=new java.util.Date()%>
Question 15) What types of comments are available in the JSP?
Answer:15 There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%>
Example of output comment:
<!-- This is output comment -->
Question 16) What is JSP declaration?
Answer:16) JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:
<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
</body>
</html>
Question 17): What is JSP Scriptlet?
Answer:17 JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
Question 18): What are the types of Servlet?
Answer:18 There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality like doGet and doPost methods.
Question 19): What are the differences between HttpServlet and Generic Servlets?
Answer:19 HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
init and destroy, to manage resources that are held for the life of the servlet
getServletInfo, which the servlet uses to provide information about itself
There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there's almost no reason to override the doOptions and doTrace methods.
GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.
GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet.
GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.
To write a generic servlet, you need only override the abstract service method.
Question 20): Differentiate between Servlet and Applet.
Answer:20 Servlets are server side components that execute on the server whereas applets are client side components and executes on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets.
Question 21): Differentiate between Get and Post method?
Answer:21 Get request sends the data to the server by appending it to URL as part of query string
Post request sends the data as par of message body.
Use GET:
• To retrieve an HTML file or an image file, because only the filename needs to be sent.
Use POST:
• To send a lot of data; for example, POST is well suited for an online survey, since the length of the query string may exceed 255 characters.
• To upload a file, because the file size may exceed 255 characters, and moreover, the file may be a binary file.
• To capture the username and password, because we want to prevent users from seeing the password as a part of the URL.
Question 22) What are methods of HttpServlet?
Answer:22 The methods of HttpServlet class are :
* doGet() is used to handle the GET, conditional GET, and HEAD requests
* doPost() is used to handle POST requests
* doPut() is used to handle PUT requests
* doDelete() is used to handle DELETE requests
* doOptions() is used to handle the OPTIONS requests and
* doTrace() is used to handle the TRACE requests
Question 23) What are the advantages of Servlets over CGI programs?
Answer:23 Java Servlets have a number of advantages over CGI and other API's. They are:
Platform Independence
Java Servlets are 100% pure Java, so it is platform independence. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets.
Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites.
Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.
Safety
Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.
Secure
Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.
24) What are the lifecycle methods of Servlet?
Answer:24 The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps.
1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.
25)What is ServletContext?
Answer:25 ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
26) What is the directory Structure of Web Application?
Answer: 26Web components follow the standard directory structure defined in the J2EE specification.
27) What is meant by Pre-initialization of Servlet?
Answer: 27 When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-on-startup>
in between the <servlet></servlet> tag.
28) What mechanisms are used by a Servlet Container to maintain session information?
Answer:28 Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.
29) What do you understand by servlet mapping?
Answer:29 Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.
30) What must be implemented by all Servlets?
Answer:30The Servlet Interface must be implemented by all servlets.
31) What are the objects that are received when a servlets accepts call from client?
Answer:31 The objects are ServeltRequest and ServletResponse. The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client.
Session related interview questions:
Question:1 What is a Session?
Answer:1 A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.
Question:2 What is Session ID?
Answer:2 A session ID is an unique identification string usually a long, random and alpha-numeric string that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case URL rewriting) and hidden fields of Web pages.
Question:3 What is Session Tracking?
Answer:3 HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.
Question:4 What are different types of Session Tracking?
Answer:4 Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions
Question:5 What is HTTPSession Class?
Answer:5 HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.
Question:6 Why do u use Session Tracking in HttpServlet?
Answer:6 In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application.
Question:7 What are the advantage of Cookies over URL rewriting?
Answer:7 Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like URL rewriting.
Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not.
In URL rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.
Question:8 What is session hijacking?
Answer:8 If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress.
Question:9 What is Session Migration?
Answer: Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.
Question:10 How to track a user session in Servlets?
Answer: The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true);
Question:11 How you can destroy the session in Servlet?
Answer: You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate(); http://capptitudebank.blogspot.in/
If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!
0 comments:
Have any question? Feel Free To Post Below: