Download JSP and Servlet Notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
J2EE JSP and Servlets
JSPs and Servlets
____________________________________
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 1
J2EE JSP and Servlets
The Simplest JSP is a Plain HTML Page
example0.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus 1.2">
<META NAME="dichter" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY BGCOLOR="#12FF12">
<!-- This is a plain HTML page, but I call it a jsp page -->
<%-- This a jsp comment: does not show up in browsers --%>
<H2>Welcome to Java JSP</H2>
<H2>Do you speak Java?</H2>
<IMG SRC="duke.gif" BORDER=0 ALT="pic of duke">
<HR>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 2
J2EE JSP and Servlets
Let’s install the Apache Tomcat Web Server
1.
Open the apache-tomcat-5.5.15.zip file located in the
code\ apache-tomcat 5.5.15 folder using WinZip.
2.
Extract to the root directory.
3.
You should have an apache-tomcat 5.5.15 folder off the root.
4.
Now we need to create two environment variables an Windows
5.
Open Control Panel -> System -> Advanced
6.
Press Environment Variables
7.
Under System Variables choose New
8.
Enter the following, and press OK
9.
One again, choose New
10.
You need to create a variable JAVA_HOME (use your Java installation
directory 1.4 or higher). The value of the variable stops just above the bin
folder of the java installation. Your may be different than shown below.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 3
J2EE JSP and Servlets
Apache Tomcat Web Server Installation (continued)
11.
To Test our system, open a command window (Run, cmd)
12.
Go to the following directory
C:\ apache-tomcat 5.5.15\bin
Type the command startup
13.
Tomcat server should start, and you should see a similar screen as shown
below. This is a good screen.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 4
J2EE JSP and Servlets
Apache Tomcat Web Server Installation (continued)
14.
To test if we were successful, open Internet Explorer (IE) and type the
following address:
http://localhost:8080
15.
A successful install will give the following view
This completes the install
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 5
J2EE JSP and Servlets
Let’s Create Our Application in Tomcat
1.
Create a folder called mmm under C:\ apache-tomcat 5.5.15\webapps
2.
In the mmm folder, create a another folder called WEB-INF
3.
You should have a folder structure as shown below
4.
C:\  apache-tomcat 5.5.15  webapps  mmm  WEB-INF
C:\  apache-tomcat 5.5.15  webapps  mmm  WEB-INF  classes
This completes the application directory setup
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 6
J2EE JSP and Servlets
JSP Exercises
1.
Move the example0.jsp and duke.gif files into the mmm folder.
2.
Open IE, and go to http://localhost:8080/mmm/example0.jsp
3.
You should see the image on page 2.
4.
Examine the source code using IE’s View -> Source
5.
What is missing from the source that is present in the JSP file? Do you
know why?
This completes the exercises.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 7
J2EE JSP and Servlets
Types of JSP Statements
Declaration
Declares a variable valid in the scripting language used in the JSP page.
JSP Syntax
<%! declaration; [ declaration; ]+ ... %>
XML Syntax
<jsp:declaration>
declaration; [ declaration; ]+ ...
</jsp:declaration>
Examples
<%! int n = 0; %>
<%! int a, b, c; %>
<%! Date date = new java.util.Date(); %>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 8
J2EE JSP and Servlets
Types of JSP Statements
Expression
Contains an expression valid in the scripting language used in the JSP page.
JSP Syntax
<%= expression %>
XML Syntax
<jsp:expression>
expression
</jsp:expression>
Examples
The map file has <font color="blue"><%= map.size()
%></font> entries.
Good guess, but nope. Try
<b><jsp:expression>numguess.getHint()</jsp:expressio
n></b>.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 9
J2EE JSP and Servlets
Types of JSP Statements
Scriptlet
JSP Syntax
<% code fragment %>
XML Syntax
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Examples
<% vector.addElement(new Integer(5)); %>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 10
J2EE JSP and Servlets
Using Declarations, Expressions and Scriptlets
This simple JSP uses 3 types of JSP statements
<%-- Declarations --%>
<jsp:declaration>
java.util.Vector vector = new java.util.Vector();
double amount;
</jsp:declaration>
<%! int n = 0; %>
<%! int a, b, c; %>
<%! java.util.Date date = new java.util.Date(); %>
<%-- Expressions --%>
Today is
<b><jsp:expression>date</jsp:expression></b>.
<BR><BR>
My Vector has <%= vector.size() %> elements.
<%-- Scriptlets --%>
<% vector.addElement(new Integer(5)); %>
<% vector.addElement(new Integer(6)); %>
<% vector.addElement(new Integer(7)); %>
<BR><BR>
My Vector now has <%= vector.size() %> elements.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 11
J2EE JSP and Servlets
JSP Exercises
1.
Copy example1.jsp into your web application folder, webapps\mmm.
2.
Call up this JSP page from IE
3.
Add the following two scriptlets at the end of example1.jsp.
<% out.println("Hello JSP World"); %>
<% System.out.println("Test JSP World"); %>
4.
Determine where the output is going. Check your code against the
example1/solution folder if needed.
This completes the excercises
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 12
J2EE JSP and Servlets
Importing Classes and Packages in JSP
Either syntax can be used to import either classes or entire packages
<%@page import="java.util.Calendar"%>
<jsp:directive.page import="java.util.*"/>
<%@page import="java.util.Calendar"%>
<jsp:directive.page import="java.util.*"/>
<% Calendar cal = Calendar.getInstance(); %>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 13
J2EE JSP and Servlets
JSP include tag
Static include
The include directive <%@include file="myFile.jsp"%>
Reads the source of the included file into the current jsp page as a translation time
activity
Dynamic include
The include tag <jsp:include page="mypage.jsp" flush="true"/>
Similar to above, but changes what is included every time the jsp:included page changes
include tag dynamics:
The include tag includes the result of the included page in the current page. This allows
each page to have its own scope, i.e. two different beans can have the same name, and
they would not conflict with each other.
Pages which jsp:include other JSP pages will immediately reflect those changes, as the
servlet will be rebuilt every times the base jsp page changes or a jsp:included page
changes.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 14
J2EE JSP and Servlets
JSP Exercises
1.
Copy example2.jsp into your web application folder, webapps\mmm.
2.
Call up this JSP page from IE. You should see
3.
Now add a dynamic include of the example1.jsp page between the two
output lines. Call up the page again. You should see
4.
Check your code against the example2/solution folder if needed.
This completes the excercises
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 15
J2EE JSP and Servlets
A Basic JSP Page with a Loop
example3.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE> A JSP page with declared variables </TITLE>
</HEAD>
<BODY BGCOLOR="#04e522">
<% int i = 1; %>
<% int j = -5;%>
<P>i = <%= i %>. </P>
<P>j = <%= j %>. </P>
<HR>
<% for(int k = 0; k < 10; k++) { %>
k = <%= k %>
<%= " V"%>
<BR>
<% ; } %>
<HR>
<% for (int m = 1; m < 5 ; m++) { %>
m = <%= " " + m %>
<% } %>
<P>Today is <%= new java.util.Date().toString() %></P>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 16
J2EE JSP and Servlets
Output of example3.jsp
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 17
J2EE JSP and Servlets
Including another Page: example3solution.jsp
Note the include directive, <%@include file=" "%>
Static translation time activity
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE> A JSP page with declared variables </TITLE>
</HEAD>
<BODY BGCOLOR="#04e522">
<%@include file="example0.html"%>
<% int i = 1; %>
<% int j = -5;%>
<P>i = <%= i %>. </P>
<P>j = <%= j %>. </P>
<HR>
<% for(int k = 0; k < 10; k++) { %>
k = <%= k %>
<%= " V"%>
<BR>
<% ; } %>
<HR>
<% for(int m = 1; m < 5 ; m++) { %>
m = <%= " " + m %>
<% } %>
<P>Today is <%= new java.util.Date().toString() %></P>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 18
J2EE JSP and Servlets
Output of example3solution.jsp
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 19
J2EE JSP and Servlets
JSP Exercises
1.
Copy example3solution.jsp into your web application folder,
webapps\mmm. Create a page example0.html which has the same
content as example0.jsp. Call example3solution.jsp from IE. You
should see the output shown on the previous page.
2.
Now modify the example0.html so that the text reads
<H2>Do you speak French?</H2> instead of
<H2>Do you speak Java?</H2>
3.
Call example3solution.jsp from IE. Does it reflect the change in
example0.jsp?
4.
What would you have to do to get the modified example0.html reflect
in example3solution.jsp?
This completes the excercises
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 20
J2EE JSP and Servlets
Integrating JSP with HTML
example4.jsp
<HTML>
<HEAD><TITLE>I Love jsp</TITLE></HEAD>
<% for(int i = 1;i <= 7;i+=1) { %>
<FONT COLOR=<%= Integer.toHexString((int)(1+Math.random()*256))+
Integer.toHexString((int)(1+Math.random()*256))+
Integer.toHexString((int)(1+Math.random()*256))%>
SIZE=<%=i%>>I Love jsp</FONT><BR>
<% } %>
<% for(int i = 6;i > 0;i-=1) { %>
<FONT COLOR=<%= Integer.toHexString((int)(1+Math.random()*256))+
Integer.toHexString((int)(1+Math.random()*256))+
Integer.toHexString((int)(1+Math.random()*256))%>
SIZE=<%=i%>>I Love jsp</FONT><BR>
<% } %>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 21
J2EE JSP and Servlets
Output of example4.jsp
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 22
J2EE JSP and Servlets
Passing Parameters to JSP Pages
Parameters can be passed to a JSP page directly in the call, or by other
techniques used in the HTTP 1.1 protocol.
A simple way to send parameters is to add them after the URI as in
http://localhost:90/MMM/example5.jsp?name=JOE&hobby=SKIING
Normally the parameters are taken from the HTML Form element
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 23
J2EE JSP and Servlets
Passing Parameters to JSP Pages
Here is the URI used to call the page
http://localhost:90/MMM/example5.jsp?name=Julius&town=Litchfield&id=234
example5.jsp
<HTML><HEAD></HEAD>
<BODY><HR>
<% java.util.Enumeration enum; %>
<% int i = 1; %>
<% java.lang.String pName; %>
<% enum = request.getParameterNames(); %>
<% if (enum == null) { %>
<P>Sorry, No Parameters</P>
<% } else { %>
<P>Parameters:</P>
<% while(enum.hasMoreElements()) { %>
parameter[ <%=i%>] =
<% pName=(java.lang.String)enum.nextElement(); %>
<%= pName %>
value = <%= request.getParameter(pName) %>
<BR>
<% i++ ; %>
<% } } %>
<BR><BR>
Thanks, for using <%= request.getServerName() %>
<BR>Your connection was from <%= request.getRemoteHost() %>@
<%= request.getRemoteAddr() %>
. </BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 24
J2EE JSP and Servlets
Output of example5.jsp
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 25
J2EE JSP and Servlets
Using an HTML Form to Call the JSP Page
example6.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FORM METHOD=POST BGCOLOR=#00FFFF ACTION="example5.jsp">
<TABLE BGCOLOR=#FFCC99 BORDER=1>
<TR>
<TD>First Name</TD>
<TD><INPUT TYPE="text" NAME="firstname"></TD></TR>
<TR>
<TD>Last Name</TD>
<TD><INPUT TYPE="text" NAME="lastname"></TD></TR>
<TR>
<TD>Job</TD>
<TD><INPUT TYPE="text" NAME="job"></TD></TR>
<TR>
<TD>Hobby</TD>
<TD><INPUT TYPE="text" NAME="hobby"></TD></TR>
<TR>
<TD colspan="2"><CENTER><INPUT TYPE="submit" VALUE=" Ok
"></CENTER></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 26
J2EE JSP and Servlets
Using the HTML Form
example6.html
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 27
J2EE JSP and Servlets
Result of the ACTION Element
After pressing the OK Button
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 28
J2EE JSP and Servlets
Using Beans in JSP Pages
Java Beans are simply Java objects
Can be used receive, hold and mange parameters sent from HTML Forms
Do processing behind the scenes of the JSP pages
JSP Syntax
<jsp:useBean
id="beanInstanceName"
scope="page | request | session | application"
{
class="package.class" |
type="package.class" |
class="package.class" type="package.class" |
beanName="{package.class | <%= expression %>}"
type="package.class"
}
{
/> |
> other elements </jsp:useBean>
}
Examples
<jsp:useBean id="cart" scope="session" class="session.Carts" />
<jsp:setProperty name="cart" property="*" />
<jsp:useBean id="checking" scope="session" class="bank.Checking" >
<jsp:setProperty name="checking" property="balance" value="0.0" />
</jsp:useBean>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 29
J2EE JSP and Servlets
Using Beans in JSP Pages
Scope of Beans
Page - You can use the Bean within the JSP page with the <jsp:useBean> element or
any of the page's static include files, until the page sends a response back to the client or
forwards a request to another file.
Request - You can use the Bean from any JSP page processing the same request, until a
JSP page sends a response to the client or forwards the request to another page. You can
use the request object to access the Bean, for example,
request.getAttribute(beanName) or with the <jsp:useBean> element.
Session - You can use the Bean from any JSP page in the same session as the JSP page
that created the Bean. The Bean exists across the entire session, and any page that
participates in the session can use it.
Application - You can use the Bean from any JSP page in the same application as the
JSP page that created the Bean. The Bean exists across an entire JSP application, and any
page in the application can use the Bean.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 30
J2EE JSP and Servlets
Using Beans in JSP Pages
JSP Class (Bean Client)
test1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE> A JSP page with declared variables </TITLE>
</HEAD>
<BODY BGCOLOR="#FFFF33">
<HR>
<jsp:useBean id="beanie" scope="request" class="mmm.JspBean1" />
<jsp:setProperty name="beanie" property="*"/>
Your name is:
<jsp:getProperty name="beanie" property="userName"/>
<BR>
Your Card Number is:
<jsp:getProperty name="beanie" property="cardNumber"/>
<HR>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 31
J2EE JSP and Servlets
Using Beans in JSP Pages
Simple Bean
Jspbean1.java
package mmm;
public class JspBean1 {
private String userName;
private String cardNumber;
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber; }
public String getCardNumber() {
return cardNumber; }
public void setUserName(String userName) {
this.userName = userName; }
public String getUserName() {
return userName; } }
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 32
J2EE JSP and Servlets
Calling the JSP Page from an HTML Page
jsptest1.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>Testing a JSP Bean</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FORM METHOD=GET ACTION="test1.jsp">
<TABLE BORDER="1" WIDTH="40%" BGCOLOR="#FEAA" >
<TR>
<TD>User Name: </TD>
<TD><INPUT TYPE="text" NAME="userName"></TD></TR>
<TR>
<TD>Card # </TD>
<TD><INPUT TYPE="text" NAME="cardNumber"></TD></TR>
<TR>
<TD>Register</TD>
<TD align="center"><INPUT TYPE="submit" VALUE="OK"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 33
J2EE JSP and Servlets
The Resulting Page
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 34
J2EE JSP and Servlets
Standard JSP Objects
request
This is the HttpServletRequest associated with the request, and lets you look at the
request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the
incoming HTTP headers (cookies, Referer, etc.).
response
This is the HttpServletResponse associated with the response to the client.
out
This is the PrintWriter used to send output to the client.
session
This is the HttpSession object associated with the request. Recall that sessions are
created automatically, so this variable is bound even if there was no incoming session
reference.
application
This is the global object associated with the entire application
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 35
J2EE JSP and Servlets
Variations of <jsp:setProperty ...>
<jsp:setProperty name="beanie" property="*">
All name-matched bean property and form parameters are set
non-matched, extra properties and/or parameters are ignored
<jsp:setProperty name="beanie" property="userName" value="
<%= request.getParameter("Name") %> ">
Property and parameter name need not agree
<jsp:setProperty name="beanie" property="xyz"/>
Property xyz in the bean has a same-name equivalent in the HTML form
<jsp:setProperty name="beanie" property="xyz" param="abc"/>
Property xyz in the bean is set to HTML form parameter abc
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 36
J2EE JSP and Servlets
 Database Connection With a JSP Bean
databaseTest.jsp:
<Table border=1 width="80%">
<TR><TH nowrap colspan = "9" bgcolor="#E6E6E6" ><FONT size="3"
COLOR="#CC0000">
My Query</TH>
</TR>
<jsp:useBean id="db" scope="request" class="lhcc.standard.DBBeanJSP" />
<% db.setUrl("jdbc:odbc:names"); %>
<% db.setQuery("select * from People"); %>
<% db.execSQL(); %>
<% String [][] rows2D = db.getRows2D(); %>
<TR>
<% for (int i = 0; i < rows2D[0].length; i++) { %>
<TH nowrap bgcolor="#FFFFC1" ><FONT size="3" COLOR="#CC0000">
<%= "&nbsp;&nbsp;" + rows2D[0][i] + "&nbsp;&nbsp;" %>
</TH>
<% ; } // end header i loop %>
</TR>
<% for (int i = 1; i < rows2D.length; i++) { %>
<TR>
<% for (int j = 0; j < rows2D[i].length; j++) { %>
<TD nowrap>
<%= "&nbsp;&nbsp;" + rows2D[i][j] + "&nbsp;&nbsp;" %>
</TD>
<% ; } // end j loop%>
</TR>
<% ; } // end i loop %>
<TR><TH nowrap colspan = "9" bgcolor="#E6E6E6" ><FONT size="3"
COLOR="#CC0000">
&nbsp;
</TH></TR>
</Table>
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 37
J2EE JSP and Servlets
Database Connection with a JSP Bean ( java bean code)
Be sure to place al the non-standard database drivers where your JSP engine can find
them.
constructor code:
public DBBeanJSP() {
// Load MS Access and Oracle Drivers
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.err.println("MS Access Driver Loaded");
//Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
// System.err.println("SQL Server Driver Loaded");
Class.forName ("oracle.jdbc.driver.OracleDriver");
System.err.println("Oracle Driver Loaded"); }
catch (ClassNotFoundException cnfe) {System.err.println("Driver Load Failure"); } }
execSQL() method code:
private String url = "jdbc:odbc:names";
private String user = "admin";
private String password = "secret";
public void execSQL() {
try {
con = DriverManager.getConnection (url, user, password);
stmt = con.createStatement ();
rs = stmt.executeQuery (query);
columnCount = rs.getMetaData().getColumnCount();
catch (SQLException ex) {
System.err.println ("\n*** SQLException caught ***\n");
error = ex.toString(); }
catch (java.lang.Exception ex) {
ex.printStackTrace ();
error = ex.toString(); } }
// execSQL()
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 38
J2EE JSP and Servlets
Database Connection with a JSP Bean ( java bean code)
DBBeanJSP - 4 selected methods:
public String [] getColumnNames() {
try{
int count = rs.getMetaData().getColumnCount();
String [] columnName = new String[count];
for(int i = 1; i <= count; i++)
columnName[i-1] = rs.getMetaData().getColumnName(i);
return columnName; }
catch (SQLException sqle) { return null; } }
public boolean moreData() {
if( rs == null)
return false;
try{
return rs.next();}
catch(SQLException sqle) { return false; } }
public String getError() {
return error; }
public String getColumn(String column) {
try {
return rs.getString(column); }
catch(SQLException sqle) { return "ERROR"; }}
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 39
J2EE JSP and Servlets
Database Connection with a JSP Bean ( java bean code)
DBBeanJSP - 1 selected method:
public String [][] getRows2D() {
ResultSetBean rsb = new ResultSetBean(rs, ResultSetBean.STRING_2D_ARRAY);
return rsb.getRows2D(); }
Note: This method calls the ResultSetBean constructor. The ResultSetBean has a 2-D
String array property called rows2D. The constructor calls a method
build2DUntaggedPagingStringBuffer()which sets the rows2D as follows. The forst row
is the set of headers for the query. Each next row holds the attributes for a detail line.
The ResultSetBean method build2DuntaggedPagingStringBuffer() listing is shown on
the next page.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 40
J2EE JSP and Servlets
Database Connection with a JSP Bean
ResultSet build2DUntaggedPagingStringBuffer()listing
private void build2DUntaggedPagingStringBuffer() {
Vector vector = new Vector();
String [] oneRow = null;
try {
if (rs == null) {
// System.out.println("rs = null");
throw new SQLException("ResultSet is NULL"); }
int cols = rs.getMetaData().getColumnCount();
oneRow = new String[cols];
String [] headers = new String[cols];
for (int i = 0; i < cols; i++) {
oneRow[i]= rs.getMetaData().getColumnLabel(i+1); }
vector.addElement(oneRow);
while (rs.next()) {
oneRow = new String[cols];
for (int j = 0; j < cols; j++) {
oneRow[j] = rs.getString(j+1); }
vector.addElement(oneRow); }}
catch (SQLException sqle) {
System.err.println("Error in ResultBean.build2DUntaggedPagingStringBuffer()");
rows2D = null;
return; }
rows2D = new String[vector.size()][];
for (int i = 0 ; i < rows2D.length; i++)
rows2D[i] = (String [])vector.elementAt(i); }
public String [][] getRows2D() {
return rows2D; }
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 41
J2EE JSP and Servlets
Result of the Database JSP
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 42
J2EE JSP and Servlets
JSP Exercises
1.
We need to add the names3.mdb MS Access database in Windows
System OBDC configuration
2.
Go to Control Panel -> Administrative Tools -> Data Sources (ODBC)
Press Add.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 43
J2EE JSP and Servlets
JSP Exercises
Select MS Access Driver. Press Finish.
The data source will ba called names. Press Select and browse to the
example 8\database\names3.mdb file. Choose it, the press OK. The database
is configured with ODBC.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 44
J2EE JSP and Servlets
JSP Exercises
3.
Now place the JSP file databaseTest.jsp in your web application
folder, webapps\mmm.
4.
Place the two bean files, DBBeanJSP.java and ResultSetBean.java in
the webapps\mmm\WEB-INF\classes folder.
5.
You need to compile the beans. Use command line as you place
yourself in the bean directory
C:\apache-tomcat-5.5.12\webapps\MMM\WEB-INF\classes>javac -d . *.java
C:\apache-tomcat-5.5.12\webapps\MMM\WEB-INF\classes>dir
Directory of C:\apache-tomcat-5.5.12\webapps\MMM\WEB-INF\classes
02/07/2006 05:55 PM <DIR>
.
02/07/2006 05:55 PM <DIR>
..
11/21/2005 11:00 PM
9,454 DBBeanJSP.java
02/07/2006 05:55 PM <DIR>
lhcc
11/15/2005 10:54 AM
6,817 ResultSetBean.java
2 File(s)
16,271 bytes
3 Dir(s) 35,718,684,672 bytes free
C:\apache-tomcat-5.5.12\webapps\MMM\WEB-INF\classes>
6.
Notice the compile has added the lhcc\standard packager folders
7.
You need to restart the Tomcat server. So kill the window running
startup.bat, and click that file again, to restart the server.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 45
J2EE JSP and Servlets
JSP Exercises
8.
Now open your IE browser and go to
http://localhost:8080/MMM/databaseTest.jsp
Your output should be similar to the one on page 301.
9.
Now modify line #11 to read
<% db.setQuery("select * from People where Last like 'D%'"); %>
Your IE response will look like
This completes the excercises
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 46
J2EE JSP and Servlets
Session Management
A session object is automatically created whenever a JSP page arrives
without a SessionID
The sessionID is passed by the client each time the same server is
accessed
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 47
J2EE JSP and Servlets
Java Servlets
Servlets are Java programs, and are a direct part of the application part of the
application.
They run in the space of the web application.
JSP pages are first translated to Servlets, then compiled and executed.
JSP pages usually have visual component, Servlets usually do not.
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 48
J2EE JSP and Servlets
Java Initializing Servlet
package mmm;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class InitServlet extends HttpServlet {
private String greeting = "VOID";
private Properties props = new Properties();
public void init(ServletConfig config) throws ServletException {
super.init(config);
String LOCATION = config.getInitParameter("location");
try { props.load(new FileInputStream( LOCATION + "conf.ini")); }
catch (FileNotFoundException fnfe) { System.out.println("File " + "conf.ini" + " Not
Found!");
fnfe.printStackTrace(); }
catch (IOException ioe) { }
ServletContext context = config.getServletContext();
context.setAttribute("DEVELOPER", "Julius Dichter(c) 2006");
context.setAttribute("FILE_PATH", props.getProperty("FILE_PATH"));
context.setAttribute("GREETING", props.getProperty("GREETING"));
context.setAttribute("APACHE_IP", props.getProperty("APACHE_IP"));
//MidnightThread midnight = new MidnightThread(context);
//midnight.setPriority(Thread.MAX_PRIORITY);
//midnight.start();
} // init
public void service(ServletRequest req, ServletResponse res) {
System.err.println("MMM System Running ..."); } }
J2EE JSP and Servlets
The material in this document must not be reproduced without the written consent of Julius Dichter
Julius Dichter © 2004, 2005
Page 49