JDBC (Java Database Connectivity) provides a standard interface for connecting Java applications to different database systems. There are four main types of JDBC drivers:
1. JDBC-ODBC bridge driver - Used to connect to any ODBC compliant database. It is platform dependent.
2. Native-API (partially Java) driver - Uses a database vendor's native API. Faster than JDBC-ODBC but still platform dependent.
3. Network protocol driver - Uses a database-independent protocol like ODBC or SQL/CLI. Platform independent but not as fast as native.
4. Pure Java driver - Written entirely in Java. Fastest,
2. 2
1.What is BASIC Authentication? Explain with example.
An authentication protocol defined within the HTTP protocol, which allows user to
make request, browser sends a dialog box to ask username and password and verified by server. In
this, user is not
allowed to change the look and fe el of the dialog box. User entries are maintained in web.xml file.
Example:
When you start Apache Tomcat, it asks for username and password. This server uses HTTP Basic
authentication for authenticating users.
Following are the steps for implementing HTTP Basic Authentication:
1. Add username and password with their roles in tomcat-users.xml file. This is available in
“conf” folder of Tomcat installation folder.
2. Create a Servlet class.
3. Deploy this Servlet and provide necessary constraints in Web.xml.
for example : Tomcat 6.0conftomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="Administrator"/>
<role rolename="Guest"/>
<user username="Yash" password="MyPune" roles="Administrator,
Guest"/>
<user username="Sweety" password="IAMSWEETY" roles="Guest"/>
</tomcat-users>
Create a Servlet class
Save following source code in BasicAuthority.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BasicAuthority extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
3. 3
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Wel-come ......!");
out.println("You are authorized by server....");
}
}
Deploying Web Application in Deployment Descriptor (DD)
<?xml version="1.0" encoding="ISO-8859-1"?>
<Web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/Web-app_2_4.xsd" ersion="2.4">
<servlet>
<servlet-name>secret</servlet-name>
<servlet-class>BasicAuthority</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>secret</servlet-name>
<url-pattern>/BasicAuthority</url-pattern>
</servlet-mapping>
<!- - Security Constraints are defined here -->
<security-constraint>
<Web-resource-collection>
<Web-resource-name>Basic-Authority</Web-esource-name>
<url-pattern>/BasicAuthority</url-pattern>
<url-pattern>/secret</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</Web-resource-collection>
<auth-constraint>
<role-name>Administrator</role-name>
</auth-constraint>
4. 4
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>
http://localhost:8080/Sample/BasicAuthority
</realm-name>
</login-config>
<security-role>
<role-name>Administrator</role-name>
</security-role>
</Web-app>
When you request for an application, the server finds the role defined in DD and check that
with the role defined is “tomcat-users.xml”.
The following <login-config> tag defines which method of authentication is used (BASIC, FORM,
DIGEST or CLIENT-CERT)
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>
http://localhost:8080/Sample/BasicAuthority
</realm-name>
</login-config>
Following line of code gives security constraints to the mentioned URL-pattern like which HTTP
methods are allowed. Here only GET and POST are allowed. Other methods like, HEAD, PUT,
DELETE etc., are not allowed.
<security-constraint>
<Web-resource-collection>
<Web-resource-name>Basic-Authority</Web-resource-name>
<url-pattern>/BasicAuthority</url-pattern>
<url-pattern>/secret</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</Web-resource-collection>
<auth-constraint>
<role-name>Administrator</role-name>
5. 5
</auth-constraint>
</security-constraint>
In <url-pattern> you can declare different URLs, which represent a single Web application or
multiple Web applications. The <auth-constraint> specifies abstract roles that should have access to
the given URLs. Using
auth constraint with no URLs auth-role-name means no direct access is allowed.
Running the Application:
Start Tomcat server and type the following URL to execute the Transaction are set of operations
which must executes all or should be rollback. The setAutoCommit() and rollback() methods are
used to do these tasks
BasicAuthority Servlet:
“http://localhost:8080/Sample/BasicAuthority”
1.Describe the steps needed to establish database connectivity with JDBC.
To make a database connection you need to go through the following
sequence:
i) Load JDBC Driver: Loading the driver can be done by
Class.forName() method. This method takes the driver class of
the respective database in String format.
ii) Open database Connection: You open database connection using
DriverManager.getConnection(URL, Username, Password)
where URL represents path of database, and username and
passwords are string used to open database.
iii) Send queries
iv) Create ResultSet
v) Fetch Data from ResultSet
vi) Close Statement
vii) Close ResultSet
viii) Close Connection
Load JDBC Driver.
To load the driver, Class.forName(String) method is used. This method takes a string representing a
fully qualified class name and loads the corresponding class with respect to database. Here are
some examples:
// Connect to MySQL database Server
try {
Class.forName("org.gjt.mm.mysql.Driver");
6. 6
} catch(ClassNotFoundException e)
{
System.err.println("Error loading driver: " + e);
}
// Connect to Oracle Database Server
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e)
{
System.err.println ("Error loading driver: " + e);
}
The string taken in the Class.forName() method is the fully qualified class name specific to
database. Free JDBC drivers are available for most of the databases, but there are many third-party
vendors for older databases.Before loading driver make sure that the driver class is set in the
classpath, otherwise, the forName() method may throw ClassNotFoundException.
Step – 2. Make JDBC Connection
Once a driver is loaded successfully, you can create an instance of the Connection object. Since the
Connection object is an interface, it can't be instantiated directly. The following example shows one
way of creating an
instance of the Connection interface.
7. 7
The first parameter URL indicates the URL of the database. It includes the protocol, the vendor,
the driver, the database server name, the port number, and a database name. And the username
and password, of you database.
Second and third parameters are the username and password, which must be same as you would
enter into a database to access your account.
Step – 3. Process the Query Results
while ( rs.next() ) {
// get the type_id, which is an int
System.err.println("Type ID = " + rs.getInt("type_id"));
// get the type_name, which is a String
System.err.println("Type Name = " +
rs.getString("type_name"));
}
Closing the Connections
rs.close();
con.close();
2.What are the life cycle methods of JSP?
JSP Life Cycle Methods
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of
the JSP.
1. Initialization using jspInit() method
jspInit() method is called immediately after the instance was created. It is
8. 8
called only once during JSP life cycle.
2. _jspService()method
This method is called for every request of this JSP during its life cycle. So when a request comes
to the JSP, _jspService() method is invoked, the request is processed and the response is
generated. Here the actual
business logic is written.
3. jspDestroy() method
This method is used for clean process and is called when JSP is destroyed by the server. With
this call the Servlet serves its purpose and submits itself to heaven (garb age collection). This is
the end of JSP life
cycle.
3.What are attributes? Explain tags with attributes.
Attributes are used to pass information into a custom tag to configure the behavior of the tag. Tag
attributes are like XML or HTML attributes and are
name/value pairs of data. The values must be quoted with single or double quotes.The JSP
specification allows attributes to have values that can include Java
expressions. If the lookup name had been passed in as a request parameter called
agencyJNDIname,th e lookup tag could have been written as follows:
<demo: lookup name=<%=request.getParameter
(―agencyJNDIname)%>/>
Java expressions like this are referred to as request time expressions. Tag attributes can be defined
to disallow request time expressions, in which
case, the value must be a simplestring.
The TLD description for the tag must define any attributes it uses. Each supported attribute name
must be listed together with details of the attribute.
Every attribute must have an <attribute> tag with the sub-components shown in the table.
Attribute -Introduces an attribute definition in the <tag> component
of the TLD.
Name -Defines the attribute name.
Required -Followed by true if the attribute must be provided; otherwise, false.
Rtexprvalue -Defines whether the attribute can be specified with a request time expression. Set this
element to true to allow JSP scripting values to be used for the attribute; otherwise, the value
must be a string literal.
Type -Defines the type of an attribute and defaults to
java.lang.String. This element must be defined if the
rtexprvalue is true and the attribute value is not a String.
9. 9
4.Describe the process of deactivating Individual Expression Language Statements.
Suppose you have a JSP 1.2 page containing ${ that you want to use in multiple places. In
particular, you want to use it in both JSP 1.2 Web applications and in Web applications that contain
expression language
pages. You want to be able to drop the page in any Web application without making any changes
either to it or to the web.xml file. Although this is an unlikely scenario, it could happen, and none
of the previously discussed constructs will serve the purpose. In such a case, you simply replace the
$ with the HTML character entity corresponding to the ISO 8859-1
n JSP 1.2 and earlier, strings of the form ${...} had no special meaning. So, it is possible that the
characters $ {appear within a previously created page that is now being used on a server that
supports JSP 2.0. In such a case you need to deactivate the expression language in that page. You
have four options for doing so.
Deactivating the expression language in an entire Web application.
You use a web.xml file that refers to servlets 2.3 (JSP 1.2) or earlier.
Deactivating the expression language in multiple JSP pages. You use the jsp-property-group
web.xml element to designate the appropriate pages.
Deactivating the expression language in individual JSP pages. You use the isELEnabled attribute
of the page directive.
Deactivating individual expression language statements. In JSP 1.2
pages that need to be ported unmodified across multiple JSP versions (with no web.xml
changes), you can replace $ with $, the HTML character entity for $. In JSP 2.0 pages that
contain both expression
language statements and literal ${ strings, you can use ${ when you want ${ in the output.
Deactivating the Expression Language in an Entire Web Application:
The JSP 2.0 expression language is automatically deactivated in Web
applications whose deployment descriptor (i.e., WEB-INF/web.xml file) refers to servlet
specification version 2.3 or earlier (i.e., JSP 1.2 or earlier).
For example, the following empty-but-legal web.xml file is compatible with JSP 1.2, and thus
indicates that the expression language should bedeactivated by default.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
</web-app>
Deactivating the Expression Language in Multiple JSP Pages:
10. 10
In a Web application whose deployment descriptor specifies Servlets 2.4 (JSP 2.0), you use the el-
ignored sub-element of the jsp-property-group web.xml element to designate the pages in which
the expression language
should be ignored. Here is an example that deactivates the expression language for all JSP pages in
the legacy directory.
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
version="2.4">
<jsp-property-group>
<url-pattern>/legacy/*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</web-app>
Deactivating the Expression Language in Individual JSP Pages:
To disable EL evaluation in an individual page, supply false as the value of the isELEnabled
attribute of the page directive, as follows.
<%@ page isELEnabled="false" %>
Note that the isELEnabled attribute is new in JSP 2.0 and it is an error to use it in a server that
supports only JSP 1.2 or earlier. So, you cannot use this technique to allow the same JSP page to
run in either old or new
servers without modification. Consequently, the jsp-property-group element is usually a better
choice than the isELEnabled attribute.
Deactivating Individual Expression Language Statements:
Suppose you have a JSP 1.2 page containing ${ that you want to use in multiple places. In
particular, you want to use it in both JSP 1.2 Web applications and in Web applications that contain
expression language
pages. You want to be able to drop the page in any Web application without making any changes
either to it or to the web.xml file. Although this is an unlikely scenario, it could happen, and none
of the previously discussed constructs will serve the purpose. In such a case, you simply replace the
$ with the HTML character entity corresponding to the ISO 8859-1 value of $ (36). So, you
replace ${ with $ { throughout the page.
5.Compare BASIC authentications with HTTP Digest authentications.
Digest Authentication is a proposed authentication scheme for HTTP. It is planned to take over
11. 11
from unencrypted use of the Basic access authentication, allowing user identity to be established
securely without
having to send a password in plaintext over the network. So you can say
this is a direct replacement of Basic Authentication. This technique uses
MD5-base64 algorithm for password encryption. It takes text strings of arbitrary length and
generates a 16-byte checksum. It is designed so that if you are given only an MD5 checksum, it is
extremely difficult to find a block
of text that would result in that checksum. It can be considered a one-way encryption algorithm.
For example, when the server receives a new request, it looks up the user name in its password
database and gets the user's real password. It then computes the same three checksums above, using
that real password. If the result is the same as the one the browser sent, then the user either supplied
the correct password, or they got very lucky and found another password that has the same
checksum. Actually, the server should store the result of the first MD5 checksum in the password
database instead of storing the clear-text password - this saves computation, and, more
importantly, protects the user's password. The digest authentication standard include s some other
features. It allows for an MD5 checksum of the entire request or response to be included,
enabling the server or browser to detect if their messages have been tampered with somewhere on
the communication network between them. It
also allows the server to specify to w hich other pages the same authentication can be applied.
Working of Digest authentication Digest authentication is a challenge-response mechanism:
The browser sends an HTTP request (e.g. a GET) to a Web server.
The server sees the URL being accessed has been configured to require Digest authentication
and replies with a 401 "Authentication Required" status plus a "nonce": a unique hash of several
data items,
one of which is a secret key known only to the server.
The browser pops up a dialog box requesting username and password. Once the user enters
his/her information, an MD5 hash of the username, password, nonce and URL are computed and
the browser re-sends the original request along with the hash.
The Web server compares that hash with its own computation of the same values. If they match,
the original HTTP request is allowed to complete.
12. 12
6.What is JDBC? Describe different JDBC drivers. The Java Database Connectivity (JDBC)
API provides interfaces and classes for developing database applications in Java. JDBC is a
part of Java Standard Edition (Java SE). To use JDBC, you'll need at least JDK 1.1.
Currently Java SE 6 includes JDBC API 4.0 version. JDBC API’s are available in java.sql and
javax.sql packages. Most of web-application uses JDBC to send SQL, PL/SQL statements to
almost any relational database like, Oracle, MySQL, Sybase, DB2 etc. JDBC is a Java API for
executing SQL statements and supports basic SQL
functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Java
Database Connectivity is a Java API that enables you to connect any databases like MySql, Oracle,
Sybase, MS-Access, DB2 etc. To use JDBC, you'll need at least JDK 1.1, a database, and JDBC
drivers. As you know Java runs on most of the platforms, JDBC makes it possible to write a single
database application that can run on different platforms and interact with different databases.
There are many JDBC drivers available which support almost all popular databases. You can use a
specific driver for specific database, for example:
1. org.gjt.mm.mysql.Driver for MySql
2. oracle.jdbc.driver.OracleDriver for Oracle
For general, Sun has provided a driver which is compatible with ODBC, so you can to connect to
any ODBC compliant databases. It come with JDK, so if this is installed, no need to install
database specific drivers. But for this you need to create an ODBC data source accessing database
in your Java applications.
7.Explain various Scripting elements of JSP.
These are the building blocks of JSP. Every JSP contents Scripting elements. There are three
different types of Scripting elements:
1. Declaration
2. Scriptlets
3. Expression
Scriptlets allow you to put any valid Java code in it. Here you may declare variables as well as
methods. The code written in Scriptlets goes in service method of Servlet. These are called local
eclaration. They have two forms
i) Using Jsp tags
ii) Using XML tags
i) Using JSP Tags
13. 13
It has form <% scriptle here......... %>. Variables and methods are
accessible with _Jspservice() method only.
For example:
<% int age=18;
public int isEligible()
{
if(age>=18)
return “Candidate is eligible”;
else
return “Candidate is not elible;
}
%>
ii) Using XML tags
It has form <jsp:scriptlet> scriptle here......... </jsp:scriptlet>. Variables and
methods are accessible with Jsp_service() method only.
For example:
<jsp:scriptlet>
int age=18;
14. 14
public int isEligible()
{
if(age>=18)
return “Candidate is eligible”;
else
return “Candidate is not elible;
}
</jsp:scriptlet>
This part of scripting allows declaration of variables as well as methods.
This declaration goes in the Servlet class. You may call these variables and
methods as an instance variable and instance methods. So This can be
accessible throughout the class. Declaration generates output, so can be
used to Expressions and Scriptlets. Every tag must end with semicolon ( ; )
In JSP, declaration has two forms.
a) Using JSP tags
b) Using XML tags
a) Using JSP tags
It has form <%! Declaration here... %>. In between this tag you can declare
variables as well as methods.
15. 15
For example:
<%! String name = “Shreya” ;
public show()
{
return name; } %>
b) Using XML tags
It has form <jsp:declare> decaration here....... </jsp:declare>. In between
this tag you can declare variables as well as methods
Example:
<jsp:declare> String name = “Shreya”
public show()
{
return name; } </jsp:declare>
Expressions
This tag allows user to put any expression which goes in output. This is
alternative to out.println(). Semicolon (; ) is allowed with this tag. It has
form:
i) Using JSP tag
16. 16
ii) Using XML tag
i) Using JSP Tag
Expression is declared using <%= expression %> tag.
For example:
<%=new java.util.Date() %>
<%= isEligible() %>
<%= show() %>
ii) Using XML Tag
It has form
<jsp:expression> expression </jsp:expression>
For example:
<jsp:expression> new java.util.Date() </jsp:expression>
<jsp:expression> isEligible() </jsp:expression>
<jsp:expression> show() </jsp:expression>
8.Explain the methods in the custom tag life cycle.
The doStartTag () Method
The doStartTag () method is called once when the start tag is processed.
This method must return an int value that tells the JSP how to process the
17. 17
tag body. The returned value must be one of the following:
• Tag.SKIP_BODY The tag body must be ignored. The TLD should define
the <body-content> tag as empty.
• Tag.EVAL_BODY_INCLUDE The body tag must be evaluated and
included in the JSP page.
The TLD should define the <body-content> tag as JSP for tags that extend
Tag Support, or JSP or tagdependent for tags that extend BodyTagSupport.
The doEndTag () Method
The doEndTag () method is called once when the end tag is processed. This
method must return an int value indicating how the remainder of the JSP
page should be processed:
• Tag.EVAL_PAGE Evaluate the rest of the page.
• Tag.SKIP_PAGE Stop processing the page after this tag.
Where a tag has an empty body, the doEndTag () method is still called after
the doStartTag () method.
The release () Method
The release() method is called once when the JSP has finished using the
tag and is used to allow the tag to release any resources it may have
acquired. This method’s return type is void.
The doAfterBody () Method
The doAfterBody () method is called after the tag body has been processed
18. 18
and before the doEndTag () method is called. This method is only called for
classes that implement Iteration Tag or Body Tag (those that extend
BodyTagSupport). It must return one of the following values to the JSP page
indicating how the tag body should be processed:
•
IterationTag.EVAL_BODY_AGAIN This value is used to inform the page
that the tag body should be processed once more. The JSP processing
will read and process the tag body and call the doAfterBody() method
once more after the body has been processed again.
9.Describe the theory behind accessing scoped variables.
A Servlet invokes code that creates the
data, then uses RequestDispatcher.forward or response.sendRedirect to
transfer control to the appropriate JSP page. To permit the JSP page to
19. 19
access the data, the Servlet needs to use setAttribute to store the data in
one of the standard locations: the HttpServletRequest, the HttpSession, or
the ServletContext.
Objects in these locations are known as “scoped variables,” and the
expression language has a quick and easy way to access them. You can
also have scoped variables stored in the PageContext object, but this is
much less useful because the Servlet and the JSP page do not share PageContext objects. So, page-
scoped variables apply only to objects
stored earlier in the same JSP page, not to objects stored by a servlet.
To output a scoped variable, you simply use its name in an expression
language element. For example,
${name}
means to search the PageContext, HttpServletRequest, HttpSession, and
ServletContext (in that order) for an attribute named name. If the attribute is
found, its toString method is called and that result is returned. If nothing is
found, an empty string (not null or an error message) is returned. So, for
example, the following two expressions are equivalent.
${name}
4
<%= pageContext.findAttribute("name") %>
The problems with the latter approach are that it is verbose and it requires
explicit Java syntax. It is possible to eliminate the Java syntax, but doing so
requires the following even more verbose jsp:useBean code.
<jsp:useBean id="name" type="somePackage.SomeClass"
scope="...">
20. 20
<%= name %>
Besides, with jsp:useBean, you have to know which scope the Servlet has
used, and you have to know the fully qualified class name of the attribute.
This is a significant inconvenience, especially when the JSP page author is
someone other than the Servlet author.
Choosing Attribute Names
To use the JSP expression language to access scoped variables, you must
choose attribute names that would be legal as Java variable names. So,
avoid dots, spaces, dashes, and other characters that are permitted in
strings but forbidden in variable names.
Also, you should avoid using attribute names that conflict with any of the
predefined names.