• Post Reply Bookmark Topic Watch Topic
  • New Topic

A small web application  RSS feed

Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.io.*;
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 (results.next()) {
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 (results.next())
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) {
this.id = id;
firstName = "";
lastName = "";
image = "";
email = "";
department = "";
public EmployeeBean() {
public int getId() {
return this.id;
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) {
this.email = email;
public String getEmail() {
return this.email;
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)i.next();

<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="abc@hotmail.com" />

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 ]
Amer Khan
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
means p

means :and odbc
Suggestions to improve or to add more functionality are more than welcome.
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
correct location of web.xml:


Amer Khan
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Amer, it is working right now.
Ranch Hand
Posts: 174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Amer,
Thanks for you apllication. It's easy to read, the most important thing that i appreciated.
I tried it,it works well.
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

Amer Khan
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!