Servlets
What are Servlets?
The following are the basic steps of using servlets:
• The client makes a request.
• The Web server forwards the request to the servlet after receiving it from the client.
• Some kind of process is done by the servlet after receiving the HTTP request.
• A response is returned back to the web server from the servlet.
• The web server will forward the response to the client.
Why use servlets Instead of CGI?
CGI makes separate process for each request but servlet can't make separate process.
• What are the requirements for writing Servlets?
Install JavaSoft’s Java Servlet Development Kit (JSDK). Set the environment variable CLASSPATH, to the required location so that your servlets can find the servlet packages.
The following setting has to be made for Windows 95 and NT systems, with the JSDK installed in the default location:
set CLASSPATH=%CLASSPATH%;C:\Program Files\JSDK\lib\Classes.zip
To run Servlets you need a Web server that supports the Servlet API. The following steps are required to run any servlet:
• If your Web server is not running, start it.
• Configure the Web server to install the servlet.
• Run your Web browser.
• Direct the browser to the particular URL that refers to the new servlet.
For example, a URL that refers to the servlet is of the form:
http://host-name:port/servlet/servlet-name?request-query-string
The Java Web Server
The Java Web Server known as Jeeves is JavaSoft’s Web server, which supports the use of servlets. This Web Server is written in the Java language and it is not a part of JDK distribution.
• Configuring Java Web Server for Servlets
The administration tool is invoked by accessing the administration port of the server with a Java enabled Web browser. The Java Web Server administration tool is installed on port 9090. In order to invoke this tool, you can use the following URL: http://localhost:9090/index.html
The following fields are displayed on the servlet-loading view, which are used for configuring:
Name: This is the name assigned to the server. It need not be the name of the servlet class.
Description: It describes the servlet in brief. It is only used from within the Web service.
Class Name: It defines the Java class name for the servlet, including the package name.
Arguments: It defines the list of arguments to be passed to the servlet.
The arguments should be given in the following format: key=value
Load at Startup: This indicates whether the servlet should be loaded automatically when the server starts.
Loaded Now: This indicates whether the servlet is currently loaded. This field can be used to load and unload the servlet.
Load Remotely: This indicates whether the Web service should load the servlet from a remote location.
Class File URL: This indicates the URL of the remote servlet class.
The other way of configuring the Java Web Server for servlets is by changing the properties defined in the configuration file called servlets.properties available in the admin\properties\process\javawebserve \adminservice directory.
To define a servlet in this file, use the following form:
servletname.code=classname
The default code base of a servlet is the servlets directory but it can be overridden by an entry in the following form:
servletname.codebase=URL
The arguments to the servlets can be specified by an entry in the following form:
servletname.initArgs=comm_separated_list
To configure the servlets.properties file for running a servlet named TestServlet defined in a class called Test, you have to enter the following lines in the file servlets.properties:
TestServlet.code=Test
TestServer.codebase=http://localhost:8080/servlet
TestServer.initArgs=one=Hello,two=World
• Create your .java file i.e. SimpleServlet.java
• Place in your directory e.g. C:\MyServlets
• Set classpath as set classpath=c:\jsdk2.0\lib\JSKD.jar this instruct a compiler that all class file which is imported is located in jsdk2.0\lib directory and the file is jsdk.jar
• Compile your SimpleServlet.java file, you will get SimpleServlet.class.
• Open another command window
• Change your directory c:\jsdk2.0\bin
• Start servletrunner and use –d option to specify where your class file is located in our case it is MyServlets i.e. c:\jsdk2.0\bin\servletrunner –d c:\MyServlet
• Open a browser and give address as http://localhost:8080/servlet/SimpleServlet This means that servlet is present in your local machine and port address is 8080. The name of the servlet is SimpleServlet.
The Servlet API
The package javax.servlet defines all the classes and interfaces associated with the Servlet API. This package includes four Java interfaces and three classes. The interfaces are:
• ServletContext
• ServletRequest
• ServletResponse
• ServletStub
And the classes are:
• Servlet
• ServletInputStream
• ServletOutputStream
Basic Servlet classes and methods
The Servlet class allows the developer to create servlets by providing the necessary functions. This class includes the methods listed in Table below:
Servlet Class Methods
Public void service( ServletRequest req, ServletResponse res) : This method is used to service a single request from a client. The main purpose of the parameters is to access the input and output streams that are connected to the client browser.
Public void init() : This method is called by the system when the servlet is first loaded. It is basically used for general initialization of the servlet. The init () method might be called to reset the servlet after it has been used. Therefore, you have to be careful that only initialization is performed in this init () method.
ServletContext getServletContext(): This method gets a servletContext object that is associated with information about the environment in which the servlet is running.
void log( String mesg ): This method is used to log a message to the servlet log. Logs are generally written into a directory called log under the server’s home directory. These log entries depict the accesses the Web server receives.
String getServletInfo(): This method returns the information about the servlet, as a string.
public void destroy(): This method is used to release the servlet.
Methods to get Information about the Request - The ServletRequest Interface
int getContentLength():This method is used to return the size of the input data to be supplied (in bytes). It returns -1 if the size is unknown.
String getContentType():This method is used to return a string that is associated with the MIME content type for the data that is to be sent to the servlet from the client browser. This method returns null if the client has not specified the content type. The Content type depends on the browser. For instance, some browsers specify content types of text / plain to indicate that the data is of no special type. Some use content / unknown, and some use application / octet-stream.
String getProtocol():This method is used to return the protocol and version of a Web browser client. The returned string is of the form.
String getParameter( String parameter-name): This method is used to return the value of the parameter (Query string defined in the URL) associated with the name of the parameter passed as an argument to this method. For example, if an URL is given as : http://localhost:8080/servlets/Myservlet>mesg=Hello, the method call getParameter(“mesg”) would return the string value Hello.
Enumeration getParameterNames():This method is used to return an enumeration of strings representing the names of the parameters defined in the URL. This method does not return the values associated with the parameters. To obtain the associated values, call the getParameter() method.
InetAddress getRemoteAddr(): This method is used to return the IP address of the client who sent the request.
String getRemoteHost():This method is used to return the name of the host who made the request.
String getQueryString(): This method is used to return a string that represents only the query string part of the Servlet URL.
String getServerName(): This method is used to return a string that represents the host name of the server.
Int getServerPort(): This method is used to return an integer that represents the port number through which the request is received.
String getPathTranslated():This method is used to return the path information that describes the path on the server machine from which the servlet was loaded.
String getHeader( String header_field): This method is used to return the header information associated with the header_field. To obtain the header_field use the method getParameterNames().
ServletInputStream getInputStream():This method returns the input stream for reading the request data.
Methods to send Information to the client’s browser - The ServletResponse Interface
The response status can be set through a list of static integer variables defined by the ServletResponse interface. The following are the variables:
• SC_OK
• SC_CREATED
• SC_NO_CONTENT
• SC_MOVED_PERMANENTLY
• SC_MOVED_TEMPORARILY
• SC_BAD_REQUEST
• SC_UNAUTHORIZED
• SC_FORBIDDEN
• SC_NOT_FOUND
ServletResponse Interface
ServletOutputStream getOutputStream():This method is used to return the output stream for writing responses to the client browser.
void setContentLength(int length): This method is used to set the content length of the response.
void setContentType( String type ): This method is used to set the content type for the response. The content types are the MIME types discussed earlier. (Refer note for more details about MIME).
void writeHeaders():This method is used to write the status and message headers for the response to the output stream.
void setStatus( int status ): This method is used to set the status code and a default message for the response.
void setHeader( String header_field, String header_value): This method is used to set the value of a header field.
Methods to get Information regarding the servlet context - The ServletContext Interface
The ServletContext interface allows you to find out information about the environment in which the servlet is running.
ServletContext Interface
String getServerInfo():This method is used to return a string that represents the name and the version of the server running.
String getServlet():This method is used to return a string that represents the name of the servlet.
Enumeration getServlets():This method is used to return an enumeration of all the available servlets in this context.
The basic steps required for writing servlets are as follows:
• Step 1 : Extend the Servlet class.
• Step 2 : Override the service() method.
• Step 3 : Get the output stream from the ServletResponse object and create a PrintStream object with it.
• Step 4 : Set the response status to OK using the static variable SC_OK.
• Step 5 : Set the content type of the response to the appropriate MIME type.
• Step 6 : Finally, print the request string to the PrintStream.
Let us write a simple servlet program with the help of the above methods. This servlet will respond to the client with the server’s information.
The output produced by the above program is in plain text, as follows:
Listing 3:The following program displays the responses given by the servlet. This program demonstrates some methods of the ServletRequest interface:
Listing 4 : The following program responds to the client with an image :
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimpleImg extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
res.setContentType("image/jpeg");
File f = new File("servlets/","veli.jpg");
int size = (int)f.length();
res.setContentLength(size);
byte [] buffer = new byte[size];
FileInputStream in = new FileInputStream(f);
in.read(buffer);
res.getOutputStream().write(buffer);
res.getOutputStream().close();
}
}
This is the output produced by this servlet program.
Server-Side Includes
The following steps illustrates the basic flow of Server-Side Includes:
- The mapping table is checked by the Web server for any prefix or suffix matches. In this case, the .shtml file matches a suffix mapping which instructs the Web server to invoke the Server Side Include servlet.
- If necessary, the Server Side Servlet is loaded and invoked. The Servlet tags are searched only after the Servlet Side Include servlet has parsed the data stream that was read by the File servlet.
- The servlets corresponding to all the servlet tags found will be invoked and the output fron the servlets merged with the data stream at the point of inclusion of the servlet tags.
- Finally, the assembled HTML page will be sent to the client.
Exception? What does that mean?
"Exception" in general means something which is not usual or something which is different from normal. For example, taking tablets or some medicine can be considered as an exception. Because they do not happen normally but in some unusual situations.
By the way "Exception" in programming means any event that interrupts the normal execution of the program. so now this goes in hand with the general definition of exception.
-------------------------------------------------------------------------------------------------------------------
| Exception is an event that interrupts the normal execution of the program |
-------------------------------------------------------------------------------------------------------------------
Why Should we handle exception?
Handling exception may seem to be a weird stuff for a beginner and there are all the possibilities that the beginners end up with this question.
For beginners the programs which they work on, for learning will be small and simple and they surely will not be in a need to handle exception. But, when the software size grows, its necessary to handle the exception, especially for the software that are designed for commercial purpose.
Now here is a simple example to explain the importance of Exception handling..
consider the software used in banking systems. If the software crashes due to some exception then there would be so much loss in terms of money.
So its always good that the software don't stop abruptly. But if the error is so fatal that the software has to stop then at least some measures to store the information so that it can be recovered after the crash. This obviously shows that exception handling is necessary.
Now let's get into Java
Exception handling in Java
To handle exception in Java is very simple, just place the suspicious code in try block and the handling code in catch block.
General Syntax
try
{
// code that can cause exception
}
catch( /*Exception class*/ )
{
// code to handle the exception
}
catch(){}
:
:
finally
{
//code that will be executed always
}
Execution of try catch block
The above block diagram shows the working of Try catch block.
Statements that are in try block will be executed and if any exception occurs then the statements in corresponding catch block will be executed. if no exception occurs then catch block will not be executed.
Code sample
try
{
int a=10,b=0,c;
c=a/b; //Division by zero error occurs in this statement
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurred") ; //displays the error message
}
catch(Exception e)
{
System.out.println(e.toString());
}
finally
{
System.out.println("Finally block"); // This statement will always be executed
}
In the above example when the error occurs it is caught by the catch block and the error message is displayed and then finally block will be executed.
If the statement doesn't have any error for example if value of b is not zero then there will not be any exception so catch block will not be executed, but finally block will be executed.
In the catch block "ArithmeticException" is the class name of the Exception to be caught and "e" is the object which can be used to get information about the exception that was caught by that block.
If any other Exception is to be caught then corresponding Exception class names can be used. To catch all kinds of Exception "Exception" class can be used. "Exception" is the base class for all Exception classes. Therefore "ArithmeticException" is a derived class of "Exception".
In the above example both "Exception" and "ArithmeticException" are used and if any arithmetic exception occurs then only the catch block with "ArithmeticException" will be executed. But if any other exception occurs then the catch block with "Exception" will be executed. This is because if exception occurs then the catch blocks will be checked for any match and if anything is found then it will be used and if not found then catch blocks will be searched for any base class and it will executed.
Exceptions need be predefined but they can also be user-defined.
This is the basic Exception handling in Java.
Deleted.
Java Database Connectivity (JDBC) is a standard database access interface with SQL. It provides programmers with a uniform interface to various relational database systems regardless of differences in implementations. JDBC is part of Java 2 (the java.sql package). Database vendors ship JDBC drivers that enable accessing their databases from Java program through JDBC. For example, DB2, IBM's RDBMS, provides a JDBC driver class, COM.ibm.db2.jdbc.app.DB2Driver, that translates JDBC calls into native DB2 calls and converts the DB2 results into a JDBC data structure. The class COM.ibm.db2.jdbc.net.DB2Driver is used for remote access of the database. Thus application programs that use JDBC can run with different RDBMSs without modification. A list of more than 150 JDBC drivers supplied by database vendors is maintained at Sun's Web site (http://industry.java.sun.com/products/jdbc/drivers). If you want to use Open Database Connectivity (ODBC), a standard API for accessing a database, to connect Java applications to Microsoft Access or Excel, you can use the JDBC-ODBC bridge. In this part of article, assume there is a sample database that contains a table named employee. The employee table has the schema shown in Table LOHIT1. The sample database and the employee table are included in DB2 as a sample, so you do not have to create them.
JDBC
Symbols such as CHARACTER and DATE show the data types of each column. For example, the data type CHARACTER(6)represents a six-letter character string, while VARCHAR(12) represents the data type of a character string that is at most 12 characters long. We use the data in this table as shown in Table LOHIT2, which is based on the schema in Table LOHIT1
Before creating a sample program that accesses the employee table by using JDBC, let's look at the functions of JDBC |
JDBC Package JDBC is provided by the java.sql package. Tables Here is the lists of classes, interfaces, and exceptions, respectively.
Classes in the java.sql Package
Interfaces in the java.sql Package INTERFACE
- Array: An interface that represents the SQL ARRAY type.
- BLOB: An interface that represents the Binary Large Object (BLOB) type.
- CLOB: An Interface that represents the SQL Character Large Object (CLOB) type.
- CallableStatement: An interface used for executing a stored procedure of SQL.
- Connection: An interface that represents a session with a specific database. It is created by calling the Driver#connection() method.
- DatabaseMetaData: An interface used for accessing the properties of a database as a whole
- Driver: This is the main body of a JDBC driver. An implementation-specific driver must implement this interface.
- Ref: An interface used to access the SQL structured type.
- PreparedStatement: A subinterface of Statement that represents a compiled query for efficiently executing the same query many times.
- ResultSet: An interface that provides access to a table of data generated by executing an SQL query using a Statement object.
- ResultSetMetaData: An interface used for accessing the properties of query results, such as data types and column names.
- SQLData: An interface used to access an SQL user-defined type.
- SQLInput: An interface that represents an input stream to get an SQL user-defined type stored in database.
- SQLOutput: An interface that represents an output stream to write attributes of a user-defined data type to the database.
- Statement: An interface used for executing an SQL statement.
- Struct: An interface that represents an SQL structured type.
Exceptions in the java.sql Package EXCEPTION
- SQLException: An exception that provides information on a database access error.
- SQLWarning: An exception that provides information on a database access warning.
- BatchUpdateException: An exception that occurs during a batch update operation.
- DataTruncation: An exception that occurs when JDBC unexpectedly truncates data.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
Loading a JDBC Driver
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
In this case, we used the JDBC driver for DB2. The class name must be replaced when you use other database implementations. The coding style is something strange. What happens when the method is called?
The static method forName(), defined in the class Class, generates a class object of the specified class. How is the JDBC driver object registered with DriverManager? Any JDBC driver has to have a static initialization part that is executed when the class is loaded, as shown next. As soon as the class loader loads this class, the static initialization is executed, which automatically registers it as a JDBC driver with DriverManager.
public class DB2Driver {
public DB2Driver() {
...
}
static {
try {
DriverManager.registerDriver(new DB2Driver());
return;
} catch(SQLException sqlexception)
}}
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
Connecting to a Database
With the driver in place, we next need to specify the data source we want to access. In JDBC, a data source is specified by a URL with a scheme jdbc.
Subprotocol represents the type of the data source, which is normally the name of the database system, such as db2 and oracle. Subname is used to specify information for the database. The contents and syntax of subname depend on the subprotocol.
For example, to access a table named sample stored in IBM's DB2 on a local machine, you need to create a URL as follows:
String url = "jdbc:db2:sample";
String url = "jdbc:db2:monet.trl.ibm.com/sample";
// Userid and password are specified as
// System properties
String userid = System.getProperty("chap11.userid");
String password =System.getProperty("chap11.password");
// Connects with default username and password
Connection con = DriverManager.getConnection(url,userid,password);
// Default username is used
Connection con = DriverManager.getConnection(url);
Submitting a Query
Statement stmt = con.createStatement();
String SQLquery = "SELECT * FROM EMPLOYEE";
// Gets result of the query
ResultSet rs = stmt.executeQuery(SQLquery);
The class ResultSet defines a number of methods for accessing the result. The result set is basically a sequence of rows, over which we can iterate using the next() method. The result set maintains a cursor to remember the current row in the result set. A call of the next() method advances this cursor to the next row until the end of data, where next() returns null. Within the cursor row, you can access the value of each column by specifying either the index number of the column or the name of the column. The getXX methods, where XX represents data types such as Int and String, can be used to access each column.
The following code fragment shows how to retrieve the first column (EMPNO) and second column (FIRSTNAME) of the result set.
while (rs.next()) {
String firstColumn = rs.getString(1);
String secondColumn = rs.getString(2);
System.out.print(firstColumn);
System.out.print(" " + secondColumn);
System.out.print("\n");
}
package appendixD;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
class JDBCSample {
static {
try {
// Register the driver with DriverManager
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String argv[]) {
try {
// URL is jdbc:db2:dbname
String url = "jdbc:db2:sample";
// Userid and password are specified as
// System properties
String userid = System.getProperty("appendixD.userid")
String password = System.getProperty("appendixD.password");
// Connects with default username and password
Connection con = DriverManager.getConnection(url,userid,password);
// Creates statement
Statement stmt = con.createStatement();
String SQLquery = "SELECT * FROM EMPLOYEE";
// Gets result of the query
ResultSet rs = stmt.executeQuery(SQLquery);
// Displays Result
while (rs.next()) {
String firstColumn = rs.getString(1);
String secondColumn = rs.getString(2);
System.out.print(firstColumn);
System.out.print(" " + secondColumn);
System.out.print("\n");
}
rs.close();
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
}}}
Executing this program generates the following output.
This section of article introduced a program using JDBC. This program is quite simple but shows a typical pattern appearing in large applications. The next section describes other functions of JDBC by using more complex programs.
Using a Connection Pool
We showed how to connect to a database in the previous section. However, connecting to a database is expensive work for most Web applications. Therefore, application servers provide various ways for managing database connections and reducing the overhead for the connections. However, the implementation is vendor-specific, and it is an obstacle to developing vendor-independent systems.
To resolve this issue, JDBC supports the javax.sql.DataSource and javax.sql.ConnectionPoolDataSource classes, which abstract low-level connection information. These classes are distributed separately as an optional package of JDBC .
By using the connection pool, you do not need to specify the database URI in a program. Instead, you use the Java Naming and Directory Interface (JNDI) to bind a declared name to a database. It makes a program more robust for changing database settings. The connection pool also provides a way to control the number of connections. We recommend that you use the connection pool if it is available in your middleware, such as an application server.
However, the detailed setting of connection information still depends on implementations of JDBC drivers. The function is now supported mainly by J2EE-compliant application servers, so it may be available when you are developing applications on an application server. In the other sections in this appendix, we use sample programs that connect to database without using the connection pool, as shown in Listing LOHIT1.
import javax.naming.Context;
import javax.naming.InitialContext;
import COM.ibm.db2.jdbc.DB2DataSource;
// Connects with default username and password
DataSource ds = (DataSource)Class.forName(
"COM.ibm.db2.jdbc.DB2DataSource").newInstance();
// Sets database-specific info. It depends on JDBC driver
// implementations
(DB2DataSource)ds).setDatabaseName("sample");
Context ctx = new InitialContext();
// Binds JNDI name and DataSource instance
ctx.bind("jdbc/SampleDataSource", ds);
...
The Context interface is used to specify a name context. A JNDI name is managed by the context. The Context object is initiated by calling a constructor of the InitContext class. An implementation of JNDI is provided as a provider. There are some implementations of the JNDI provider based on Lightweight Directory Access Protocol (LDAP), an ordinal file system, and so on.
The class COM.ibm.db2.jdbc.DB2DataSource is an implementation of DataSource and provides some (implementation-specific) methods to set database information. After setting the information, you register a JNDI name by using the bind() method. To learn the details of the connection pool, please consult the vendor-specific APIs for the DataSource implementation, or consult the manuals for the application server you are using.
import javax.naming.Context; // JNDI
import javax.naming.InitialContext;
import java.sql.Conncection;
import javax.sql.DataSource; // JDBC 2.0 Optional
import COM.ibm.db2.jdbc.DB2DataSource; // DB2 specific
...
// Connects with default username and password
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/SampleDataSource");
Connection con = ds.getConnection("db2admin", "db2admin");
...
Deleted.