Q) Servlet
Servlet is server side component, a servlet is small pluggable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Servlets will be loaded in the Address space of web server.
* Servlet are loaded 3 ways 1) When the web sever starts 2) You can set this in the configuration file 3) Through an administration interface.
* One of the new features in Servlet 3.0 is the introduction of annotation to define a servlet, thus making web.xml optional.
@WebServlet(urlPatterns = "/TestServlet", loadOnStartup = 1)public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(request, response);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(request, response);
}
Q) Life cycle of Servlet?
Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
* Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.
* Servicing the Request: After successfully completing the initialization process, the servlet will be available for service.
Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
* Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method this is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates the servlet releases all the resources associated with it.
Java Virtual Machine claims for the memory associated with the resources for garbage collection.
Q) Servlet Life cycle methods
public void init (ServletConfig config) throws ServletException
public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()
* init() method is called by the servlet container after the servlet class has been instantiated.(typically establishes database connections). We can use the try, catch statement inside the init method.
* Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet. If u put “Private” modifier for the service() it will give compile time error. Normally you could not override the service method if we override we need to call super.service().
* When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called. This allows you to free any resources you may have got hold of in your Servlet's init () method, this will call only once.
ServletException Signals that some error occurred during the processing of the request and the container should take appropriate measures to clean up the request.
IOException à Signals that Servlet is unable to handle requests either temporarily or permanently.
Q) Does the servlet run when the container starts up?
Servlet classes are not normally initialised when the servlet container is first started, they are brought into service when the first request for the servlet is received.
Q) What a servlet container does for each HTTP request?
Container loads the servlet class and calls the init method of the servlet as soon as the servlet is called for the first time. Then this container makes an instance of javax.servlet.ServletRequest/ServletResponse for each request.
Then it passes the ServletRequest and ServletResponse objects by invoking the servlet's service method.
public void service(ServletRequest req, ServletResponse res) {
try {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
} catch (ClassCastException e) {
}
service(request, response);
}
}
protected void service(HttpServletRequest req, HttpServletResponse resp) {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
doGet(req, resp);
}
}
Finally, it calls the destroy method and unload the servlet class when the servlet class is to be shut down.
Q) ServletConfig Interface & ServletContex Interfaces
ServletConfig
|
ServletContext
|
The ServletConfig interface is implemented by the servlet container in order to pass configuration information and initialization parameters to a servlet. The server passes the return ServeltConfig object to the init() method.
|
A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
|
There is one ServletConfig parameter per servlet.
|
There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
|
The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web.xml file
|
The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.
|
ServletConfig à The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. This used to obtain configuration data when it is loaded. There can be multiple ServletConfig objects in a single web application.
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
</web-app>
|
public void init() {
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverclassname");
String dbURL = config.getInitParameter("dburl");
Class.forName(driverClassName);
Con =DriverManager.getConnection(dbURL,uname,pwd);
}
|
ServletContextà is also called “Application Object” that contains information about the Web application & container. S.Context is used to obtain information about environment on which a servlet is running. There is one instance object of the S.Context interface associated with each Web application deployed into a container. In cases where the container is distributed over many virtual machines, a Web application will have an instance of the S.Context for each JVM.
Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.
Q) Why there is no constructor in servlet?
An init() method that acts as a constructor, an initialization code you need to run should be place in the init(), since it get called when the servlet is first loaded.
Q) Why main() is not written in servlets programs?
Servlet will execute in webcontainer only. Whenever client sends a request the web container will call servlet life cycle methods only to execute our servlet. So even you defined main() method in your servlet there is no wrong but there is no use why because it never execute throughout the servlet life cycle.
Q) Can we use the constructor, instead of init(), to initialize servlet?
Yes, But you will not get the servlet specific things from constructor. init() method creates and loads the servlet. But the servlet instance is first created through the constructor that was done by Servlet container. We cannot write constructors of a servlet class with arguments in servlet (It will throw Exception). So, They provided a init() method that accepts an ServletConfig object as an argument. ServletConfig object supplies a servlet with information about its initialization parameters. Servlet class cannot declare a constructor with ServletConfig object as a argument and cannot access ServletConfig object.
Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor?
No, because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.
Q) Can we write a constructor for servlet?
Yes. But the container will always call the default constructor only. If default constructor is not present , the container will throw an exception
Q) Are Servlets multithread?
Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance.
Q) How do servlets handle multiple simultaneous requests?
The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
Q) Why HttpServlet is declared as abstract?
The default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods doXXX(). If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.
Q) What is the need of super.init (config) in servlets?
Then only we will be able to access the ServletConfig from our servlet. If there is no ServletConfig our servlet will not have any servlet nature.
Q) HttpServletRequest is an interface, how do I get an instance?
The HttpServletRequest interface is implemented by the servlet container. The container instantiates and passes servlet request and response objects to the servlet's service method, which calls doGet or doPost in turn.
Q) Why HttpServlet declared abstract?
The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.
Q) How to add Application scope in Servlets?
In Servlets Application is nothing but ServletContext Scope.
ServletContext context = config.getServletContext();
context.setAttribute(paramName, req.getParameter(paramName));
context.getAttribute(paramName);
Q) Diff Servlet init parameter & Context init parameter?
Servlet init parameters à is for a single servlet only, no body out side that servlet can access that. Method for accessing servlet init parameter is getServletConfig ().getInitParamter (?name?);
Context init parameter à is for the entire web application. Any servlet or JSP in that web application can access context init parameter. Context parameters are declared in a tag <context-param> in web.xml.
Methods for accessing context init parameter is getServletContext ().getInitParamter (?name?) ;
Q) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?
You can bind this information to a context that is accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory.
Q) HttpServletRequest is an interface, how do I get an instance?
This implemented by the servlet container. The container instantiates and passes servlet request and response objects to the servlet's service method, which calls doGet or doPost in turn.
Q) Servlet Attribute Scopes?
There are three scopes Request, Session & Context
Request Attribute Attributes may be set by a servlet to communicate information to another servlet (via RequestDispatcher). Attributes are accessed with the ServletRequest interface methods: getAttribute, getAttributeNames, setAttribute, removeAttribute.
Session Attributes A servlet can bind an object attribute into an HttpSession. Any object bound into a session is available to any other servlet that belongs to the same ServletContext and handles a request identified as being a part of the same session. Methods of the httpsession: getAttribute, getAttributeNames, setAttribute, removeAttribute.
Context Attributes A servlet can bind an object attribute into the context by name. Any attribute bound into a context is available to any other servlet that is part of the same Web application.
Context attributes are LOCAL to the JVM in which they were created. This prevents ServletContext attributes from being a shared memory store in a distributed container. When information needs to be shared between servlets running in a distributed environment, the information should be placed into a session, stored in a database, or set in an Enterprise JavaBeans component.
Q) How can I share data between two different web applications?
Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications.
Q) Diff GET & POST
* GET & POST are used to process request and response of a client.
* GET method is the part of URL, we can send less amount of data through GET. The amount of information limited is 240-255 characters (or 1kb in length).
* Using POST we can send large amount of data through hidden fields.
* Get is to get the posted html data, POST is to post the html data.
Q) Diff Http & Generic Servlet
Http Servlet
|
Generic Servlet
|
HttpServlet class extends Generic servlet , so Generic servlet is parent and HttpServlet is child
|
Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package
|
Http implements all Http protocols
|
Generic servlet will implements all networking protocol
|
Http is stateless protocol, which means each request is independent of previous one. A protocol is said to be stateless if it has no memory of prior connection
|
In generic we cannot maintain the state of next page only main state of current page
|
HttpServlet can override doGet(), doDelete(), doGet(), doPost(), doTrace()
|
Generic servlet will override Service() method only.
|
HttpServlet extra functionality is capable of retrieving Http header information
|
Q) Session Tracking? What is the need of Session Tracking in web application?
Session tracking is the capability of the server to maintain the single client sequential list.
HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is referred as "state". To keep track of this state we need session tracking.
Q) Session Tracking techniques
(i) URL Rewriting (ii) Hidden form Field (iii) Persistence Cookies
(iv) Session Tracking API (v) User Authorization
URL Rewriting is a technique in which the requested URL is modified with the extra data (session id) at the end of URL, every local URL the user might click on is dynamically modified, or rewritten, to include extra information. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies
Ex:- http://server:port/servlet/Rewritten?sessionid=123 added parameter
Hidden form Fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:
<INPUT TYPE=hidden NAME="zip" VALUE="94040">
In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.
Persistence Cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server. A cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per page, 300 for entire application, and they can limit each cookie's size to 4096 bytes.
Sending cookies from a servlet
Cookie cookies = new Cookie ("ID", "123");
res.addCookie (cookies);
A servlet retrieves cookies by calling the getCookies() method of HttpServlet Request:
public Cookie[] HttpServletRequest.getCookies()
This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:
Reading browser cookies from a Servlet
Cookie [] cookies = req. getCookies();
for (int i = 0; i < cookies.length; i++) {
String name = cookies [i]. getName ();
String value = cookies [i]. getValue();
}
Deleting the Cookies
<% Cookie cookie = new Cookie("mycookie", null);
cookie.setMaxAge(0); // set the maximum age of a cookie with the cookie.setMaxAge(int seconds)
response.addCookie(cookie);
%>
* Zero means to delete the cookie
* + value is the maximum number of seconds the cookie will live, before it expires
*- value means the cookie will not be stored beyond this browser session (deleted on browser close)
Session Tracking API
It allows a session object to be created for each user session and values to be stored and retrieved for each session. A session object is created through the HttpServletRequest using the getSession() method:
HttpSession session = request.getSession(true);
This will return the session for this user or create one if one does not already exist. Values can be stored for a user session using the HttpSession method putValue():
session.putValue("valueName", valueObject);
Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames(). Values can also be removed using removeValue(String valueName)
User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.
Q) Session
Session is a persistence network connection between client & server that facilitate the exchange of information between client & server. The container generates a session ID, when you create a session the server saves the session ID on the clients machine as a cookie. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time.
There is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length, which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.
// “True” means check whether already a session is existing for the user. If a session is existing, it will return that session object, otherwise it will create new session object and return that object.
// “False” means check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return “null”.
HttpSession session = req.getSession(true);
session.putValue ("MyIdentifier1", count1); // Storing Value into session Object
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object
Invalidating a Session
There are 6 different ways to invalidate the session.
1 Httpsession.setMaxInactiveIntervel(int sec)
2 Session will automatically expire after a certain time of inactivity
3 User closes browser window, notice that the session will time out rather than directly triggering session invalidate.
4 calling invalidate()
5 if server cashes
6 put <session-timeout> in web.xml
Q) How do you create Http Session that never times out?
Setting a negative value for the max inactive interval for the session:
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(-1);
Q) Cookie advantages & Disadvantages
Advantages Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id.
Disadvantage The biggest problem with cookies is that browser do not always accept cookies. Some times browser does not accept cookies. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. It cannot work if the security level set too high in browser. Cookies are stored in a plain text format so every one can view and modify them. We can put maximum 300 cookies for entire application.
Q) Diff session & cookie?
Session is stored in server but cookie stored in client side. Session should work regardless of the settings on the client browser. There is no limit on the amount of data that can be stored on session. But it is limited in cookie. Session can store objects and cookies can store only strings. Cookies are faster than session.
Q) Advantages of Sessions over Cookies & URLRewriting?
* Sessions are more secure and fast because they are stored at server side. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side.
* Cookies are store at client side so some clients may disable cookies so we may not sure that the cookies which we are maintaining may work or not, if cookies are disable also we can maintain sessions using URLRewriting.
* In URLRewriting we cannot maintain large data because it leads to network traffic and access may be become slow. Sessions will not maintain the data which we have to maintain instead we will maintain only the session id.
Q) If the cookies at client side are disabled then session don't work, in this case how can we proceed?
1. (from servlet) write the next page with a hidden field containing a unique ID that serves as "session ID". So next time when the user clicks submit, you can retrieve the hidden field.
2. If you use applet, you may avoid "view source" (so that people can't see the hidden field). Your applet reads back an ID from the servlet and use that from then on to make further requests
Q) Diff include() & forward() methods?
include()
|
forward()
|
The RequestDispatcher include() method inserts the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.
|
The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
|
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored.
|
The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
|
The include() method is often used to include common text or template that may be included by many servlets.
|
The forward() method is often used where a servlet is taking a controller role, processing some input and deciding the outcome by returning a particular response page.
|
Q) Diff requestDispatcher.forward() & res.sendRedirect()?
forward()
|
sendRedirect(url)
|
This will work at “server side”, this will forward the req & res to another resource that was specified in getRequestDispatcher(String path) , without the client being informed that a different resource is going to process the request.
This process occurs completely with in the web container And then returns to the calling method. Since the client does not know about this forward on the server, no history of it will be stored on the client, so using the back and forward buttons will not work. This method is faster than using sendRedirect as no network round trip to the server and back is required.
|
This will work at “client side”, when ever the request will come it will take the request & build a new request and submit it to the server, when a new request is being submitted all previous parameters stored in the request will be unavailable. The client's history will be updated so the forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains. It cannot forward the http parameters of the previous page. If page1.jsp redirects to page2.jsp, the browser's address bar be updated to show page2.jsp.
|
Q) Diff request.getParameter() & request.getAttribute()?
request.getParameter()
|
request.getAttribute()
|
This will return the value of a parameter that was submitted by an HTML form or that was included in a query string.
|
This is done at server side. You have added the attribute to the request object and submit the request to another resource. When you call rd.forward() the request will be forwarded to the resource specified. Ex:- request.setAttribute(string "key", object "Obj"). In the next page you can get those attributes but passing the string "key" int request.getAttribute("key").
|
Q) ServletContext.getRequestDispatcher()
ServletRequest.getRequestDispatcher()
ServletRequest.getNamedDispatcher()
1) ServletContext.getRequestDispatcher( / ) —> You must use Absolute paths, it can extend outside current servlet context.
2) ServletRequest.getRequestDispatcher(/) —> The path may be Relative, but cannot extend outside current servlet context, the URL in the address bar doesn’t change. The client looses path information when it receives a forwarded request.
3) ServletRequest.getNamedDispatcher(String name) —> “name” is the name of the servlet for which a dispatcher is requested, and is in the web.xml file
Ex:-
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.example.ServletExample</servlet-class>
</servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.example.ServletExample</servlet-class>
</servlet>
RequestDispatcher dispatch = request.getNamedDispatcher(?FirstServlet??);
Q) Different cases for using sendRedirect() vs. getRequestDispatcher() / getNamedDispatcher?
* When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher (or) getNamedDispatcher.
* If you want to dispatch to resources OUTSIDE the context(web application), then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.
Q) Can I catch servlet exception and give my own error message? (or) custom error pages?
Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page.
RequestDispatcher dispatcher = null;
req.getRequestDispatcher(/err/SQL.jsp);
try {
// SQL operation
}
catch (SQLException se) {
dispatcher.forward(request, response);
}
Web.xml
<error-page>
<error-code> HTTP error code (404) <error-code>
<exception-type> java.lang.RuntimeException </exception-type>
<location> /err/RuntimeException.jsp </location>
</error-page>
Q) SingleThread model
Is a tag interface with no methods, in this model no two threads will execute concurrently the service method of the servlet, to accomplish this each thread uses a free servlet instance from the servlet pool. So any servlet implementing this can be considered thread safe and it is not required synchronize access to its variables.
Q) How do I support both GET & POST protocol from the same Servlet?
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}
Q) What happens to System.out & System.err output in a Servlet?
System.out goes to 'client side' and is seen in browser, while System.err goes to 'server side' and is visible in error logs and/or on console.
Q) Why can't Http Session be used instead of Session bean?
HttpSession is used to maintain the state of a client in webservers, which are based on Http protocol. Where as Stateful Session bean is a type of bean, which can also maintain the state of the client in Application servers, based on RMI-IIOP.
Q) What is Temporary Servlet?
When we sent a request to access a JSP, servlet container internally creates a servlet & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use the following command.
Java weblogic.jspc—keepgenerated *.jsp
Q) Servlet chaining
Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest
Servlet Aliasing à allow you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain open your browser and give the alias name in URL.
HttpRequestà construct a URL string and append a comma delimited list of servlets to the end.
Q) Diff CGI & Servlet
* Servlet is thread based but CGI is process based.
* CGI allow separate process for every client request, CGI is platform dependent and servlet is platform independent.
Q) Servlet Listeners
(i) ServletContextListener (I)
void contextDestroyed (ServletContextEvent sce)
void contextInitialized (ServletContextEvent sce)
Implementations of this interface receive notifications about changes to the servlet context of the web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
(ii) ServletContextAttributeListener (I)
void attributeAdded (ServletContextAttributeEvent scab)
void attributeRemoved (ServletContextAttributeEvent scab)
void attributeReplaced (ServletContextAttributeEvent scab)
Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
Q) HttpListeners
(i) HttpSessionListener (I)
public void sessionCreated(HttpSessionEvent event)
public void sessionDestroyed(HttpSessionEvent event)
Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
(ii) HttpSessionActivationListener (I)
public void sessionWillPassivate(HttpSessionEvent se)
public void sessionDidActivate(HttpSessionEvent se)
Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated.
(iii) HttpSessionAttributeListener (I)
public void attributeAdded(HttpSessionBindingEvent se)
public void attributeRemoved(HttpSessionBindingEvent se)
public void attributeReplaced(HttpSessionBindingEvent se)
This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application.
(iv) HttpSession Binding Listener (** If session will expire how to get the values)
Some objects may wish to perform an action when they are bound (or) unbound from a session. For ex, a database connection may begin a transaction when bound to a session and end the transaction when unbound. Any object that implements the javax.servlet.http.HttpSessionBindingListener interface is notified when it is bound (or) unbound from a session. The interface declares two methods, valueBound() and valueUnbound(), that must be implemented:
public void HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)
public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)
valueBound() à method is called when the listener is bound into a session
valueUnbound() à is called when the listener is unbound from a session.
The javax.servlet.http.HttpSessionBindingEvent argument provides access to the name under which the object is being bound (or unbound) with the getName() method:
public String HttpSessionBindingEvent.getName()
The HttpSessionBindingEvent object also provides access to the HttpSession object to which the listener is being bound (or unbound) with getSession() :
public HttpSession HttpSessionBindingEvent.getSession()
=========
public class SessionBindings extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession(true);
session.putValue("bindings.listener", new CustomBindingListener(getServletContext()));
// Add a CustomBindingListener
} }
=============
class CustomBindingListener implements HttpSessionBindingListener {
ServletContext context;
public CustomBindingListener(ServletContext context) {
this.context = context;
}
public void valueBound(HttpSessionBindingEvent event) {
context.log("BOUND as " + event.getName() + " to " + event.getSession().getId());
}
public void valueUnbound(HttpSessionBindingEvent event) {
context.log("UNBOUND as " + event.getName() + " from " + event.getSession().getId());
} }
Q) When a session object gets added / removed to the session, which event will get notified?
HttipSessionBindingListener will get notified, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically
Q) Filter
Filter is an object that intercepts a message between a data source and a data destination, and then filters the data being passed between them. It acts as a guard, preventing undesired information from being transmitted from one point to another.
When a servlet container receives a request for a resource, it checks whether a filter is associated with this resource. If a filter is associated with the resource, the servlet container routes the request to the filter instead of routing it to the resource. The filter, after processing the request, does one of three things:
It generates the response itself and returns it to the client.
It passes on the request (modified or unmodified) to the next filter in the chain
It routes the request to a different resource.
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
MIME-type chain filters Caching filters XSL/T filters that transform XML content
The javax.servlet.Filter interface defines three methods:
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)
public FilterConfig getFilterConfig()
public void setFilterConfig (FilterConfig filterConfig)
Ex:-
public class SimpleFilter implements Filter {
private FilterConfig filterConfig;
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) {
try {
chain.doFilter (request, response); // for Filter Chain
} catch (IOException io) {
} }
public FilterConfig getFilterConfig() {
return this.filterConfig;
}
public void setFilterConfig (FilterConfig filterConfig) {
this.filterConfig = filterConfig;
private FilterConfig filterConfig;
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) {
try {
chain.doFilter (request, response); // for Filter Chain
} catch (IOException io) {
} }
public FilterConfig getFilterConfig() {
return this.filterConfig;
}
public void setFilterConfig (FilterConfig filterConfig) {
this.filterConfig = filterConfig;
} }
Q) How do I load a servlet at start-up? What is preinitialization of a servlet?
Default Container doesnot initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The <load-on-startup> element which can be specified in the deployment descriptor (web.xml) to make the servlet container load and initialize the servlet as soon as it starts up.
Q) Can I call the doPost() method from a hyperlink?
Hyperlink normally creates an HTTP GET request to the given URL, Post requests are normally produced by the submission of an HTML form.
Q) Web.xml (Deployment Descriptor): -
<web-app>
<!-- Defines WebApp initialization parameters.-->
<context-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</context-param>
<!-- Defines filters and specifies filter mapping -->
<filter>
<filter-name>Test Filter</filter-name>
<filter-class>filters.TestFilter</filter-class>
<init-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Test Filter</filter-name>
<servlet-name>TestServlet</servlet-name>
</filter-mapping>
<!-- Defines application events listeners -->
<listener>
<listener-class> listeners.MyServletContextListener </listener-class>
</listener>
<!-- Defines servlets -->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlets.HelloServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
<security-role-ref>
<!-- role-name is used in HttpServletRequest.isUserInRole(String role) method. -->
<role-name>manager</role-name>
<!-- role-link is one of the role-names specified in security-role elements. -->
<role-link>supervisor</role-link>
</security-role-ref>
</servlet>
<!-- Defines servlet mappings -->
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>*.hello</url-pattern>
</servlet-mapping>
<!--specifies session timeout as 30 minutes. -->
<session-config>
<session-timeout>30</session-timeout>
<session-config>
<! -- Error page -- >
<error-page>
<error-code>404</error-code>
<exception-type>java.sql.SQLException</exception-type>
<location>notfoundpage.jsp</location>
</error-page>
<taglib>
<taglib-uri>/examplelib</taglib-uri>
<taglib-location>/WEB-INF/tlds/examplelib.tld</taglib-location>
</taglib>
<load-on-startup>1</load-on-startup>
</web-app>
Q) Diff Server & Container?
Server provides many services to the clients, A server may contain one or more containers such as ejb containers, servlet / jsp container.
Servlet Container is a part of a Web / Application server that provides the network services over which requests and responses are sent.. The main function of the container is to load, initialize and execute servlets.
A container handles large number of requests as it can hold many active servlets, listeners etc. Container and the objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are being handled by the container due to the entrance of more than one thread to an object at a time.
When the servlet is called for the first time, load the servlet class and call its init method (once only). For each request, construct an instance of javax.servlet.ServletRequest and an instance of javax.servlet.ServletResponse. Invoke the servlet's service method, passing the ServletRequest and ServletResponse objects. When the servlet class is shut down, call the servlet's destroy method and unload the servlet class
Q) Diff Multiple Instances of Browser & Multiple Windows? How does this affect Sessions?
* From the current Browser window, if we open a new Window, then it referred to as Multiple Windows. Sessions properties are maintained across all these windows, even though they are operating in multiple windows. * Instead, if we open a new Browser, by either double clicking on the Browser Shortcut then we are creating a new Instance of the Browser. This is referred to as Multiple Instances of Browser. Here each Browser window is considered as different client. So Sessions are “not” maintained across these windows.
Q) Why do you need both GET & POST methods in servlets?
A single servlet can be called from different HTML pages, so different method calls can be possible.
Q) Automatically start Servlet?
If present, calls the servlet's service() method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.
The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use:
<servlet servlet-name='test.HelloWorld'>
<run-at>0:00, 6:00, 12:00, 18:00</run-at>
</servlet>
Q) Retrieving query parameters names?
Enumeration params = request.getParameterNames();
String paramName = null;
String[] paramValues = null;
while (params.hasMoreElements()) {
paramName = (String) params.nextElement();
paramValues = request.getParameterValues(paramName);
System.out.println("\nParameter name is " + paramName);
for (int i = 0; i < paramValues.length; i++) {
System.out.println(", value " + i + " is " + paramValues[i].toString());
} }
String paramName = null;
String[] paramValues = null;
while (params.hasMoreElements()) {
paramName = (String) params.nextElement();
paramValues = request.getParameterValues(paramName);
System.out.println("\nParameter name is " + paramName);
for (int i = 0; i < paramValues.length; i++) {
System.out.println(", value " + i + " is " + paramValues[i].toString());
} }
Q) HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.
Q) Client pull & Server push?
Client pull
Client pull is similar to redirection, with one major difference: the browser actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. It's called client pull because the client is responsible for pulling the content from the next page.
Client pull information is sent to the client using the Refresh HTTP header. This header's value specifies the number of seconds to display the page before pulling the next one, and it optionally includes a URL string that specifies the URL from which to pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh", "3");
And here's a call that tells the client to display Netscape's home page after the three seconds:
setHeader("Refresh", "3; URL=http://home.netscape.com");
Server push
Server push because the server sends, or pushes, a sequence of response pages to the client. With server push, the socket connection between the client and the server remains open until the last page has been sent.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">
Q) How can a servlet refresh automatically if some new data has entered the database?
You can use client side refresh are server push
Q) How many ways we can instantiate a class?
Class.forName().newInstance() and new keyword
Q) Which is faster, servlets or JSP?
JSP documents are compiled into servlets before the servlet container uses them to respond to a request. Once JSP has been compiled, they should be equally fast as standard servlets. The JSP compilation phase introduces a small delay for the first request, but all following requests are handled by the same pre-compiled servlet.
Q) encodeURL & encodeRedirectURL
These are methods of HttpResponse object, “encodeURL” is for normal links inside your HTML pages, “encodeRedirectURL” is for a link your passing to response.sendRedirect().
Q) How can i upload File using a Servlet?
<FORM ENCTYPE="multipart/form-data" method=post action="/utils/FileUploadServlet">
<INPUT TYPE="file" NAME="currentfilename">
<INPUT TYPE="submit" VALUE="upload">
</FORM>
<INPUT TYPE="file" NAME="currentfilename">
<INPUT TYPE="submit" VALUE="upload">
</FORM>
Q) Request Headers
User-agent: - Gives the information about client software, browser name, version and information about the machine on which it is running.
request.getHeader(“user-agent”);
Q) How do i get the name of the currently executing script?
req.getRequestURI() / req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info.
URL
| |
GetRequestURI
|
servlets/HelloServlet/jdata/userinfo
|
GetServletPath
|
servlets/HelloServlet/
|
GetPathInfo
|
/jdata/userinfo
|
GetQueryString
|
pagetype=s3&pagenum=4
|