• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A small web application

 
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

controller:
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 {
super.init(config);
context = config.getServletContext();
String driver =context.getInitParameter("driver");
String url=context.getInitParameter("url");
try {
Class.forName(driver);
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"));
bean.setFirstName(results.getString("fname"));
bean.setLastName(results.getString("lname"));
bean.setEmail(results.getString("email"));
bean.setDepartment(results.getString("department"));
bean.setImage(results.getString("image"));
return bean;
}
public EmployeeBean fetchEmployee(int id) {
try {
ResultSet results;
synchronized (statement) {
statement.clearParameters();
statement.setInt(1, id);
results = statement.executeQuery();
}
EmployeeBean bean = null;
if (results.next()) {
bean = makeBean(results);
}
if (results != null)
results.close();
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())
list.add(makeBean(results));
return list;
}
catch (SQLException se) { return null; }
}

public void destroy() {
try {
if (connection != null)
connection.close();
}
catch (SQLException e) { }
}
}
------------------------------------------------
Bean:
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() {
this(0);
}
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;
}
}

----------------------------------------------
employee.jsp
<%@ page import=" javaranch.EmployeeBean" %>
<jsp:useBean id="employee" class="javaranch.EmployeeBean"
scope="request" />
<html>
<head><title>employee record</title></head>
<body>
<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"/>
</b></font></td></tr>
<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"/>
</td></tr>
<tr><td><b>employee id:</b></td><td>
<jsp:getProperty name="employee" property="id"/>
</td></tr>
<tr><td><b>department:</b></td><td>
<jsp:getProperty name="employee" property="department"/>
</td></tr>
<tr><td><b>e-mail:</b></td><td>
<jsp:getProperty name="employee" property="email"/>
</td></tr>
</table>
</td>
</tr>
</table>
</body>
</html>
---------------------------------------------
list.jsp:
<%@ page import="java.util.* , javaranch.EmployeeBean" %>
<jsp:useBean id="employee" class="javaranch.EmployeeBean" />
<html>
<body>
<b>Current Employees</b>
<ul>
<%
Vector v = (Vector)request.getAttribute("list");
Iterator i= v.iterator();
while (i.hasNext()) {
employee = (EmployeeBean)i.next();

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

</a>
<% } %>
</ul>
<HR>
<jsp:include page="included.jsp" flush="true" >
<jsp aram name="webmaster" value="abc@hotmail.com" />
</jsp:include>
</body>
</html>
--------------------------------------------
included.jsp:

webmaster email:
<%=request.getParameter("webmaster") %>
------------------
web.xml
<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc dbc:emp</param-value>
</context-param>

<servlet>
<servlet-name>fetch</servlet-name>
<servlet-class>javaranch.EmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fetch</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
I HAVE USED ACCESS DATA BASE
DSN NAME--emp
data base name---any-
dsn name matters--only
table name---people_table
ID--NUMBER
FNAME--TEXT
LNAME--TEXT
DEPARTMENT---TEXT
EMAIL--TEXT
IMAGE---TEXT-----consists the url's for the images
/webAppPrefix/sample.gif
Add some records in the people_table

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

type in your browser:
..../webAppPrefix/test
or
...../webAppPrefix/test?cmd=get&id=1
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.
(update,add,delete)
SETTING TOMCAT (WINDOWS 2000)
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
.;d:\tomcat\common\lib\servlet.jar
HERE tomcat is the name of tomcat installation directory.
ok
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
OR/and
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
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
:gotJavaHome
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
type:
http://localhost:8080/
Enter
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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
means p
param

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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
correct location of web.xml:
webAppPreFix/WEB-INF/web.xml

Not

webAppPreFix/WEB_INF/web.xml
 
Amer Khan
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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"
"http://java.sun.com/dtd/web-app_2_3.dtd">
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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Amer, it is working right now.
 
Ranch Hand
Posts: 174
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

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

Thanx
verity
 
Amer Khan
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If u want to access your pages using
http://localhost/applicationName/-------
Instead of
http://localhost:8080/application/----------

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"
enableLookups="true"
acceptCount="100" debug="0" scheme="https" secure="true"
useURIValidationHack="false" disableUploadTimeout="true">
<Factory className="org.apache.coyote.tomcat4.CoyoteServerSocketFactory"
clientAuth="false" protocol="TLS" />
</Connector>[
[ June 24, 2003: Message edited by: Amer Khan ]
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic