Java Technologies: Biyani's Think Tank
Java Technologies: Biyani's Think Tank
Java Technologies
MCA
Ms Ritu
Revised by: Mr Shiv Kishore Sharma
Deptt. of IT
Biyani Girls College, Jaipur
2
Published by :
Think Tanks
Biyani Group of Colleges
Edition : 2012
While every effort is taken to avoid errors or omissions in this Publication, any mistake or
omission that may have crept in is not intentional. It may be taken note of that neither the
publisher nor the author will be responsible for any damage or loss of any kind arising to
anyone in any manner on account of such errors and omissions.
Preface
I am glad to present this book, especially designed to serve the needs of the
students. The book has been written keeping in mind the general weakness in
understanding the fundamental concepts of the topics. The book is self-explanatory and
adopts the “Teach Yourself” style. It is based on question-answer pattern. The language
of book is quite easy and understandable based on scientific approach.
Any further improvement in the contents of the book by making corrections,
omission and inclusion is keen to be achieved based on suggestions from the readers
for which the author shall be obliged.
I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay Biyani,
Director (Acad.) Biyani Group of Colleges, who are the backbones and main concept
provider and also have been constant source of motivation throughout this endeavour.
They played an active role in coordinating the various stages of this endeavour and
spearheaded the publishing work.
I look forward to receiving valuable suggestions from professors of various
educational institutions, other faculty members and students for improvement of the
quality of the book. The reader may feel free to send in their comments and suggestions
to the under mentioned address.
Author
4
Syllabus
Servlets, JDBC and Inter servlet communications – JDBC, Driver types, JDBC servlet,
JDBC connection pool, inter servlet communication, servlet security and different
packages of JSP and servlets.
2. Unit II : Servlet
2.1 Introduction and life cycle of servlet
2.2 Single-Thread model
2.3 Difference between GET and POST method
2.4 Example of servlet
2.5 Session Tracking
2.6 Example of Session
2.7 Cookies with Example
2.8 Inter-servlet Communication
3. Unit III: Java Database Connectivity
3.1 Introduction
3.2 Steps involved in basic jdbc operation
3.3 Types of jdbc drivers
3.4 Connection Pooling
3.5 Servlet Security
Unit 1
J2EE
MCQ’s
1. Your application supports multiple client types including HTTP clients. Your
business layer is implemented using Enterprise Java Beans. Which of the
following is best suited for maintaining client state?
a. Stateful session beans
b. Entity Beans
c. HttpSession attributes
d. Cookies
e. URL Rewriting
Correct answer: a
2. Which enterprise bean type is defined without any client view interfaces?
a. BMP Entity bean
b. CMP Entity bean
c. Stateful Session bean
d. Stateless Session bean
e. Message Driven Bean
Correct answer: e
3. Which of the following should NOT be used to share data between servlets in a
distributed web application?
a. Attributes of ServletContext
b. Enterprise Java Beans
c. Attributes of HttpSession
d. Database
Correct answer: a
8
4. You want to use URL rewriting to support client browsers, which do not use
cookies. Which method will you use to attach the session id to a URL that is to be
used for the sendRedirect() method of the HttpServletResponse?
a. encodeURL
b. encodeRedirectURL
c. encodeSessionURL
d. encodeSessionRedirectURL
e. None of these
Correct answer: b
7. Which of these packaging options of enterprise beans are recommended for most
J2EE applications?
a. Package each enterprise bean for an application in its own EJB module
b. Package all enterprise beans for an application in one EJB module
c. Package all related enterprise beans for an application in one EJB module
d. None of These
Correct answer: c
Java Enterprise
Java Technologies 9
JJA
AVVA
A EEN
NTTEER
RPPR
RIISSEE
Client tier: In this tier Servlets and JavaServer Pages (JSPs), or standalone Java
applications provide a dynamic interface to the middle tier.
10
Middle tier:, In this tier enterprise beans and Web Services encapsulate reusable,
distributable business logic for the application.
Enterprise data tier: In the data tier, the enterprise's data is stored and persisted,
typically in a relational database.
Java Technologies 11
Unit 2
Servlets
MCQ’s
1. If the HTTP error 500 is generated by your servlet, you do not want to show the
"Internal Server Error" page to the client. Instead, you want a custom error page
to be displayed. What is the best way to accomplish this?
a. Forward the user to the error page using
HttpServletResponse.sendRedirect method.
b. Forward the user to the error page using RequestDispatcher.forward
method.
c. Specify the mapping of the error-code 500 and the error page in the
deployment descriptor.
d. It is not possible to accomplish this.
Correct answer: c
2. A servlet needs to acquire a data source through a JNDI naming lookup. Which
of the following is the best place to do this?
a. Constructor
b. init method
c. service method
d. doGet method
e. doPost metho
Correct answer: b
d. Servlets can handle only a single request, where as Applet can handle multiple
requests
Correct answer: a and b
5. Which method is used to specify before any lines that uses the PintWriter?
a. setPageType()
b. setContextType()
c. setContentType()
d. setResponseType()
Correct answer: c
13. The init parameter name and value pairs that are defined in web.xml file are
handled by
a. ServletConfig object
b. ServletContext object
c. ServletRequest object
d. ServletResponse object
Correct answer: a
14. How many ServletContext objects are available for an entire web application?
a. One each per servlet
b. One each per request
c. One each per response
d. Only one
Correct answer: d
• Initialization
1. Loading and Instantiation: 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.
2. Initialization: After creating the instances, the servlet container calls the init(
) method and passes the servlet initialization parameters to the init( ) method.
3. Servicing the 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.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any
request, the servlet container calls the destroy() method .
16
In POST method
- data is submitted as a part of http request
- data is not visible in the url
- it is more secure but slower as compared to GET
Java Technologies 17
When multiple clients make continuous request the server cannot identify from
which client it is getting requests.For this purpose session is used.
Because HTTP is a stateless protocol.When there is a need to maintain the
conversational state, session tracking is needed.
1. User authorization
2. Hidden fields
18
3. URL rewriting
4. Cookies
5. Session tracking API
1. User Authorization
The user has username and password to login to the application. Based on that the
user can be identified and the session can be maintained.
2. Hidden Fields
<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be
sent to the server for session tracking.
3. URL Rewriting
Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url.
4. Cookies
Cookie is a key value pair of information, sent by the server to the browser.
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value);
}
}
}
Output:
Session ID: D91A214517E7F08C01A755737D170F41
Created: Wed Jul 04 10:07:34 CEST 2012
Last Accessed: Wed Jul 04 10:19:54 CEST 2012
Example:
Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);
Example of Cookie:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UseCookies extends HttpServlet
out.println("<HTML><HEAD><TITLE>");
out.println(" Use of cookie in servlet");
out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
out.println(" <b>This is a Cookie example</b>");
out.println("</BODY></HTML>");
out.close();
}
}
Output:
Request Dispatching
HTTP Redirect
Servlet Chaining
HTTP request (using sockets or the URLConnection class)
Shared session, request, or application objects (beans)
Direct method invocation (deprecated)
Shared static or instance variables (deprecated)
1.HTTP Authentication:
The HTTP protocol provides built-in authentication support--called basic
authentication--based on a simple challenge/response, username/password
model
2.Digital Certificates:
A simple servlet that tells the client its name and what kind of authentication has
been performed (basic, digest, or some alternative).
Methods:
getRemoteUser()
getAuthType()
Unit 3
JDBC
MCQ’s
1. The JDBC-ODBC Bridge supports multiple concurrent open statements per
connection?
a. True
b. False
Correct answer: a
2. Which driver is efficient and always preferable for using JDBC applications?
a. Type – 4
b. Type – 1
c. Type – 3
d. Type – 2
Correct answer: a
3. JDBC facilitates to store the java objects by using which of the methods of
PreparedStatement
1. setObject () 2. setBlob() 3. setClob()
a. 1, 2
b. 1,2,3
c. 1,3
d. 2,3
Correct answer: b
5. All raw data types (including binary documents or images) should be read and
uploaded to the database as an array of
a. byte
b. int
c. boolean
d. char
Correct answer: a
7. Which of the following methods finds the maximum number of connections that
a specific driver can obtain?
a. Database.getMaxConnections
b. Connection.getMaxConnections
c. DatabaseMetaData.getMaxConnections
d. ResultSetMetaData.getMaxConnections
Correct answer: c
JDBC
JDBC concepts:
Statement: An SQL Statement to perform a query or update operation
Metadata: Information about returned data, the database and the driver
26
Pure Java drivers that communicate directly with the vendor‟s database
JDBC commands converted to database engine‟s native protocol directly
Advantage: no additional translation or middleware layer
Improves performance
Unit 4
Java 2 Micro Edition(J2ME)
MCQ’s
1. All MIDP implementations are required to support what image format?
a. GIF
b. JPG
c. BMP
d. PNG
Correct answer: d
5. Which of the following techniques can be used for wireless session tracking?
a. Cookies
b. URL Rewriting
c. Hidden Fields
d. None of the above
Correct answer: b
6. Which one of the following methods of the MIDlet abstract class must be
implemented by a midlet?
a. initApp, startApp
b. startApp, destroyApp
c. initApp, startApp, pauseApp, destroyApp
d. startApp, pauseApp, destroyApp
Correct answer: d
8. Which class would you use to write applications to access low-level input events
or to issue graphics calls for drawing to the display?
a. Wrong
b. Display
c. Command
d. Screen
e. None of these
Correct answer: d
9. The MIDP user interface API is a subset of the AWT/ Project Swing libraries?
a. False
b. True
Correct answer: a
10. A Java virtual machine1 (JVM) supporting CLDC has no support for:
32
MIDP (TopMost Layer): Which contains Java APIs for user network connections,
persistence storage, and the user interface. It also has access to CLDC libraries
and MIDP libraries.
J2ME API’s(Profiles): Which consists of the minimum set of application
programming interfaces for the small computing device
Configurations: Which handles interactions between the profile and the JVM.
JVM
Operating System(Bottom Layer).
Java Technologies 33
J2ME Architecture
startApp(): called by the application manager when the MIDlet is started and
contains statements that are executed each time the application begins execution.
Public and have no return value nor parameter list.
34
pauseApp(): called before the application manager temporarily stops the MIDlet.
The application manager restarts the MIDlet by recalling the startApp() method.
Public and have no return value nor parameter list.
destroyApp(): called prior to the termination of the MIDlet by the application
manager. Public method without a return value. It has a boolean parameter that
is set to true if the termination of the MIDlet is unconditional, and false if the
MIDlet can throw a MIDletStateChangeException.
1. Alert
Alerts are best used in informational or error messages that stay on the screen for a
short period of time and then disappear.
2. List
A list contains one or more choices (elements), which must have a text part, an
optional image part, and an optional font for the text part.
3. TextBox
TextBox is a screen‟s object, using which we can give input and modify the text.
4. Form
Forms used to combine multiple components into one screen. It is a screen that
contains items.
1. Canvas
2. Graphics
Command Types
NAME MEANING
OK Confirms a selection.
3. You can create a command with a short and long label like this:
Example:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Commander extends MIDlet
{
public void startApp()
{
Displayable d = new TextBox("TextBox", "Commander", 20, TextField.ANY);
Command c = new Command("Exit", Command.EXIT, 0);
d.addCommand(c);
d.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
});
Display.getDisplay(this).setCurrent(d);
}
Constructor :
Ticker(String str):- This is used to Constructs a new Ticker object, given its initial
contents string.
Two methods:
getString():- This is the String type methods which Gets the string currently
being scrolled by the ticker.
setString(String str):- This is the void type, it Sets the string to be displayed by
this ticker.
Methods:
Example:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TextBoxMIDlet extends MIDlet{
private Display display;
public TextBoxMIDlet()
{
display = Display.getDisplay(this);
}
public void startApp()
{
TextBox t = new TextBox("TextBox Example",
It have a text part, an optional image part, and an optional font for the text part.
EXCLUSIVE
IMPLICIT
MULTIPLE
Example:
40
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ExclusiveChoiceList extends MIDlet{
private Display display;
private List list;
public ExclusiveChoiceList()
{
list = new List("Movies", Choice.EXCLUSIVE);
}
{
display = Display.getDisplay(this);
list.append("The Legend of Bhagat Singh", null);
list.append("Mother India", null);
list.append("Lagaan", null);
list.append("Chak De..", null);
list.append("Hum Aapke Hain Kaun", null);
display.setCurrent(list);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
}
Example:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class AppendItem extends MIDlet{
private Display display;
private MIDlet midlet;
public void startApp()
{
Form form = new MyForm("MY FORM");
display = Display.getDisplay(this);
display.setCurrent(form);
}
Unit 5
Java Server Pages
MCQ’s
9. The listener is notified when the Servlet context (i.e., the Web application) is
initialized and destroyed ?
a. Servlet context attribute
b. Servlet context listeners
c. Session Attribute
d. Session Listeners
44
Correct answer: b
10. The < % return; % > simply aborts the processing of JSP?
a. true
b. false
c. can't say
d. none of the above
Correct answer: a
Architecture:
Java Technologies 45
Steps:
The user goes to a web site made using JSP. The user goes to a JSP page (ending
with .jsp). The web browser makes the request via the Internet.
The JSP request gets sent to the Web server.
The Web server recognises that the file required is special (.jsp),therefore passes
the JSP file to the JSP Servlet Engine.
If the JSP file has been called the first time,the JSP file is parsed,otherwise go to
step 7.
The next step is to generate a special Servlet from the JSP file. All the HTML
required is converted to println statements.
The Servlet source code is compiled into a class.
The Servlet is instantiated,calling the init and service methods.
HTML from the Servlet output is sent via the Internet.
HTML results are displayed on the user's web browser.
Application: These objects has an application scope. These objects are available at the
widest context level, that allows to share the same information between
the JSP page's servlet and any Web components with in the same
application.
Out: This object allows us to access the servlet's output stream and has a page
scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides
the output stream that enable access to the servlet's output stream.
Page: This object has a page scope and is an instance of the JSP page's servlet
class that processes the current request. Page object represents the current
page that is used to call the methods defined by the translated servlet class.
First type cast the servlet before accessing any method of the servlet through
the page.
Pagecontext: PageContext has a page scope. Pagecontext is the context for the
JSP page itself that provides a single API to manage the various scoped
attributes. This API is extensively used if we are implementing JSP custom
tag handlers. PageContext also provides access to several page attributes like
including some static or dynamic resource.
Request: Request object has a request scope that is used to access the HTTP
request data, and also provides a context to associate the request-specific
data. Request object implements javax.servlet.ServletRequest interface. It uses
the getParameter() method to access the request parameter. The container
passes this object to the _jspService() method.
Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object. Response object is an instance of the
classes that implements the javax.servlet.ServletResponse class. Container
generates to this object and passes to the _jspService() method as a parameter
.
Session: Session object has a session scope that is an instance of
javax.servlet.http.HttpSession class. Perhaps it is the most commonly used
object to manage the state contexts. This object persist information across
multiple user connection.
<jsp:include> Includes the response from a servlet or JSP page during the
request processing phase
<jsp:forward> Forwards the processing of a request to servlet or JSP page
</body>
</html>
2) errorPage.jsp
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<body>
<h2>Error Encountered!</h2>
<font color="red"><%= exception %> has been encountered. You haven't specify
any String.</font>
</body>
</html>
Java Technologies 49
Keywords
J2EE: Java Enterprise uses a component based approach for Design,
Development,Assembly and Deployment of the enterprise application.
Servlet: Servlets are small java programs used to design the web applications.
JDBC: JDBC is Java application programming interface that allows the Java
programmers to access database management system from Java code.
session: A Session refers to all the request that a single client makes to a server.
A session is specific to the user and for each user a new session is created to
track all the request from that user.
cookies: Cookies are small bits of textual information that a Web server sends
to a browser and that the browser returns unchanged when visiting the same
Web site or domain later.
Implicit objects: Implicit objects are created automatically by the container and
are accessed using standard variables.
Standard Actions: JSP Standard action are predefined tags that are required at
the exact time the JSP page is requested by a browser.
J2ME:J2ME is used to develop tiny devices .Example: mobile phones, TV set top
boxes, Vehicle telematics, pagers, PDAs etc.
Out: This object allows us to access the servlet's output stream and has a page
scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the
output stream that enable access to the servlet's output stream.
Page: This object has a page scope and is an instance of the JSP page's servlet
class that processes the current request. Page object represents the current page
that is used to call the methods defined by the translated servlet class
Pagecontext: PageContext has a page scope. Pagecontext is the context for the
JSP page itself that provides a single API to manage the various scoped
attributes.
Java Technologies 51
Request: Request object has a request scope that is used to access the HTTP
request data, and also provides a context to associate the request-specific data.
Request object implements javax.servlet.ServletRequest interface. It uses the
getParameter() method to access the request parameter. The container passes this
object to the _jspService() method.
Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object. Response object is an instance of the classes
that implements the javax.servlet.ServletResponse class. Container generates to
this object and passes to the jspService() method as a parameter.
Ticker: It used for scrolling text across the top of the display.
52
Bibliography
Harvey M. Deitel, Paul J. Deitel, Sean Santry: Advanced Java 2 Platform: How
to Program