0% found this document useful (0 votes)
52 views22 pages

JAVA (QuestionBank)

Uploaded by

Sahil Chauahan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views22 pages

JAVA (QuestionBank)

Uploaded by

Sahil Chauahan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of
the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

1) Servlet class is loaded

The classloader is responsible to load the servlet class.

The servlet class is loaded when the first request for the servlet is received by the web
container.
2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class.

The servlet instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance.

The init method is used to initialize the servlet.

It is the life cycle method of the javax.servlet.Servlet interface.

Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException  

4) service method is invoked

The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method. Notice
that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:

public void service(ServletRequest request, ServletResponse response)   
  throws ServletException, IOException  

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:

public void destroy()  
Different between Servlet and jsp

Jsp run slower


Servlet is faster
1 compared to
than jsp
servlet

Servlet is a java JSP is tag based


2
code. approach.
Cookies in Coding of Servlet
Coding of jsp is Servlet
easier than
A cookie is a small 3 is harden than piece of information
Servlet because it
that is persisted jsp. between the
is tag based.
multiple client requests.
In MVC pattern,
A cookie has a In MVC pattern, JSP is used for name, a single
value, and optional 4 Servlet plays a showing output attributes such as a
comment, path and domain qualifiers, a
controller role. data i.e. in MVC it
maximum age, and a version number.
is a view.
JSP will accept
How Cookie works Servlet accept all
5 only http
protocol request.
By default, each protocol request. request is
considered as a In Servlet, In JSP no need to new request. In
cookies technique, we add cookie with
6 aervice() method override service()
response from the servlet. So cookie is
stored in the cache need to override. method. of the browser.
After that if request In Servlet, by is sent by the user,
cookie is added with request by
default session In JSP, session
default. Thus, we recognize the user
as the old user. management is management is
7
not enabled we automatically
need to enable enabled.
explicitly.
Types of Cookie
In Servlet we do In JSP, we have
There are 2 types 8 not have implicit implicit object of cookies in
servlets. object.. support.
In JSP, package
In Servlet, all
imported
package must be
9 anywhere top,
imported on top
middle and
of the servlet.
bottom.
1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

index.html

1. <form action="servlet1" method="post">  
2. Name:<input type="text" name="userName"/><br/>  
3. <input type="submit" value="go"/>  
4. </form>  

FirstServlet.java

1. import java.io.*;  
2. import javax.servlet.*;  
3. import javax.servlet.http.*;  
4.   
5.   
6. public class FirstServlet extends HttpServlet {  
7.   
8.   public void doPost(HttpServletRequest request, HttpServletResponse response){  
9.     try{  
10.   
11.     response.setContentType("text/html");  
12.     PrintWriter out = response.getWriter();  
13.           
14.     String n=request.getParameter("userName");  
15.     out.print("Welcome "+n);  
16.   
17.     Cookie ck=new Cookie("uname",n);//creating cookie object  
18.     response.addCookie(ck);//adding cookie in the response  
19.   
20.     //creating submit button  
21.     out.print("<form action='servlet2'>");  
22.     out.print("<input type='submit' value='go'>");  
23.     out.print("</form>");  
24.           
25.     out.close();  
26.   
27.         }catch(Exception e){System.out.println(e);}  
28.   }  
29. }  

GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service
method.

GenericServlet class can handle any type of request so it is protocol-independent.


You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class


There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time
when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now
there is no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for
the given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters
defined in the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the
servlet log file and a stack trace.

Servlet Example by inheriting the GenericServlet class


Let's see the simple example of servlet by inheriting the GenericServlet class.

It will be better if you learn it after visiting steps to create a servlet.


File: First.java
1. import java.io.*;  
2. import javax.servlet.*;  
3.   
4. public class First extends GenericServlet{  
5. public void service(ServletRequest req,ServletResponse res)  
6. throws IOException,ServletException{  
7.   
8. res.setContentType("text/html");  
9.   
10. PrintWriter out=res.getWriter();  
11. out.print("<html><body>");  
12. out.print("<b>hello generic servlet</b>");  
13. out.print("</body></html>");  
14.   
15. }  
16. }  

Servlet Filter
1. Filter
2. Usage of Filter
3. Advantage of Filter
4. Filter API
1. Filter interface
2. FilterChain interface
3. FilterConfig interface
5. Simple Example of Filter

A filter is an object that is invoked at the preprocessing and postprocessing of a


request.
So maintenance cost will be less.

Usage of Filter

o recording all incoming requests


o logs the IP addresses of the computers from which the requests originate
o conversion
o data compression
o encryption and decryption
o input validation etc.

Advantage of Filter

1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance

Filter API
Like servlet filter have its own API. The javax.servlet package contains the three
interfaces of Filter API.

1. Filter
2. FilterChain
3. FilterConfig

1) Filter interface

For creating any filter, you must implement the Filter interface. Filter interface provides
the life cycle methods for a filter.

Method Description

public void init(FilterConfig config) init() method is invoked only once. It is used t
initialize the filter.

public void doFilter(HttpServletRequest doFilter() method is invoked every time when use
request,HttpServletResponse response, request to any resource, to which the filter i
FilterChain chain) mapped.It is used to perform filtering tasks.

public void destroy() This is invoked only once when filter is taken out o
the service.

2) FilterChain interface

The object of FilterChain is responsible to invoke the next filter or resource in the
chain.This object is passed in the doFilter method of Filter interface.The FilterChain
interface contains only one method:

1. public void doFilter(HttpServletRequest request, HttpServletResponse


response): it passes the control to the next filter or resource.

How to define Filter


We can define filter same as servlet. Let's see the elements of filter and filter-mapping.

1. <web-app>  
2.   
3. <filter>  
4. <filter-name>...</filter-name>  
5. <filter-class>...</filter-class>  
6. </filter>  
7.    
8. <filter-mapping>  
9. <filter-name>...</filter-name>  
10. <url-pattern>...</url-pattern>  
11. </filter-mapping>  
12.   
13. </web-app>  

For mapping filter we can use, either url-pattern or servlet-name. The url-pattern
elements has an advantage over servlet-name element i.e. it can be applied on servlet,
JSP or HTML.

Simple Example of Filter


In this example, we are simply displaying information that filter is invoked automatically
after the post processing of the request.

index.html

1. <a href="servlet1">click here</a>  

MyFilter.java

1. import java.io.IOException;  
2. import java.io.PrintWriter;  
3.   
4. import javax.servlet.*;  
5.   
6. public class MyFilter implements Filter{  
7.   
8. public void init(FilterConfig arg0) throws ServletException {}  
9.       
10. public void doFilter(ServletRequest req, ServletResponse resp,  
11.     FilterChain chain) throws IOException, ServletException {  
12.           
13.     PrintWriter out=resp.getWriter();  
14.     out.print("filter is invoked before");  
15.           
16.     chain.doFilter(req, resp);//sends request to next resource  
17.           
18.     out.print("filter is invoked after");  
19.     }  
20.     public void destroy() {}  
21. }  

HelloServlet.java

1. import java.io.IOException;  
2. import java.io.PrintWriter;  
3.   
4. import javax.servlet.ServletException;  
5. import javax.servlet.http.*;  
6.   
7. public class HelloServlet extends HttpServlet {  
8.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
9.             throws ServletException, IOException {  
10.   
11.         response.setContentType("text/html");  
12.         PrintWriter out = response.getWriter();  
13.       
14.         out.print("<br>welcome to servlet<br>");  
15.           
16.     }  
17.   
18. }  
web.xml
For defining the filter, filter element of web-app must be defined just like servlet.
1. <web-app>  
2.   
3. <servlet>  
4. <servlet-name>s1</servlet-name>  
5. <servlet-class>HelloServlet</servlet-class>  
6. </servlet>  
7.   
8. <servlet-mapping>  
9. <servlet-name>s1</servlet-name>  
10. <url-pattern>/servlet1</url-pattern>  
11. </servlet-mapping>  
12.   
13. <filter>  
14. <filter-name>f1</filter-name>  
15. <filter-class>MyFilter</filter-class>  
16. </filter>  
17.    
18. <filter-mapping>  
19. <filter-name>f1</filter-name>  
20. <url-pattern>/servlet1</url-pattern>  
21. </filter-mapping>  
22.   
23.   
24. </web-app> 

Assignment 2
Q1. What is Servlet

Servlet can be described in many ways, depending on the context.

63.7M
1.3K
OOPs Concepts in Java
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.

Q2. What is jdbc

Java JDBC Tutorial

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,

o Native Driver,

o Network Protocol Driver, and

o Thin Driver

We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces
for JDBC API.

Q3. Deiffernt between browes and server


Web Browser Web Server
It is used for various
It is used for browsing
searches, finds, and
and displaying web
provides documents to the
pages.
browser.
A web browser is used
It is used to store all the
to access the
information and data of the
information stored by
websites.
the webserver.
It makes many queries After viewing the browser
to servers in order to requests, it authorizes them
locate web-based and provides the requested
services and data. content.
The web browser
The web server is a software
serves as a bridge
program or a system that
between the server
manages web applications,
and the client,
generates responses, and
displaying web
accepts input from clients.
content.
A web browser is a
program that searches The web server is used to
the internet for create linkages between
information via websites and web browsers.
websites.
Web servers provide a
Cookies for many
location for storing and
websites are stored in
organizing a website's
the web browser.
pages.

Q1. What is JDBC-ODBC bridge?

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-
ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.

Q8. What are the uses of Connection, Statement and Result set?

JSP Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight
automatically defined variables, sometimes called implicit objects. The available
variables are request, response, out, session, application, config, pageContext,
and page. Details for each are given below.

request
This is the HttpServletRequest associated with the request, and lets you look at the
request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and
the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is
allowed to be a subclass of ServletRequest other than HttpServletRequest, if the
protocol in the request is something other than HTTP. This is almost never done in
practice.

response
This is the HttpServletResponse associated with the response to the client. Note that,
since the output stream (see out below) is buffered, it is legal to set HTTP status codes
and response headers, even though this is not permitted in regular servlets once any
output has been sent to the client.

out
This is the PrintWriter used to send output to the client. However, in order to make
the response object (see the previous section) useful, this is a buffered version
of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn
buffering off, through use of the buffer attribute of the page directive. This was
discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since
JSP expressions automatically get placed in the output stream, and thus rarely need to
refer to out explicitly.

session
This is the HttpSession object associated with the request. Recall that sessions are
created automatically, so this variable is bound even if there was no incoming session
reference. The one exception is if you use the session attribute of the page directive
(see Section 5) to turn sessions off, in which case attempts to reference the session
variable cause errors at the time the JSP page is translated into a servlet.

application
This is the ServletContext as obtained via getServletConfig().getContext().

config
This is the ServletConfig object for this page.
pageContext

JSP introduced a new class called PageContext to encapsulate use of server-


specific features like higher performance JspWriters. The idea is that, if you access
them through this class rather than directly, your code will still run on "regular"
servlet/JSP engines.

page

This is simply a synonym for this, and is not very useful in Java. It was created as a
placeholder for the time when the scripting language could be something other than
Java.

Q8.Write JSP code Structure with the page


directive.
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>  

JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

<%@ page attribute="value" %>  
Attributes of JSP page directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

1)import
The import attribute is used to import
class,interface or all the members of a
package.It is similar to import keyword in
java class or interface.

Example of import attribute


<html>  
1. <body>  
2.   
3. <%@ page import="java.util.Date" %>  
4. Today is: <%= new Date() %>  
5.   
6. </body>  
7. </html>  

2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type
of the HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute


1. <html>  
2. <body>  
3.   
4. <%@ page contentType=application/msword %>  
5. Today is: <%= new java.util.Date() %>  
6.   
7. </body>  
8. </html>  

3)extends

The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.

4)info

This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.

Example of info attribute

1. <html>  
2. <body>  
3.   
4. <%@ page info="composed by Sonoo Jaiswal" %>  
5. Today is: <%= new java.util.Date() %>  
6.   
7. </body>  
8. </html>  

The web container will create a method getServletInfo() in the resulting servlet.For
example:

1. public String getServletInfo() {  
2.   return "composed by Sonoo Jaiswal";   
3. }  

5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the
JSP page.The default size of the buffer is 8Kb.
Example of buffer attribute
1. <html>  
2. <body>  
3.   
4. <%@ page buffer="16kb" %>  
5. Today is: <%= new java.util.Date() %>  
6.   
7. </body>  
8. </html>  

6)language

The language attribute specifies the scripting language used in the JSP page. The
default value is "java".

7)isELIgnored
We can ignore the Expression Language
(EL) in jsp by the isELIgnored attribute.
By default its value is false i.e.
Expression Language is enabled by
default. We see Expression Language
later.

<%@ page isELIgnored="true" %>//Now EL will be ignored  

8)isThreadSafe
Servlet and JSP both are
multithreaded.If you want to control this
behaviour of JSP page, you can use
isThreadSafe attribute of page
directive.The value of isThreadSafe
value is true.If you make it false, the web
container will serialize the multiple
requests, i.e. it will wait until the JSP
finishes responding to a request before
passing another request to it.If you make
the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

1. public class SimplePage_jsp extends HttpJspBase   
2.   implements SingleThreadModel{  
3. .......  
4. }  

9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.

Example of errorPage attribute

1. //index.jsp  
2. <html>  
3. <body>  
4.   
5. <%@ page errorPage="myerrorpage.jsp" %>  
6.   
7.  <%= 100/0 %>  
8.   
9. </body>  
10. </html>  

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.

Example of isErrorPage attribute


1. //myerrorpage.jsp  
2. <html>  
3. <body>  
4.   
5. <%@ page isErrorPage="true" %>  
6.   
7.  Sorry an exception occured!<br/>  
8. The exception is: <%= exception %>  
9.   
10. </body>  
11. </html>  

You might also like