Part X



JSPs and Servlets

____________________________________

The Simplest JSP is a Plain HTML Page

example0.jsp

New Document

Welcome to Java JSP

Do you speak Java?

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

[pic]

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.

[pic]

Apache Tomcat Web Server Installation (continued)

11. To Test our system, open a command window (Run, cmd)

[pic]

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.

[pic]

Apache Tomcat Web Server Installation (continued)

14. To test if we were successful, open Internet Explorer (IE) and type the following address:



15. A successful install will give the following view

[pic]

This completes the install

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

JSP Exercises

1. Move the example0.jsp and duke.gif files into the mmm folder.

2. Open IE, and go to

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.

Types of JSP Statements

Declaration

Declares a variable valid in the scripting language used in the JSP page.

JSP Syntax

XML Syntax

   declaration; [ declaration; ]+ ...

Examples

Types of JSP Statements

Expression

Contains an expression valid in the scripting language used in the JSP page.

JSP Syntax

XML Syntax

   expression

Examples

The map file has entries.

Good guess, but nope. Try

numguess.getHint().

Types of JSP Statements

Scriptlet

JSP Syntax

XML Syntax

   code fragment

Examples

Using Declarations, Expressions and Scriptlets

This simple JSP uses 3 types of JSP statements

JSP Exercises

1. Copy example1.jsp into your web application folder, webapps\mmm.

2. Call up this JSP page from IE

[pic]

3. Add the following two scriptlets at the end of example1.jsp.

4. Determine where the output is going. Check your code against the example1/solution folder if needed.

This completes the excercises

Importing Classes and Packages in JSP

Either syntax can be used to import either classes or entire packages

JSP include tag

Static include

The include directive

Reads the source of the included file into the current jsp page as a translation time activity

Dynamic include

The include tag

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.

JSP Exercises

1. Copy example2.jsp into your web application folder, webapps\mmm.

2. Call up this JSP page from IE. You should see

[pic]

3. Now add a dynamic include of the example1.jsp page between the two output lines. Call up the page again. You should see

[pic]

4. Check your code against the example2/solution folder if needed.

This completes the excercises

A Basic JSP Page with a Loop

example3.jsp

A JSP page with declared variables

i = .

j = .

k =

m =

Today is

Output of example3.jsp

[pic]

Including another Page: example3solution.jsp

Note the include directive,

Static translation time activity

A JSP page with declared variables

i = .

j = .

k =

m =

Today is

Output of example3solution.jsp

[pic]

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

Do you speak French? instead of

Do you speak Java?

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

Integrating JSP with HTML

example4.jsp

I Love jsp

I Love jsp

Output of example4.jsp

[pic]

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



Normally the parameters are taken from the HTML Form element

[pic]

Passing Parameters to JSP Pages

Here is the URI used to call the page



example5.jsp

Output of example5.jsp

[pic]

Using an HTML Form to Call the JSP Page

example6.html

Using the HTML Form

example6.html

[pic]

Result of the ACTION Element

After pressing the OK Button

[pic]

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

|

            > other elements

        }

Examples

Using Beans in JSP Pages

Scope of Beans

Page - You can use the Bean within the JSP page with the 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 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.

Using Beans in JSP Pages

JSP Class (Bean Client)

test1.jsp

Using Beans in JSP Pages

Simple Bean

Jspbean1.java

Calling the JSP Page from an HTML Page

jsptest1.html

[pic]

The Resulting Page

[pic]

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

Variations of

All name-matched bean property and form parameters are set

non-matched, extra properties and/or parameters are ignored

Property and parameter name need not agree

Property xyz in the bean has a same-name equivalent in the HTML form

Property xyz in the bean is set to HTML form parameter abc

• Database Connection With a JSP Bean

databaseTest.jsp:

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:

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()

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 Administrative Tools -> Data Sources (ODBC)

[pic]

Press Add.

JSP Exercises

Select MS Access Driver. Press Finish.

[pic]

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.

[pic]

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

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.

JSP Exercises

8. Now open your IE browser and go to



Your output should be similar to the one on page 301.

9. Now modify line #11 to read

Your IE response will look like

[pic]

This completes the excercises

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

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.

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 ..."); } }

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 .

02/07/2006 05:55 PM ..

11/21/2005 11:00 PM 9,454 DBBeanJSP.java

02/07/2006 05:55 PM 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>

Testing a JSP Bean

User Name:

Card #

Register

public String [][] getRows2D() {

return rows2D; }

private String url = "jdbc:odbc:names";

private String user = "admin";

private String password = "secret";

My Query

 

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; } }

A JSP page with declared variables

Your name is:

Your Card Number is:

First Name

Last Name

Job

Hobby

Sorry, No Parameters

Parameters:

parameter[ ] =

value =

Thanks, for using

Your connection was from @

.

java.util.Vector vector = new java.util.Vector();

double amount;

Today is

date.

My Vector has elements.

My Vector now has elements.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download