You are on page 1of 42

SERVLET

Q. What is J2EE? Ans.J2EE stands for JAVA 2 ENTERPRICE EDITION. J==>JAVA 2==>Commercial Name EE==>ENTERPRICE EDITION J2EE is the collection of 2 kinds of technology: 1. Component technology 2. Service technology Q. Component Technology? Ans. Component technologies are: Servlet,JSP,EJB Note === Servlet, JSP is the web technologies. EJB is the distributed technology. Q. Service Technology? Ans. Service Technology are: To assist the component technology, 1.JNDI(Java naming & directory interface) 2.JTS and JTA(Java transaction service and Java transaction API) 3.JAVA Mail(Java automatic mail service) 4.JAAS(Java authentication and authorization service) 5.JMS(Java message service) 6.JPA(Java persistent API)

Q. What is Java based Enterprises Application? Ans. An enterprises application is said to be java based, if it is developed using the following: 1.Programming methodology is Object Oriented 2.Coding language JAVA 3.Java based technology(Servlet, JSP) 4)Java Platform

Q. What is the Purpose of J2EE? Ans.J2EE is used to develop java based web enabled enterprises application. eq. Online Banking Application Online Travel Agency MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 1

Q. Give the generalized architecture of enterprises application? Ans. 1.Presentation layer(HTML,JSP) 2.Service layer(bossiness logic==Servlet,i.e Controller) 3.Data Access Layer(JDBC) 4.Data layer(database like oracle)

Q. Give a note of J2EE versions? Ans. J2EE1.2 Servlet2.2,JSP1.1 J2EE1.3 Servlet2.3,JSP1.2 J2EE1.4 Servlet2.4,JSP2.0 J2EE 5 Servlet2.5,JSP2.1 J2EE 6 Servlet3.0,JSP2.2

1999 2001 2003 2006 2009

Q. What is Single Tier Architecture or Standalone? Ans. Those application which required at a time only single user, that comes under the Single Tier Architecture. Eq .windows based application. (Prsentation+Controll Logic + Data ) installed in same machine. pl==VB MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 2

Q. Why do people prefer Single Tier Architecture? Ans. Whenever their is only user working on one application and need only one system . eg. Kirana Shop, Medical shop Q. What is Two Tier Architecture ? Ans. Those application which work in same organization ,that comes under the TWO Tier Architecture. eq. Super Market Applications Q. Why do people prefer Two Tier Architecture? Ans. Whenever their are multiple user working on same application but different-2 machines with in LAN. eq. Super Market, Banking s/w Q. What is Three Tier Architecture or Web based Application or MVC? Ans. Whenever is required to enterprises level application available to all user outside the LAN also. i.e. on the internet, such type of application comes under the 3 tier arch. eq. web application. MVC(MODEL VIEW CONTROLLER) MODEL==DATA BASE(JDBC) VIEW(HTML--(static web page development),JSP-->(dynamic web page development)) CONTROLLER(SERVLET(bussiness logic))

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 3

Q. Supported technology by 1-tier arch? Ans. Only one technology supported. (java or vb or ....,but only one technology for construct the 1-tier arch application). But best technology for 1-tier arch is VB.

Q. Supported technology by 2-tier arch? Ans. It supports 2 technologies. eg. (java(presentation part+ control logic),database) Q. Supported technology by 3-tier arch? Ans. It supports 3 technologies. eg.(java( control logic),html(presentation part),database(model part)).

Q. What is Client? Ans. 1)Client is a networking program, using which we can send and receive the data. Is called Client. 2)It generates the request and send the url to the destination. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 4

eg. Browser Q. What is Server? Ans. Server is the pure networking program ,using which it get the request and generate the response ,i.e. Server. eg.WEB server,DB server etc.

Q. What is Browser? Ans. Browser is a client program using which it can understand only presentation part which is created in html,jsp,php etc. Using browser we can send the data from one place to another place using URL. Q. What is Network? Ans. Network is nothing but it is a set of program which is used to communicate b/w 2 or more machines called N/W. via==>LAN,VAN,MAN Q. What is Web Server? Ans. Those server which is used to receive the request and send the response to browser ,i.e. WEB BROWSER. eq.TOMCAT APPACHE,JBOSS,GLASS FISH etc. Q. Name of DB server? Those server which is used to receive the request and send the response to databse consol,i.e.DB server. eg.oracle,mysql etc. Q .What is Request? Ans. Any data that has been send by the client to server for processing could be called as Request.

Q. What is Response? Ans. Request of the process that has been send from server to client could be called as Response.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 5

Q. What is Port no.? Ans. Logical address on the RAM in which place server program are executing, i.e. Port Number. Q. What is URL? Ans. Stands for UNIFORM RESOURSE LOCATOR which consist the actual address of the location.

Q. What is SERVLET? Ans. 1.SERVLET is the java based web technology from SUN MICRO SYSTEM. 2.SERVLET is a J2EE technology. 3.SERVLET is the specification of WEB CONTAINER(web server) manufacturers. 4.SERVLET(javax.servlet) is an API to develop java based web application. 5.SERVLET uses servlet engine to execute the servlet program. 6.SERVLET is used to develop server side application. 7.SERVLET is the server side piece of code. 8.SERVLET is the dynamic web resource in a java based web application.

Q .Why do we need SERVLET? Ans. TO develop any server side application ,we need to use SERVLET.

Q.javax.servlet.*; Q.javax.servlet.http.*;

Q. What is Servlet interface and its method? Ans. 1)Servlet is the name of interface which is present in "javax.servlet" package which is provide by web server vendors itself. 2)Servlet interface contains 5 method: public void init(javax.servlet.ServletConfig a); public void service(javax.servlet.ServletRequest a,javax.servlet.ServletResponse b); MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 6

public void destroy(); public String getServletInfo(); public javax.servlet.ServletConfig getServletConfig();

Q. What is the life cycle of SERVLET? Ans. There are 3 life cycle method: public void init(ServletConfig a); public void service(ServletRequest a,ServletResponse b) public void destroy();

life cycle method means what: those method which comes under life cycle of the servlet, which are executed automatically by servlet engine,when-ever request send.

1.public void init(ServletConfig a); this method will execute very first only one time, when-ever request first time send. 2.public void service(ServletRequest a,ServletResponse b); this method will execute ,how many number of we send request, those many number of time service method will execute. service method is pure client request handler method.

3.public void destroy(); this method execute in very last only one time whenever servlet engine is shutting down.

Q. Responsibility of the SERVLET program? Ans. 1.CAPTURING THE user input(if required) 2.Interacting with database(if required) 3.processing the data 4.producing the dynamic web page 5.Handling over dynamic page to the web server. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 7

Q. How to develop java web based application? Ans. Java based web application development involves 4 steps: 1.Creating a structure hierarchy of directories. 2.Developing all the web resources of the application. 3.developing deployment descriptor 4.Configuring the Application files 1.Creating a structure hierarchy of directories =============================================== a) We need to create a folder with any name, this folder name becomes the web application name. b)In this root directory we place following files of the application: i)jsps ii)html documents iii)image files iv)web page related file also(java script file,css files)

c)WEB-INF ======== With in the root directory we need to create one folder, ie. "WEB-INF" case sensitive. With in this folder we need to create 3 folder: 1)classes==>mandatory as well as case sensitive 2)lib======>optional but case sensitive 3)src======>optional as well as not case sensitive(for only developer convenience) .all .class files of the application must be placed in "classes" folder. .all the jar files of the application must be placed in "lib" folder. .all the source code files of the application must be placed in "src" folder. .deployment descriptor file(web.xml) is copied into "WEB-INF" directory.

2.Developing all the web resources of the application ===================================================== All the dynamic web resources (servlet,jsp) of the application are to be developed by J2EE professionals.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 8

All the static web resources (html,image,css) of the application are to be developed by web designers.

3.developing deployment descriptor ================================== i)web.xml is known as deployment descriptor. ii)web.xml is only one per web application. iii)web.xml is the java based web application configuration file. iv)web container(WEB SERVER(servlet engine,jsp engine)) uses this file to understand the web application configuration. v)web application developer (J2EE professionals) develop this file and stored into "WEB-INF" folder. following things are performed in this file: 1)Servlet Registration 2)Mapping a client request to a servlet(alias name or public url name) 3)jsp Registration 4)Mapping a client request to a jsp(alias name or public url name) 5)Home page configuration 6)Error page configuration 7)Supply init parameter 8)Supply context parameter 9)Configuring pre-initialization of a servlet 10) Registering the listeners(Servlet) 11)Filter registration 12)Applying Filters to servlet & jsp 13)Tag library registration 14)Specifying the session time out period 15)Configuring the security information. etc

4.Configuring the Application files =================================== Configuring the Application files is nothing but placing appropriate files into appropriate directory.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 9

After that==> We need to start SERVER ,just double click start. bat file

Q. Develop a web application in which, upon client request a servlet display "HELLO WEB APPLICATION" on the server consol. Ans.(APP1) step1 step2 step3 web.xml ======= <web-app>//Root tag <servlet>//child tag <servlet-name>One</servlet-name>//One Servlet registration name <servlet-class>Classfilename</servlet-class> <servlet> <servlet-mapping> <servlet-name>One</servlet-name>//One Servlet registration name <url-pattern>/abc</url-pattern>// /abc is the public url name </servlet-mapping> </web-app>

Q .How many names does a servlet have in a web application. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 10

Ans. A servlet has 3 names in a web application: 1)Registration name 2)class name 3)public url name Note ==== Client request comes to a servlet with public URL name only ==>In this application: registration name of servlet is:"F1" class name="MyServlet" public url name="/abc"

step4 =====to place all the appropriate file to the appropiate directory.

Q. How to verify the whole structure of particular servlet application. Q. What are the System requirement to develop and execute java based web application? Ans. 1.Install J2SE platform(jdk1.5 or above) 2.Install any web container(like TOMCAT APPACHE,JBOSS,GLASH FISH) 3.set classpath of the "servlet-api.jar" file

Q. How to execute "HELLO WEB APPLICATION" of the previous web application. Ans. First of all we need to deploy the web application into web container and then specify the following URL in the browser. start the server and open web browser, and type URL URL==> http://localhost:8081/fapp/abc

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 11

Q. Who will execute Servlet program? Ans. Servlet Engine or Servlet Container. Note === Every web resources(.class files,.html file,.jsp files) have their own URL.

Q. What is web application deployment? and How to deploy the web application into TOMCAT? Ans. Loading the web application into web container(web server) service are available to the web client is known as web application deployment.

There are 2 steps involved in deploying the web application in TOMCAT: 1.to place web project into webapps directory in TOMCAT folder. 2.start the tomcat server(startup.bat file==double click)

Q .Duty of web Server? Ans. 1.To provide connection b/w browser to server using specified URL. 2.If URL bind with html,jsp files then execute by the web server,if URL bind with public URL name(servlet .class file) then,control send to the SERVLET ENGINE.

http://localhost:8081/fapp/A1.html Q. Duty of SERVLET engine with diagram along with internal coding mechanism? Ans. Firstly SERVLET engine get the public URL name(servlet .class file) and check the corresponding servlet registration name, and then get the servlet interface implementing class name ,if it is present in classes folder, then start the execution process, other wise RUN TIME EXCEPTION. start the execution process: 1.Loading the .class from H/d to RAM. 2.Allocate the memory for all static context. 3.if static variable is not initialized then set default value. 4.execute all static block. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 12

5.creating the object of servlet class and assign the reference into variable of type Servlet interface. Servlet s=new MyServlet(); 6.execute the public default constructor. 7.and then execute life cycle method.

Q. How does servlet engine create the of a class automatically? Ans.Class.forName("classfilename").getInstance(); Checked exception: a)java.lang.ClassNotFoundException a)java.lang.InstantiationException c)java.lang.IllegalAccessException

How to Use MyEclips IDE for the development of java based web application. Q.(APP2)Develop a web application in which end-user enters two number into web page and get the sum of two numbers as a response.

Q. What is Request Parameter name? Q. What is Request Parameter value?

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 13

GenericServlet abstract class


Q. What is GenericServlet? Ans. GenericServlet is the name public abstract java class which available I javax.servlet package.

Q. What is limitation of GenericServlet? Ans. GenericServlet cannot give complete functionality required for developing web application. eq. SessionTracking,Cookies,URL Rewriting etc. Q. What is advantage of GenericServlet? Ans. Only provide flexibility for java program and also decrease complexity Because of that we use GenericServlet class. Q. Practical implementation of public class A extends javax.servlet.GenericServlet Q. How to overcome the limitation of GenericServlet? Ans. using javax.servlet.http.HttpServlet class,we overcome SessionTracking,Cookies,URL Rewriting problem.

HttpServlet abstract class


Q. What is javax.servlet.http.HttpServlet? Ans.HttpServlet is the name of public abstract java class which belongs to the javax.servlet.http package. Q. Practical implementation of public class A extends javax.servlet.http.HttpServlet

Q. Inheritence chart of javax.servlet.Servlet interface. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 14

Q.Inheritence chart of javax.servlet.ServletRequest and Inheritence chart of javax.servlet.ServletResponse interface. Ans.

Note ===In case of service() method both request type are allowed ,GET and POST. But in case of doGet() method only GET request type are allow and in case of doPost() method only POST request type are allow. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 15

Q. res.setContentType("mime type"); Ans.The above method call is made on the response object to specify MIME(multi purpose internet mail extension) type. eq. text/html image/gif text/plain etc. eq. res.setContentType(" text/html"); There are 256 mime types. That means after processing the data servlet engine return the html file in the form of text to the web server. Q. explain about void sendRedirect(String url) method. Ans. void sendRedirect(String url),this method belongs to javax.servlet.ServletResponse interface using this method we can set the control from one program to specified URL. use. response.sendRedirect("URL"); Note ==== before execute the sendRedirect() method,servelt engine execute all statement of the method and then finally control move to the specified URL and control will not return in previous method. Q. Develop an web application to use sendRedirect("URL") method. //Send1 in tomcat/webapps folder Q.PrintWriter p=res.getWriter(); Ans. ==>getWriter() is the method of ServletResponse interface which return the object reference of PrintWriter class. ==>using this object reference we can write the data on the browser. ==>PrintWriter object is known as browser stream. Whatever is written into that stream, it transfer to the browser.

Q. Who call doGet/doPost method of the user defined servlet? (internal mechanism) ANS.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 16

Servlet | service(SR SR) | GenericServlet | service(SR,SRes) | HttpServlet | public void service(SR ,Sres) { type casting service(HSrq,HSres); } protected void service(HSrq,HSres) { if(method is GET) {doGet(req,res);} else{doPost(req,res)}} Q. What are the Http request method? Ans. A web client makes the request to the web server into two style 1.GET 2.POST ==>this concept doesn't belong from servlet, belongs to networking(Http protocol). ==>GET and POST methods are known as Http request method. Q. Rule of Http protocol? Ans. POST:(allow only DML(insert,delete,update) operation) GET:(allow only DDL(Select) operation) Q. Develop a web application in which, end user enters account details to be stored into the database.

Q. Develop a web application in which, end user enters empno and then get details from database and display on the browser.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 17

Q.D/f b/w GET and POST?

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 18

ServletConfig interface
Q.Concept of javax.servlet.ServletConfig interface. Ans. 1)ServletConfig is the name of interface which is present in "javax.servlet" package. 2)servlet engine create the object of ServletConfig interface implemented class by encapsulated all data which is configure in "web.xml" file. 3.we can configure the data to a servlet in "web.xml" file with relation of key and value pair.

Q. What are the initialization parameter? Ans. Names(key),value pair of the textual information supplied to servlet during initialization phase as known as initialization parameter(init param). Q. How to supply init parameter to the servlet? Ans. <sevlet> <servlet-name></servlet-name> <servlet-class><servlet-class> <init-param> <param-name>Class</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </init-param> <init-param> <param-name>URL</param-name> <param-value>jdbc:oracle:this:@localhost:1521:orcl</param-value> </init-param>

<init-param> <param-name>UN</param-name> <param-value>scott</param-value> </init-param>

<init-param> <param-name>PW</param-name> <param-value>tiger</param-value> </init-param></sevlet> MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 19

Q. API of javax.servlet.ServletConfig interface. Ans. There are 4 method in ServletConfig interface which have already override in GenericServlet class because of that GenericServlet class impelemnts Servlet interface as well as ServletConfig interface. 1.public String getInitParameter(String init_param_name) ========================================== we can get one data from the web.xml,if name not found in web.xml file then return null. 2.public java.util.Enumeration<String> getInitParameterNames() ============================================== we can get all init param name which is present in web.xml file of current servlet. 3.javax.servlet.ServletContext getServletContext()// ===================================== return object reference of ServletContext interface implemented class.

4.String getServletName()//return registration name of the servlet. =============================================== Q.How to capture init param in a servlet. Ans. 1)String a=sc.getInitParameter("init-param-name"); Or

2) when more than servlet java.util.Enumeration a=sc.getInitParameterNames(); while(a.hashMoreElements()) { Object aa=a.nextElement(); String name=(Object)aa; String value=sc.getInitParameter(name); }

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 20

Q. How may init param in the web.xml. Ans. nth number of init param per servlet.

Q. Why init parameter? Ans. Without changing the source code of servlet,at the different times of its deployment, different value can supplied to servlet using init param concept. eq. DB program example. Q. Develop a web application in which ,init parameter concept is implemented.

Q. Develop the web application balance enquiry services is provided to the END-USER. Q. Why do we use init,service and destroy method? Ans. init==method used for resource allocation service=>used for client request handling destroy==>used for resource de-allocation Q. Overriding magic of init() and init(ServletConfig c) as well as service(SReq,SRes) ans service(HttpSReq,HttpSRes) and getServletConfig() method and discuss complete engg.

GS instance variable ServletConfig s; pv init(SC s) { ........ init(); } pv init(){} Q .Develop a web application that implements user authentication use case. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 21

Servlet chaining
Q. What is Servlet chaining or request dispatching? Ans. A servlet delegating request processing duty to another servlet is known as Servlet chaining or request dispatching. ==>Request dispatching is used to inter-servlet communication. ==>taking one servlet to another servlet. ==>"A concept of forwarding the request of one servlet to another servlet for further processing also called Servlet chaining or request dispatching". diagram ======= bank example

Q. Why do we request dispatching or servlet chaining? Ans. Whenever it is required to process the same request using multiple servlet then we apply the concept of request dispatching or servlet chaining.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 22

Q.How is request dispatching implemented? Ans. step1: Creating object of javax.servlet.RequestDispatcher interface. -->request.setAttribute("name",value);// return type of setAttribute("name",value) is void. -->javax.servlet.RequestDispatcher rd=request.getRequestDispatcher("complete URL of other servlet"); step2: Dispatch the request to other servlet. rs.forward(request,response); or rs.include(request,response); In other servlet receiving: request.getAttribute()// return type of getAttribute("name") is java.lang.Object type. Q .Develop a web application in which ,inter-servlet communication is implemented using forward mechanism of request dispatching. Ans. html=enter basic salary servlet1:calculate GROSS SALARY servlet2:calculate NET SALARY(result) Q.Develop a web application in which ,inter-servlet communication is implemented using include mechanism of request dispatching. Ans. html=enter basic salary servlet1:calculate GROSS SALARY(final result of net salary) servlet2:calculate NET SALARY(result go to servlet1:) Q. Explain about forward/include mechanism, of request dispatching? Ans. forward mechanism ================= => A servlet receive the control from client, perform some portion of processing and delegates the request processing duty to another servlet. =>The other servlet perform remaining portion of the processing ,produce the response page and send to the client(via web server). include mechanism ================= ==>In case of include mechanism of request dispatching, MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 23

..> A servlet receive the control from client, perform some portion of processing and delegates the request processing duty to another servlet. ..>The other servlet perform remaining portion of the processing , and control goes to first servlet. ..>first servlet duty to produce the response page and send to the client(via web server). Q.D/f b/w include and forward mechanism? Ans. forward include 1)forward() is most useful include() is most useful, ,whenever we work in Servlet. whenever we work in JSP. 2)above Q.Diagram Ans. above

Q. What are the different scope of data sharing among servlets of a web application. Ans. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 24

We have three scope for sharing the data in among servlets: 1)request scope(Using javax.servlet.RequestDispatcher interface) 2)Application scope(Using javax.servlet.ServletContext interface) 3)session scope There are four method of "javax.servlet.ServletRequest" interface to deal with data in different scope. 1.public void setAttribute(String key,Object value) =================================================== This method is used to store a data item in any scope(in form of key and value pair). eg. request.setAttribute("gr",3000f); request.setAttribute("connection",con); 2.java.lang.Object getAttribute(String key) ===========================================if key not found in request object then return null., if found return value of corresponding key. eg. Object gr=request.getAttribute("gr"); float a=(Float)gr;//auto-unboxing as well as NRTC.

3.void removeAttribute(String keyname) ===================================== This method is used to remove the data item which have already stored in request scope. eg. request.removeAttribute("gr"); if key name not found, then no error, in this case nothing will remove from request scope.

4.java.util.Enumeration<String> getAttributeNames() ==================================================== This method return all key name which is present in request scope. eg. Enumeration<String> a=request.getAttributeNames(); MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 25

while(a.hasMoreElements()) { Object a1=a.nextElement()//get the key name. }

Q .Why scope concept comes in the picture? Ans. To share the data from one servlet into another servlet.

ServletContext interface
Q.Explain about javax.servlet.ServletContext interface. Ans. 1.ServletContext is the library interface of servlet api. 2.servlet engine implements javax.servlet.ServletContext interface. 3.As soon as the web application is deployed and before any client request Comes ,servlet engine create the object of ServletContext object. 4.ServletContext object is one per application. 5.Every servlet of same application can share this object. 6.Through config object ,we can get the reference of ServletContext. eq. 7.Data is stored in application scope means it is stored & retrieve from ServletContext object only. 8.ServletContext object is destroy whenever application is undeployed. that means server is shutting down. Q. What is the life time of request object and ServletContext object? Ans. Request object is destroy(garbage collected) whenever request-response cycle is completed. ServletContext object is destroy whenever application is undeployed. that means server is shutting down. Q. How many servlet can share the data of request scope? Ans. How many servlet are participating in request dispatching ,all those servlet can only share the data of request scope.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 26

eg. Servlet1----->servlet2 Q. Drawback of request scope.

Servlet3

Q .How many servlet can share the data of application scope? Ans. -->All those servet can share the data of application scope within the same application. -->As all the servlet,share the unique ServletContext object,all servlet of the application share application scope.

Q. What are context parameter? Ans. -->Name,value pair of textual information supplied to the whole application instead of individual servlet,are nothing but Context parameter. -->There parameter can be share any servlet of same application.

Q. How to create context parameter in web.xml file. Ans. <web-app> <context-param> <param-name>ClassLoading</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </context-param> <context-param> <param-name>URL</param-name> <param-value>jdbc:odbc:DSN_NAME</param-value> </context-param>

<context-param> <param-name>UN</param-name> <param-value>scott</param-value> </context-param>

<context-param> <param-name>PW</param-name> MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 27

<param-value>tiger</param-value> </context-param> <servlet> <servlet-name></servlet-name> <servlet-class></servlet-class> </servlet> <servlet-mapping> <servlet-name></servlet-name> <url-pattern></url-pattern> </servlet-mapping> </web-app> -->Servlet engine reads the context param and encapsulate into ServletContext object -->By calling"String getInitParameter(String key)" method of ServletContext interface we can get context param value. --->By calling "Enumeration<String> getInitParameterNames()" method of ServletContext we can get all context param name(key) and using key we can get all the context param value. Q. Develop an application to use context parameter.

Session Tracking =============


Q. What is a Session? Ans. ->Time period b/w user's login and logout with the website is known as USER SESSION/ CLIENT SESSION. -->Session is nothing but it is a object using which we can send the data which are available into one state into another state. -->javax.servlet.http.HttpSession interface object represent a user session/ client session. Q. How many HttpSession object created? Ans. ->one per client. ->per login user, one session object creates. ->one HttpSession object per client/user.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 28

Q. When create=>When request comes to the server, then HttpSession object created. Why =>to send the data from one state to another state. When destroy=>whenever client logout/session time expired then HttpSession object destroy. What does contains HttpSession=>sessionid(jsessionid)

Q. Explain about HTTP? Ans. -->Hyper Text Transfer Protocol is a stateless protocol. It is also known as Connection less protocol. -->A protocol is said to be stateless, if the server doesn't remember the client prior connection. Q. What is stateless; Q. What is statefulness; Q. What is connectionless; Q. Why Session Tracking? Ans. To make end-user's interaction with the website stateful inspite of stateless of HTTP,session tracking is required. Q .What is Session Tracking? Ans. Keeping track of user(client) interaction b/w login and logout with website is nothing but Session Tracking. ==>In Session Tracking 2 things are involved: 1.User(client) identification 2.state management(client data management) Q. How session tracking is implemented? Ans. Step1: getting session object. HttpSession hs=request.getSession(); Step2: state management by using 4 attributes method: (all below method belongs to HttpSession interface) i.e(void setAttribute(String,Object), Object getAttribute(String), void removeAttribute(String), MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 29

Enumeration<String> getAttributeNames()). Step3: Ending the session.

Q. What happens in the background when getSession() method called on the request object. Ans. Following things happens in order: 1.Container evaluate the request object and looks for the incoming sessionid from the client. 2.If sessionid is not found in the client request ,then container create new HttpSession object of the corresponding sessionid is written into the response object .HttpSession object reference is return to the servlet. 3.If sessionid is found in the client request, then container picks up the sessionid from the request and checks for the match in the table that is maintain. Once the match is found ,Container doesnt create the new HttpSession object. Container write the sessionid into response object. Container return already existing HttpSession object reference to the servlet. Q. Develop a web application in which a data item is shared b/w more than one servlet. Q. How is a client session ended? Ans. A client session/user session is ended into two ways: 1)When user explicitly logout(sign out) 2)When session is timed out Note1: ==== -->When user logout explicitly then we need to indicate to the servlet engine (container)to destroy the session allotted for that client. -->By calling the "void invalidate()" method of HttpSession interface object container is programmatically instructed to destroy the session object. Q. Develop a web application in which a log in and logout application.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 30

Note2: ==== -->Container forcibly logging out the client when it is inactive for more than some specified period is known as session expiry or session time out. -->This concept is implemented at server side to manage the resources efficiently. -->Every container have some default session timeout period. ex.TomcatApache(Servlet Engine(container) 30 minutes). -->Default period can be changed into two ways: 1)programmatically(through the servlet program) 2)declaratively (through web.xml) Q. How to change Default period programmatically(through the servlet program)? Ans. By making "void setMaxInactiveInterval(int seconds)" method HttpSession interface object, programmatically session timeout period can be specified to the container. Q. Develop an web application in which implement, How to change Default period programmatically(through the servlet program). Q. How to change Default period declaratively (through web.xml)? Ans. By making the following eatery in "web.xml" declaratively also can be specified: <session-config> <session-timeout>n</session-timeout> </session-config> whenever 'n' is any integer number ,that specify the session timeout period in minutes ,not seconds. Q. Develop an web application in which implement, How to change Default period declaratively (through web.xml)?

Q. Develop a web application in which virtual shopping cart is implement (online shopping functionality).

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 31

COOKIES
Q. What are the Cookies? Ans. -->Cookies is the name ,value pair of the textual information exchange b/w web server and web client(browser). -->Cookies concept is invented by NET SCAPE compony.Net Scape is browser manufactured(development) company. -->Cookies are exchanged b/w server and client using HTTP protocol. Q. How are cookies classified? Ans. Cookies are of two type: 1)Session cookies 2)Persistent cookies Q. What is Session cookies? Ans. Session cookies is not in the file system of the browser. Once browser session ends, session cookies dies at client side, that is as soon as browser is closed, session cookies is lost at the client side. Q. What is Persistent cookies? Ans. Persistent cookies is stored into the file system of client machine by browser it self. Even if browser is closed or system is shutdown, persistent cookies doesn't dies. -->During session tracking implemented using HttpSession,sessionId is exchanged in b/w web server and web browser, as session cookies only. In this case cookies name only is "jsessionid" and cookies value is="session id(any numeric value which is generated by container)" generated by the container for that HttpSession object. HTTP (request header) -------------------------->HttpSession object(name="jsessionid" <-------------------------value="any ") HTTP(response header) -->Cookies is http concept ,Not specially servlet,Cookies is a pure Networking concept. Q. Similarity b/w Session cookies and Persistent cookies? Ans. Both are exchanged in b/w web container and web browser(web client) using Http protocol. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 32

Q.D/f b/w Session cookies and Persistent cookies? Ans. Session cookies Persistent cookies 1)not stored in file system 1)stored in file system 2)once browser is closed ,session 2)if browser is closed and even cookies dies at client side. system is shutdown, persistent cookies not dies, becoz it is stored into file system on the browser machine. 3)It is not persist. 4)Whenever we create the servlet program using HttpSession,then Session cookies automatically apply. 3)it is persist. 4)Whenever we create servlet program using cookie concept, then Persistent cookies will apply.

Q. What are the usage of cookies? Ans. To identify the client uniquely in a series of client-server interaction. Name of cookies always ="jsessionid" Value of cookies(session id)=container generated unique key. -->SessionId travel b/w server and client(browser) as a cookies. -->Any thing coming from browser stored into request object. -->Any thing going to browser stored into response object.

Q. How to implement persistent cookies mechanism in a web application. Ans. STEP 1: create a cookie by by instantiating "javax.servlet.http.Cookie " class . eg. Cookie a=new Cookie(String name,String value);` Cookie a1=new Cookie(String name,String value); many more as per our need.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 33

STEP 2: Make the cookie persistent by calling " void setMaxAge(int seconds) " of cookie object. eg. a.setMaxAge(365*24*3600);//1 year a.setMaxAge(180*24*3600);//6 month STEP 3: Send the cookie to the client by calling " void addCookie()" method on the response object. "void addCookie(Cookie c)" is the name of method which belongs to "javax.servlet.http.HttpServletResponse" method. eg. response.addCookie(a); response.addCookie(a1); STEP 4: Capture the incoming cookie from the client by calling "Cookie[] getCookie()" method on request object. "Cookie[] getCookie()" is the name of method which belongs to "javax.servlet.http.HttpServletRequest" method. Cookie[] a=request.getCookie(); eq. for(int i=0;i<a.length;i++) { String name=a[i].getName(); String value=a[i].getValue(name); } String getName() String getValue(String name) are the methods of Cookies class.

Q. Develop a web application in which implement 'persistent cookies'.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 34

URL REWRITING
Q. What is URL REWRITING? Ans. Appending session-id to the URL is known as URL REWRITING. Q. Why URL REWRITING? Ans. If cookies are disabled at client side, session tracking fails. As alternative solution to that URL REWRITING is implemented. if cookies are disabled, in that case no session id return to the browser by the servelt,we send request again then new brand object created of the HttpSession,in that case previous value hove lost, so we need to implement URL REWRITING. eq.practical. Q. How to implement URL REWRITING? Ans. By calling "String encodeURL(String url)" on the response object. "String encodeURL(String url)" belongs the "javax.servlet.http.HttpServletResponse" interface. Q. How to explicitly blocked or disable the cookies on client side. Ans. Q. Develop a web application in which to implement the concept of URL REWRITING.

Q. Explanation about above application to mentioned that, if we dont use URL REWRITING then what will happens?

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 35

HIDDEN FORM FIELD


Q. What is Hidden Form Field? Ans. Invisible fields on the html form to end-user are known as Hidden Form Fields. -->A hidden form field is created as follows in HTML: <input type="hidden" name="t1" value="10"> Visible Field It can be visible to end-user. and every thing are same. Hidden Field It can be hidden to end-user.

=>A Hidden form fields also has request parameter name and request parameter value. When the form is submitted, this name ,value pair browser submitted to the to the web server and finally they are encapsulated into "request" object. ==>As server side there is no d/f b/w visible fields name, value pair and hidden fields name, value pair. -->There is no special method to capture hidden form field data. -->Bu calling "String getParameter(String fieldname)" on request object, request parameter value of hidden form field is captured in a servlet. Q. Why Hidden form fields? Ans. Hidden form fields are used to exchange the data b/w server and client invisibly. 3 option: 1)storing permanently (DB) 2)session object(session, cookies) 3)Hidden form fields(this is 3rd strategy to transfer the data b/w client and server interaction) Q. Develop a web application in which ,hidden form field concept is implemented.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 36

FILTER
Q. What is the real time example of Filters? Ans.

Q. What is a Filter? Ans. A filter is a container managed public java class whose instantiate intercept the client request to servlet in their request response cycle. Q. What is the need of Filter? Ans. Filter are used for 2 purpose: 1)to assist(mediator) the servlet 2)to monitor(to find out how many time request comes from client side) the servlet. Q. What is fiter chaining? Ans. Applying more than one filter to servlet is known as filter chaining. eq. 1)client----->filter1---->filter2---->servlet1 2)client----->filter1---->servlet1 Q. Give a generalized structure of user define filter. Ans. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 37

A filter is a container managed public java that implement javax.servlet.Filter interface. -->Filter interface has 3 life cycle method; 1)public void init(javax.servlet.FilterConfig a); 2)public void destroy() 3)public void doFilter(ServletRequest res,ServletResponse res, javax.servlet.FilterChain f) javax.servlet.Filter(interface) | |(implements) UserDefineFilter(user define filter) (and override all three method of Filter interface in UserDefineFilter class).

Duty of init method ===================Resource allocation duty Duty of destroy method ===================Resource de-allocation duty Duty of doFilter method =======================code that performs the actual task of a filter. eq. public class MyFilter implements javax.servlet.Filter { public void init(FilterConfig fc) { } public void destroy() { } public void doFilter(ServletRequest r1,ServletResponse r2,javax.servlet.FilterChain fc) { } }

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 38

==>As soon as the web application is deployed(server start) and before any client request come ,all the filters are instantiated and initialized (execute init method of filter) by the container . ==>Filter instance(object) are garbage collected only when web application is undeployed (server is shutdown).Before a filter instance(object) is garbage collected, container calls destroy() method of filter class.

==>A filter is only once(only one time) instantiated,initialized and destroyed. ==>each client request,servlet engine calls doFIlter(SR,SR,FChain),on the filter instance(object).

Q. Explain about FilterConfig interface? Ans. -->javax.servlet.FilterConfig is an interface which is similar to javax.servlet.ServletConfig . -->Servlet engine implements FilterConfig interface itself. -->This interface have 4 method: String getInitParameter(String param_name); Enumeration<String> getInitParameterNames(); String getFilterName() ServletContext getServletContext() -->Servlet engine create the object of javax.servlet.FileterConfig interface during initialization phase(init method execute) of a user define filter and supplies it as argument to init parameter.

Q.Explain about javax.servlet.FilterChain interface? Ans. -->Container implement this interface it self. -->javax.servlet.FilterChain interface has only one method ie.: public void doFilter(ServletRequest r,ServletResponse r2); -->this method s not life cycle method because it doesn't belongs to javax.servlet.Filter interface. -->this method doesn't called by container because this method s not life cycle method. MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 39

-->It should be called explicitly. purpose ========purpose of this method to switch the control to next filter or new servlet etc.If this method is called on chain object then control never goes to the next filter or new servlet etc.

Q.How is a filter applied to a servlet? Ans. step1: register the filter in "web.xml" file <filter> <filter-name>Sn</filter-name> <filter-class>MyFilter</filter-class> </filter> <filter-mapping> <filter-name>Sn</filter-name> <url-pattern>Corresponding servlet url name</url-pattern> </filter-mapping>

Note ===filter "url-pattern" public url name must be same as corresponding servlet public url name. Q. Develop a web application in which implement the concept of filter.

Scenario of One Filter connection to the Servlet


before any client request-->execute init() method of filter. just after first client request comes->execute init() of servlet which is connected to the filter,and then execute doFilter() method filter and then service() method execute of servlet.

second or more client request ->execute doFilter() filter and then execute service() method of servlet.

whenever application is undeployed or server is shutdown then: firstly execute destroy() method of filter and destroy() of servlet.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 40

Scenario of One Filter connection with another Filter to the Servlet


before any client request-->all init of filter top to bottom order just after first client request comes->execute init of servlet which is connected to the filter1 to filter2,and then execute doFilter() method filter1 and then execute doFilter() method filter2 and then service() method execute of servlet.

second or more client request ->execute doFilter() filter1 and then Execute doFilter() filter2 and then service() method execute of servlet.

whenever application is undeployed or server is shutdown then: firstly execute destroy() method of filter1 and then execute destroy() method of filter2 and then destroy() method of servlet.

Q. How many filter we can create in one web application. Ans. nth number filter we can create in one web application. Q. Suppose we have two filter and both must be define in web.xml and both are instantiated as well as both are initialize during deployment time( start the server),then in this case which filter instantiated first and initialized first. Ans. it will work in sequence manner ,which have been already mentioned in web.xml. Q. Can we use init param in filter? Ans. YES then how: web.xml <filter> <filter-name>Sn</filter-name> <filter-class>MyFilter</filter-class> <init-param> <param-name>classloading</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </init-param> </filter> MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in Page 41

<filter-mapping> <filter-name>Sn</filter-name> <url-pattern>Corresponding servlet url name</url-pattern> </filter-mapping>

Q. How to access init param name,value in user define filter? Ans. using FilterConfig object we can use it.

MOHD ARSHAD ALI 9044928839 logon to: www.iuarshad.blogspot.in

Page 42

You might also like