0% found this document useful (0 votes)
28 views10 pages

Jee Q Ans Unit I

Uploaded by

riaz ahamed
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)
28 views10 pages

Jee Q Ans Unit I

Uploaded by

riaz ahamed
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/ 10

UNIT I

SECTION-A (2 MARKS)

1. What is Servlet?
Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.

2. What is a cookie?
A cookie is stored on a client and contains state information. Cookies are valuable
for tracking user activities.

3. Define Servlet Chaining.


Servlet Chaining means the output of one servlet act as an input to another servlet.
The output from first Servlet is sent as input to other Servlet and so on. The Output
from the last Servlet is sent back to the browser. The entire process is called Servlet
Chaining.

5. What is a Session?
A web container provides a common storage area called as session to store the state
and provides access to this session to all the servlets within the web application. For
instance, servlet A can create some state (information) and store it in the session.
Servlet B can then get hold of the session and read the state.

6. Abbreviate and define JDBC.


JDBC is an acronym for Java Database Connectivity. It is an application
programming interface (JDBC API) that defines a set of standard operations for
interacting with relational database management systems (DBMSs).

7. List the attributes in a <form> tag.


A <FORM> tag has important attributes such as action and method. The action
attribute contains the uniform resource locator (URL) of the server program to which
the browser should send the user’s input. The method attribute tells the browser
how to send the data; this attribute is usually either Get or Post.

8. Define SSI.
Server-Side Includes is a mechanism that helps developers insert dynamic content
into HTML files without requiring knowledge of the server or client-side
programming language specification.
SECTION-B (5 MARKS)

1. Discuss the life cycle methods of a servlet.


Three methods are central to the life cycle of a servlet. These are init( ), service( ), and
destroy( ). They are implemented by every servlet and are invoked at specific times
by the server.

init() method: The server invokes the init( ) method of the servlet. This method is
invoked only when the servlet is first loaded into memory. It is possible to pass
initialization parameters to the servlet so it may configure itself.

service() method: The server invokes the service( ) method to process the HTTP
request.It may also formulate an HTTP response for the client.The service( ) method
is called for each HTTP request.

destroy() method: The server calls the destroy( ) method to relinquish any resources
such as file handles that are allocated for the servlet.

2. Briefly explain how the Session is managed in servlet?


A web container provides a common storage area called as session to store the state
and provides access to this session to all the servlets within the web application. For
instance, servlet A can create some state (information) and store it in the session.
Servlet B can then get hold of the session and read the state.

Since the state (data or information) in the session is user specific, the web container
maintains a separate session for each and every user.

.
A servlet can do the following four most important operations to work with sessions.

Create the session


Store the data in the session
Read the data from the session
Destroy the session or invalidate the session.

Creating a Session
The servlet API provides a class called HttpSession to work with sessions. To create a
session, the following session object is created:

HttpSession session = request.getSession(true);

Storing the data in Session


Data in session is stored as key-value pair just like in HashMap or Hashtable. To store
the data we use the setAttribute() method as shown below:

session.setAttribute(“price”,new Double(“12.45”));

Reading the data from the Session


To read the data, we need to use the getAttribute() method by passing in the key as
shown below which then returns the value object:

Double d = (Double)session.getAttribute(“price”);

Destroying the Session


A session is usually destroyed by the last page or servlet in the web application. A
session is destroyed by invoking the invalidate() method as shown below:

session.invalidate();

3. Mention the driver types of JDBC in brief.


JDBC Drivers Types: JDBC driver implementations vary because of the wide variety of
operating systems and hardware platforms in which Java operates.
Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4.

Type 1: JDBC-ODBC Bridge Driver:


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine.
4.

Type 2: JDBC-Native API:


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors
and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver
must be installed on each client machine.

5.
Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to access databases. The
JDBC clients use standard network sockets to communicate with a
middleware application server. The socket information is then translated
by the middleware application server into the call format required by the
DBMS, and forwarded to the database server.
Type 4: 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with
the vendor's database through socket connection. This is the highest
performance driver available for the database and is usually provided by
the vendor itself.
4. Discuss the Applet-Servlet Communication.

Applet-servlet communication
Applets can connect to a remote computer either by using socket or RMI programming,
but still there is an easier way—HTTP tunneling, which is a way of creating a sub
protocol for specific tasks on top of the existing protocol (HTTP). With the help of the
HTTP protocol, applets can establish a communication channel with servlets and send
and receive any text and binary objects using Java Serialization.

An applet can collect the user’s input from the GUI components, package the data in a
serializable object, and send the data to the servlet.

To receive data from a servlet, the applet has to play the role of a Web browser. It has
to understand the data it receives and populate the appropriate GUI components

The java.net.URLConnection and java.net.URL classes are used to open a standard


HTTP connection and "tunnel" to the web server.

The server then passes this information to the servlet in the normal way. Basically, the
applet pretends to be a web browser, and the servlet doesn't know the difference.
As far as the servlet is concerned, the applet is just another HTTP client.

The URLConnection contains both an input and an output stream. These streams can
be used by the applet to transmit data to the servlet and receive data back from it.

Example:
Apps.java
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.*;
/*<applet code="Apps" width=400 height=460>
</applet>*/
public class Apps extends Applet implements
ActionListener
{
Button b;
TextField tf;
public void init()
{
b=new Button("call Servlet");
b.addActionListener(this);
add(b);tf=new TextField(25);
add(tf);
}
public void actionPerformed(ActionEvent ae)
{
try
{
URL u=new URL("http://localhost:8080/WebApplication11/Serv");
URLConnection urlc=u.openConnection();
InputStream isr=urlc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(isr));
tf.setText(br.readLine());
}
catch (Exception e)
{
showStatus(e.toString());
}
}
}
Serv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
Date d=new Date();
PrintWriter out=res.getWriter();
out.println(d.toString());
}
}
SECTION-C (10 MARKS)
1. Discuss Servlet API in detail.

Servlet API or Servlet Architecture

Two packages contain the classes and interfaces that are required to build servlets.
These are javax.servlet and javax.servlet.http. They constitute the Servlet API.
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.

Interface Description

Servlet Declares life cycle methods for a servlet.

ServletRequest Used to read data from a client request.

ServletResponse Used to write data to a client response.

GenericServlet Implements the Servlet and ServletConfig interfaces.

The javax.servlet.http package contains a number of interfaces and classes that establish
the framework in which servlets operate.

Class/Interface Description

HttpServlet The base class that represents a HTTP Servlet

HttpServletRequest The class that encapsulates all the HTTP request details

The class used for sending HTTP response back to the


HttpServletResponse
browser.

ServletConfig Class used for dynamically initializing the servlet

HttpSession Class used for session management

Class used by the servlet to dispatch the request to


RequestDispatcher
various resources.
Example Program: A simple servlet that displays a greeting
package myservlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<h1>Welcome to Servlets </h1>");
}
}

2. Explain in detail the steps used to access a database with JDBC.

The steps used to access a database with JDBC can be described in six steps.

i) Load the JDBC driver for the DBMS


ii) To connect to the database;
iii) To create a statement
iv) To query the database using SQL Select statements;
v) To insert/delete/update data in the database.
vi) Close all the resources, including ResultSet, Statement, and Connection, which should
be the last step of using JDBC.

Step 1: Load the JDBC drivers


A Java program can load several JDBC drivers at time. This allows the program to
interact with more one database running under different DBMSs. The following line of
code loads the JDBC driver for PostgreSQL,

Class.forName ("org.postgresql.Driver");

Step 2: Connect to the database


A connection to a database can be established via the getConnection method of
the DriverManager class. The getConnection method accepts three parameters -- the
database, user name, and password.
Connection db = DriverManager.getConnection(url+dbname, usernm, passwd);

Here, the url variable contains which JDBC driver is to used for this connection and also
which machine, by IP address, hosts the DBMS and the database.

Step 3: Create a statement


A Statement object has the ability to parse SQL statements, send the SQL statements to
the DBMS, and accept the results returned from the DBMS.
Statement st = db.createStatement();

Step 4 and 5: Interact with the database


Normally, two operations of Statement are needed to interact with a database. One
is executeQuery(sql_select), which takes a SQL Select statement as its argument, sends
the Select to the DBMS, and returns the results as an object of ResultSet. The other
operation is executeUpdate(sql_insert_delete_update), which takes a SQL statement
(Insert, Delete, or Update), sends it to the DBMS. Both operations throw
a SQLException if the statement cannot be executed by the DBMS successfully.

String sql = "SELECT name, title " + "FROM faculty f, course c " + "WHERE f.id =
c.instructor";
ResultSet rs = st.executeQuery(sql);
String faculty = '123456';
String sql = "INSERT INTO faculty VALUES (" + '" + faculty +
"', 'Dave Letterman', 'Estate 1942', '941-6108')";
st.executeUpdate(sql);

Step 6: Disconnect from the database


When the application completes or no further database interaction is needed, you
should return JDBC resources back to the system, which include, objects of Statement,
ResultSet, and Connection.

rs.close();
st.close();

You might also like