File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes A small  web application Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "A small  web application" Watch "A small  web application" New topic

A small web application

Amer Khan
Ranch Hand

Joined: Apr 05, 2003
Posts: 163
Hi All,

This is a small application it consists of a controller servlet,one bean,three jsp pages,web.xml.and it retrieves data from the data base.

package javaranch;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class EmployeeServlet extends HttpServlet {

private final static String sql =
"select * from people_table where id = ?";
private Connection connection = null;
private PreparedStatement statement = null;
private ServletContext context;

public void init(ServletConfig config) throws ServletException {
context = config.getServletContext();
String driver =context.getInitParameter("driver");
String url=context.getInitParameter("url");
try {
connection = DriverManager.getConnection(url);
statement = connection.prepareStatement(sql);
catch (ClassNotFoundException e) {
System.err.println("Unable to load database driver");
throw new ServletException("Unable to load database driver");
catch (SQLException e) {
System.err.println("Unable to connect to database");
throw new ServletException("Unable to connect to database");
public void service(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String jspPageUrl;
String cmd = req.getParameter("cmd");
String idString = req.getParameter("id");
int id;
try { id = Integer.parseInt(idString); }
catch(NumberFormatException e) { id=0; };

if ("get".equals(cmd)) {
EmployeeBean bean = fetchEmployee(id);
req.setAttribute("employee", bean);
jspPageUrl = "/arch/employee.jsp";
else {
Vector list = fetchAll();
req.setAttribute("list", list);
jspPageUrl = "/arch/list.jsp";
RequestDispatcher dispatcher;
dispatcher = context.getRequestDispatcher(jspPageUrl);
dispatcher.forward(req, res);
public EmployeeBean makeBean(ResultSet results)
throws SQLException {
EmployeeBean bean = new EmployeeBean(results.getInt("id"));
return bean;
public EmployeeBean fetchEmployee(int id) {
try {
ResultSet results;
synchronized (statement) {
statement.setInt(1, id);
results = statement.executeQuery();
EmployeeBean bean = null;
if ( {
bean = makeBean(results);
if (results != null)
return bean;
catch (SQLException se) { return null; }
public Vector fetchAll() {
try {
Vector list = new Vector();
ResultSet results;
Statement st = connection.createStatement();
results = st.executeQuery("select * from people_table");
while (
return list;
catch (SQLException se) { return null; }

public void destroy() {
try {
if (connection != null)
catch (SQLException e) { }
package javaranch;
public class EmployeeBean {
private int id;
private String firstName;
private String lastName;
private String image;
private String email;
private String department;
public EmployeeBean(int id) { = id;
firstName = "";
lastName = "";
image = "";
email = "";
department = "";
public EmployeeBean() {
public int getId() {
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getFirstName() {
return this.firstName;

public void setLastName(String lastName) {
this.lastName = lastName;

public String getLastName() {
return this.lastName;

public void setImage(String image) {
this.image = image;

public String getImage() {
return this.image;

public void setEmail(String email) { = email;
public String getEmail() {
public void setDepartment(String department) {
this.department = department;
public String getDepartment() {
return this.department;

<%@ page import=" javaranch.EmployeeBean" %>
<jsp:useBean id="employee" class="javaranch.EmployeeBean"
scope="request" />
<head><title>employee record</title></head>
<table border="1" align="center">
<tr bgcolor="tan"><td colspan=2><font size=+3 face=arial><b>
<jsp:getProperty name="employee" property="lastName"/>,
<jsp:getProperty name="employee" property="firstName"/>
<tr><td align=left valign=top><IMG height="150" SRC="<%= employee.getImage()%>"</td>
<td align=left valign=top>
<table border=0>
<tr><td><b>full name:</b></td><td>
<jsp:getProperty name="employee" property="firstName"/>
<jsp:getProperty name="employee" property="lastName"/>
<tr><td><b>employee id:</b></td><td>
<jsp:getProperty name="employee" property="id"/>
<jsp:getProperty name="employee" property="department"/>
<jsp:getProperty name="employee" property="email"/>
<%@ page import="java.util.* , javaranch.EmployeeBean" %>
<jsp:useBean id="employee" class="javaranch.EmployeeBean" />
<b>Current Employees</b>
Vector v = (Vector)request.getAttribute("list");
Iterator i= v.iterator();
while (i.hasNext()) {
employee = (EmployeeBean);

<a href="/webAppPrefix/test?cmd=get&id=<%=String.valueOf(employee.getId()) %>
<%= employee.getFirstName() %>,
<%= employee.getLastName() %>,

<% } %>
<jsp:include page="included.jsp" flush="true" >
<jsp aram name="webmaster" value="" />

webmaster email:
<%=request.getParameter("webmaster") %>
<param-value>jdbc dbc:emp</param-value>

data base name---any-
dsn name matters--only
table name---people_table
IMAGE---TEXT-----consists the url's for the images
Add some records in the people_table

dir structure:
webAppPreFix/WEB-INF/classes/javaranch/both the classes here(servlet/bean)
webAppPreFix/arch/all jsp pages here.

type in your browser:
Clients should not be able access the jsp pages directly,to implement this
(security)click here

Its a very simple application but we can add different functionalities to improve it.
my jdk1.3 is installation directory d:\jdk1.3
tomcat installation directory is ---tomcat d:\tomcat
>controlpanel>system>Advanced>Environment Variables>system variables>New---type CLASSPATH in the upper textfield
and the value in the lower textfield
HERE tomcat is the name of tomcat installation directory.
next set the path:
PATH ----upper textfield
d:\jdk1.3\bin ----value in lower tf.
next set catalina_home:
CATALINA_HOME ----upper tf
d:\tomcat ---value lower tf.
HERE tomcat is the name of tomcat installation directory.

set java_home:
JAVA_HOME ----upper tf
d:\jdk1.3 ----lower tf
Edit setclasspath.batch file located at tomcat>bin>setclasspath.batch:
here set java_home like this:
set JAVA_HOME=d:\jdk1.3
This batch file looks like this:
rem ---------------------------------------------------------------------------
rem Set CLASSPATH and Java options
rem $Id: setclasspath.bat,v 1.8 2003/01/17 10:07:21 remm Exp $
rem ---------------------------------------------------------------------------
rem Make sure prerequisite environment variables are set
if not "%JAVA_HOME%" == "" goto gotJavaHome
set JAVA_HOME=d:\jdk1.3 <---------------------------------------------HERE
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javaw.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\jdb.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
goto okJavaHome

To confirm your settings
u should get the default tomcat home page.
I hope it helps!
[ August 05, 2003: Message edited by: Amer Khan ]

<i>Dare to dream - everything that exists today,was once a figment of someone's imagination, nobody says tomorrow can't be a figment of your today.</i>
Amer Khan
Ranch Hand

Joined: Apr 05, 2003
Posts: 163
means p

means :and odbc
Suggestions to improve or to add more functionality are more than welcome.
Sophia Choi
Ranch Hand

Joined: Mar 22, 2002
Posts: 106
I follow your programs under same directory.But the web.xml can't be found.
2003-06-05 11:47:40 WebappLoader[/WebAppPrefix]: Deploying class repositories to work directory D:\Tomcat 4.1\work\Standalone\localhost\WebAppPrefix
2003-06-05 11:47:40 WebappLoader[/WebAppPrefix]: Reloading checks are enabled for this Context
2003-06-05 11:47:40 ContextConfig[/WebAppPrefix]: Missing application web.xml, using defaults only
Thanks for helping.
Amer Khan
Ranch Hand

Joined: Apr 05, 2003
Posts: 163
correct location of web.xml:


Amer Khan
Ranch Hand

Joined: Apr 05, 2003
Posts: 163
Hi Sophia,

Did u add these line at the begining of the web.xml.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
Instead of cluttering your Tomcat installation directory a better approach is to keep your webapplication under your working directory.Consider D:\myDir as your working directory.
create the following structure in your working directory (myDir).
1)webapplicationPrefix(this is your application name)FOLDER, in this folder create 'arch' Folder and 'WEB-INF' FOLDER
in the WEB-INF FOLDER create 'classes' FOLDER.
1,put your web.xml in the WEB-INF folder
2,put your jsp pages in arch folder.
3,your bean and servlet go in classes folder.
4.keep your images in webapplicationPrefix folder
Open the %TOMCAT_HOME%\conf\server.xml
if your tomcats server.xml has a<ContextManager>--</ContextManager> block.Add the the following entry just before the closing </ContextManager> tag OR some where here<!-- Tomcat Root Context --> in server.xml.
<Context path="/webapplicationPrefix
docBase="D:\muDir\webapplicationPrefix" debug="0" />
Tomcat inspects content of this directory at server startup.
Rember webapplicationPrefix is the name of your application.
Here the first attribute is the path pointing to your webapplicationPrefix.This is the same as the path in the URL.The second attribute is a docBase attribute pointing to where your application is located.So like this u can have your application located anywhere on the system.(out-side tomcat installation dir).
Sophia Choi
Ranch Hand

Joined: Mar 22, 2002
Posts: 106
Thanks Amer, it is working right now.
Engin Okucu
Ranch Hand

Joined: Feb 09, 2002
Posts: 174
Hi Amer,
Thanks for you apllication. It's easy to read, the most important thing that i appreciated.
I tried it,it works well.
Verity smith

Joined: May 27, 2003
Posts: 18

Amer thanks for the application ,can anyone add some more functionality.It will be a great help.

Amer Khan
Ranch Hand

Joined: Apr 05, 2003
Posts: 163
If u want to access your pages using
Instead of

Edit tomcatInstallationDirectory==>config==>server.xml
replace 8080 with 80
Edit this portion of server.xml.

<!-- done by Amer: from 8080 to 80-->
<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="80" minProcessors="5" maxProcessors="75"
enableLookups="true" redirectPort="8443"
acceptCount="100" debug="0" connectionTimeout="20000"
useURIValidationHack="false" disableUploadTimeout="true" />
<!-- Note : To disable connection timeouts, set connectionTimeout value
to -1 -->
<!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="8443" minProcessors="5" maxProcessors="75"
acceptCount="100" debug="0" scheme="https" secure="true"
useURIValidationHack="false" disableUploadTimeout="true">
<Factory className="org.apache.coyote.tomcat4.CoyoteServerSocketFactory"
clientAuth="false" protocol="TLS" />
[ June 24, 2003: Message edited by: Amer Khan ]
Shazili Rafi

Joined: Jul 31, 2003
Posts: 2
I agree. Here's the link:
subject: A small web application
It's not a secret anymore!