Using Open Source in Java Projects Jay Sissom

  • Slides: 127
Download presentation
Using Open Source in Java Projects Jay Sissom jsissom@indiana. edu

Using Open Source in Java Projects Jay Sissom [email protected] edu

Agenda n n n Expectations Why Open Source Tools Overview Example Application Open Source

Agenda n n n Expectations Why Open Source Tools Overview Example Application Open Source Tools n n n Ant j. Relational Framework Struts j. Unit Summary

Expectations n n You will NOT be a pro on these tools in 3

Expectations n n You will NOT be a pro on these tools in 3 -1/2 hours! You will NOT learn Java today You will get an idea of how these tools can work in your environment You will take home a CD with a copy of all the libraries and samples we are using today

Why Use Open Source n Arguments Against Open Source n n n “No one

Why Use Open Source n Arguments Against Open Source n n n “No one to sue” “You get what you pay for” “No vendor support”

Why Use Open Source n Arguments For Open Source n n n Why re-invent

Why Use Open Source n Arguments For Open Source n n n Why re-invent the wheel? No $$$ expenditures Great support via internet (mostly) Source is available to review design You may be able to resolve problems faster than a vendor would

Open Source Tools Overview n n Ant – automated source code building tool (make

Open Source Tools Overview n n Ant – automated source code building tool (make for Java) j. Relational Framework – Object to database mapping framework j. Unit – Unit testing framework Struts – Model/View/Controller user interface framework

Other Open Source Tools n n Log 4 j - Logging Hsql – 100%

Other Open Source Tools n n Log 4 j - Logging Hsql – 100% Java relational database Tomcat – Web server, Servlet container Net. Beans – IDE for Java These are just the tip of the iceberg!

Example Application n Personal Address Book Application n n Lookup people in an LDAP

Example Application n Personal Address Book Application n n Lookup people in an LDAP directory (or database) Add personal notes for people Web based user interface Built with ant, using Struts and j. Relational Frameworks, tested with j. Unit Thanks to Southern Illinois University for the use of their LDAP directory for this example.

Example Application (continued) n Tools used in application n n Total Cost: $0 Sun

Example Application (continued) n Tools used in application n n Total Cost: $0 Sun JDK 1. 4. 1 j. Relational Framework 1. 7 Struts 1. 0. 2 Hsql Java database Log 4 j Logging Tomcat Servlet container Ant 1. 5 to build application j. Unit 3. 8. 1 for testing Net. Beans Java IDE (optional) LDAP directory (optional)

What is Ant? n n Tool to Build an application Similar to the make

What is Ant? n n Tool to Build an application Similar to the make utility on Unix systems Written in Java Configured using XML

What’s wrong with make? n n File format difficult to use Not platform independent

What’s wrong with make? n n File format difficult to use Not platform independent Relies on shell scripts for complex tasks that can be even LESS platform independent Starting a JVM is time consuming

Ant to the rescue n n Ant uses XML for the file format Ant

Ant to the rescue n n Ant uses XML for the file format Ant is a Java application The JVM starts once and is used for all tasks (unless you tell it not to) Complex tasks can be written in Java for operating system independence

Example Ant Build File <? xml version=“ 1. 0”? > <project name=“Simple Buildfile” default=“compile”

Example Ant Build File <? xml version=“ 1. 0”? > <project name=“Simple Buildfile” default=“compile” basedir=“. ”> <property name=“src. dir” value=“src”/> <property name=“classes. dir” value=“classes”/> <property name=“build. dir” value=“build”/> <target name=“prepare”> <mkdir dir=“${classes. dir}”/> <mkdir dir=“${build. dir}”/> </target> <target name=“compile” depends=“prepare” description=“Compile Code”> <javac srcdir=“${src. dir}” destdir=“${classes. dir”/> </target> <target name=“jar” depends=“compile” description=“Build JAR file”> <jar jarfile=“${build. dir}/output. jar” basedir=“$classses. dir”/> </target> <target name=“clean” description=“Clean compiled code”> <delete dir=“${build. dir}”/> <delete dir=“${classes. dir}”/> </target> <target name=“all” depends=“clean, jar” description=“Builds everything”/> </project>

Build file components - project n Provides: n n n Name of the project

Build file components - project n Provides: n n n Name of the project Default target to use if none are specified Base directory for project One per build file This component holds targets Example: <project name=“My Killer App” default=“compile”> … </project>

Build file components - target n n A target is one unit of work

Build file components - target n n A target is one unit of work A target contains one or more task A target can depend on other targets Example: <target name=“compile” depends=“prepare”> … </target>

Build file components - task n n A task actually does some work Each

Build file components - task n n A task actually does some work Each task takes it’s own set of parameters You can write your own tasks in Java if necessary Example tasks that come with ant: n mkdir, delete, javac, javadoc, jar, war, ear, cvs, mail, unzip

Build file components - task n Tasks that come in the optional. jar file

Build file components - task n Tasks that come in the optional. jar file n n n cab – create a. cab file csc – compile c# code ftp – ftp files junit – run junit tests rpm – builds a Linux rpm There are lots more!

Build file components – other n Property n A name-value pair n <property name=“build.

Build file components – other n Property n A name-value pair n <property name=“build. dir” value=“build”/> n Use ${build. dir} to reference it

Build file components - other n Path and File lists <path id=“classpath”> <fileset dir=“${lib.

Build file components - other n Path and File lists <path id=“classpath”> <fileset dir=“${lib. dir}”> <include name=“activation. jar”/> <include name=“serlvet. jar”/> </fileset> </path> <path id=“second_classpath”> <fileset dir=“${lib. dir}”> <include name=“**/*. jar”/> <exclude name=“junit. jar”/> </fileset> </path>

Running ant n Command line: n ant target n n ant –buildfilename target n

Running ant n Command line: n ant target n n ant –buildfilename target n n Used if your build file is named build. xml in the current directory Used if your build file isn’t named build. xml or in a different directory Run from within a supporting IDE

Example Program Directory Structure (root) src properties test ldap testclasses WEB-INF lib classes dist

Example Program Directory Structure (root) src properties test ldap testclasses WEB-INF lib classes dist javadoc

Example ant script – init target <target name="init"> <property file=". . /build. compile. ant.

Example ant script – init target <target name="init"> <property file=". . /build. compile. ant. properties"/> <property name="webapp" value="ldap"/> <property name="classes" value="${webapp}/WEB-INF/classes"/> <property name="lib" value="${webapp}/WEB-INF/lib"/> <property name="src" value="src"/> <property name="test" value="test"/> <property name="testclasses" value="testclasses"/> <property name="properties" value="properties"/> <property name="dist" value="dist"/> …

Example ant script – init target … <!--- Path to compile the application -->

Example ant script – init target … <!--- Path to compile the application --> <path id="compile. classpath"> <!-- Include all elements that Tomcat exposes to applications --> <pathelement location="${catalina. home}/common/classes"/> <fileset dir="${catalina. home}/common/lib"> <include name="*. jar"/> </fileset> <!-- Application specific lib files --> <fileset dir="${lib}"> <include name="**/*. jar"/> </fileset> </path> …

Example ant script – init target … <!-- Path to test the application -->

Example ant script – init target … <!-- Path to test the application --> <path id="test. classpath"> <path refid="compile. classpath"/> <pathelement location="${testclasses}"/> <pathelement location="${classes}"/> </path> </target>

Example ant script – compile target <target name="compile" depends="init" description="Compile"> <mkdir dir="${classes}"/> <javac debug="true"

Example ant script – compile target <target name="compile" depends="init" description="Compile"> <mkdir dir="${classes}"/> <javac debug="true" deprecation="true“ destdir="${classes}" srcdir="${src}"> <classpath refid="compile. classpath"/> </javac> </target>

Example ant script - testcompile <target name="testcompile" depends="compile“ description="Compile Tests"> <mkdir dir="${testclasses}"/> <javac debug="true"

Example ant script - testcompile <target name="testcompile" depends="compile“ description="Compile Tests"> <mkdir dir="${testclasses}"/> <javac debug="true" deprecation="true“ destdir="${testclasses}" srcdir="${test}"> <classpath refid="test. classpath"/> </javac> </target>

Example ant script - javadoc <target name="javadoc" depends="init" description="Javadoc"> <mkdir dir="apidoc"/> <javadoc destdir="apidoc" packagenames="edu.

Example ant script - javadoc <target name="javadoc" depends="init" description="Javadoc"> <mkdir dir="apidoc"/> <javadoc destdir="apidoc" packagenames="edu. *"> <sourcepath> <pathelement location="${src}"/> </sourcepath> <classpath refid="compile. classpath"/> </javadoc> </target>

Example ant script - dist <target name="dist" depends="init, compile“ description="Build Distribution File"> <mkdir dir="${dist}"/>

Example ant script - dist <target name="dist" depends="init, compile“ description="Build Distribution File"> <mkdir dir="${dist}"/> <jar jarfile="${dist}/ldap. war" basedir="${webapp}"> <exclude name="WEB-INF/lib/junit. jar"/> </jar> </target>

Example ant script - all <target name="all" depends="init, dist" description="Build everything. "> <echo message="Application

Example ant script - all <target name="all" depends="init, dist" description="Build everything. "> <echo message="Application built"/> </target>

Example ant script - test <target name="test" depends="init, compile, testcompile“ description="Junit tests"> <java fork="yes"

Example ant script - test <target name="test" depends="init, compile, testcompile“ description="Junit tests"> <java fork="yes" classname="junit. textui. Test. Runner“ taskname="junit" failonerror="true"> <arg value="edu. iu. uis. sit. ldapsearch. test. All. Tests"/> <classpath refid="test. classpath" /> </java> </target>

Example ant script - clean <target name="clean" depends="init" description="Clean all build products"> <delete dir="${classes}"/>

Example ant script - clean <target name="clean" depends="init" description="Clean all build products"> <delete dir="${classes}"/> <delete file="${dist}/ldap. war"/> <delete dir="apidoc"/> <delete dir="${dist}"/> <delete dir="${testclasses}"/> </target>

Ant Summary n Allows developers to build the application consistently no matter what environment,

Ant Summary n Allows developers to build the application consistently no matter what environment, operating system

j. Relational Framework (jrf) n n Open Source Framework Object/Database mapping Framework Automates most

j. Relational Framework (jrf) n n Open Source Framework Object/Database mapping Framework Automates most of SQL programming Tables look like objects to programmers

jrf Provides n Object-to-relational mapping for: n n n n n Sequenced primary keys

jrf Provides n Object-to-relational mapping for: n n n n n Sequenced primary keys Natural primary keys Compound primary keys Insertion of a new object instance into the database. Updating of existing object instances. Deleting of existing object instances. Finding of persistent instances by primary key. Finding all persistent instances. (Finding all rows in a table). Finding of a portion of persistent instances that match an application-specific criteria. Augmentation of persistent object instances with columns from other tables (Joining of tables).

jrf Provides n n n Aggregation - creation of multiple objects from one result

jrf Provides n n n Aggregation - creation of multiple objects from one result set. Flexibility to define custom SQL queries for specialized searches. Database independent validation of objects based on the metadata defined in the Abstract. Domain subclass. (i. e. REQUIRED and UNIQUE field constraints). Database independent defaulting of attribute values when updating and selecting from the database. Optimistic locking of an object/row using a Timestamp or Integer column. When conflicts occur, an Object. Has. Changed exception is thrown by the framework. Linking of related objects at retrieval time through the use of a post. Find() method.

jrf Provides n n Plenty of "hooks" by which you can customize your object

jrf Provides n n Plenty of "hooks" by which you can customize your object before saving, after finding, etc. . . Compatible with database triggers that change the tables. Generation of basic Persistent. Object and Abstract. Domain subclasses from an existing database (using the jrf-extras jar). Connection pooling (Either via the included JDBCHelper. Pool or via your application server pooling).

Object Mapping n Each RDBMS table is mapped to two objects n n Persistent

Object Mapping n Each RDBMS table is mapped to two objects n n Persistent Object (or Entity Object) which represents one row Domain Object which represents the entire table

Entity Object n n n Is a Java. Bean Has a property for every

Entity Object n n n Is a Java. Bean Has a property for every column in a table The setter method must contain a call to this. mark. Modified. Persistent. State(); Each property MUST be a Java Object, not a built in java type Parent object is com. is. jrf. Persistent. Object

Domain Object n n n n Represents an entire table Has a method to

Domain Object n n n n Represents an entire table Has a method to return lists of all rows Has a method to return a single row via the primary key Has a method to return a list of rows based on a specified where clause Has method to add, update or delete single row Parent object is com. is. jrf. Abstract. Domain A Domain object can have “hooks” for various events in the object lifecycle

JDBCHelper n n n JDBCHelper is the jrf class to wrap a JDBC driver

JDBCHelper n n n JDBCHelper is the jrf class to wrap a JDBC driver You’ll need to work with JDBCHelper any time you talk to the database JDBCHelpers will also let you manage database transactions

Creating a Domain Object n Create a subclass of com. is. jrf. Abstract. Domain

Creating a Domain Object n Create a subclass of com. is. jrf. Abstract. Domain n Implement a protected void setup() method which should n n n set the Database. Policy set the table name Add Column specs for each column

Creating a Domain Object n Override the new. Persistent. Object method and return a

Creating a Domain Object n Override the new. Persistent. Object method and return a new instance of your entity object

Column Specs n n Each column in the table needs to be defined in

Column Specs n n Each column in the table needs to be defined in the setup method of the Domain object There are Column. Spec objects for many different data types: n n n String. Column. Spec Integer. Column. Spec Long. Column. Spec

Column Specs n The constructor for a x. Column. Spec object needs the following

Column Specs n The constructor for a x. Column. Spec object needs the following parameters: n n n column name getter method name setter method name default value zero or more options

Column Specs – default value n Default Value constants n n n n DEFAULT_TO_NULL

Column Specs – default value n Default Value constants n n n n DEFAULT_TO_NULL DEFAULT_TO_EMPTY_STRING DEFAULT_TO_ZERO (Integer only) DEFAULT_TO_ONE (Integer only) DEFAULT_TO_NOW DEFAULT_TO_TRUE DEFAULT_TO_FALSE

Column Specs - options n Option constants n n n n SEQUENCED_PRIMARY_KEY NATURAL_PRIMARY_KEY OPTIMISTIC_LOCK

Column Specs - options n Option constants n n n n SEQUENCED_PRIMARY_KEY NATURAL_PRIMARY_KEY OPTIMISTIC_LOCK REQUIRED UNIQUE Max of 3 options Primary key options shouldn’t be used with other options (Required & Unique assumed)

Column Specs n The Domain object has a method called add. Column. Spec that

Column Specs n The Domain object has a method called add. Column. Spec that lets you add each Column Spec object this. add. Column. Spec(new String. Column. Spec(“user_nm”, ”get. User_nm”, ”set. User_nm”, DEFAULT_TO_EMPTY_STRING, REQUIRED)

Finders n n Finders allow you to retrieve lists of rows that meet certain

Finders n n Finders allow you to retrieve lists of rows that meet certain requirements jrf supplies a finder by primary key, a finder for all rows, and one for a where clause You’ll need to write additional ones Finder methods belong in the Domain object

Finders n Example Finders n n find. By. User. Nm(String user_nm) find. By. ID(Integer

Finders n Example Finders n n find. By. User. Nm(String user_nm) find. By. ID(Integer id) find. By. Account(String fin_coa_cd, String account_nbr) find. Names. Starting. With(String s)

Finders n n jrf provides a find. Where method Example find. By. User. Nm

Finders n n jrf provides a find. Where method Example find. By. User. Nm method public List find. By. User. Nm(String user_nm, JDBCHelper j) { String user = JDBCHelper. delimit. String(user_nm, ”’”); return this. find. Where(this. get. Table. Alias() + “. user_nm = ” + user, j); }

Order By n n Often we need to return data in a special order

Order By n n Often we need to return data in a special order jrf provides a find. Order. By method to find all with an ORDER BY clause jrf also provides a find. Where. Order. By method to find specified rows with an ORDER BY clause Pass a list of column names separated by commas for the order. By. String parameter

Locking n n Pessimistic locking – lock a row before modifying it just in

Locking n n Pessimistic locking – lock a row before modifying it just in case someone else will want to modify the row while we are Optimistic locking – Assume that no one will modify the row while we’re changing it and check if they did after the fact

Optimistic Locking n Method 1 n n Add a Timestamp column for each table

Optimistic Locking n Method 1 n n Add a Timestamp column for each table and update it for each UPDATE Grab the Timestamp from a row. Let the user modify the row, then specify the original Timestamp in the where clause

Optimistic Locking n Method 2 n n Add a version number column for each

Optimistic Locking n Method 2 n n Add a version number column for each table and increment it for each UPDATE Grab the version number from a row. Let the user modify the row, then specify the original version number in the where clause

Optimistic Locking n n Each table will have an NUMERIC(8) column named jrf_ver_nbr jrf

Optimistic Locking n n Each table will have an NUMERIC(8) column named jrf_ver_nbr jrf will automatically handle Optimistic Locking if we tell it to: this. add. Column. Spec(new Integer. Column. Spec("JRF_VER_NBR", "get. Jrf_ver_nb "set. Jrf_ver_nbr", DEFAULT_TO_ZERO, OPTIMISTIC_LOCK));

Optimistic Locking n n n We must provide a getter/setter for jrf_ver_nbr in the

Optimistic Locking n n n We must provide a getter/setter for jrf_ver_nbr in the Entity object jrf will throw an Object. Has. Changed. Exception if the object changes between the time you retrieve the data and update the data It’s up to you to determine how your application will react

Optimistic Locking n When you retrieve data from an Entity to be edited, you

Optimistic Locking n When you retrieve data from an Entity to be edited, you must make sure the jrf_ver_nbr gets retrieved maintained until you save it

Transactions n n n By default, each SQL command happens by itself Sometimes a

Transactions n n n By default, each SQL command happens by itself Sometimes a group of actions ALL need to happen or NONE happen Database Transactions allow us to support this functionality

Transactions n Example: Transfer money between two accounts n n n create table bc

Transactions n Example: Transfer money between two accounts n n n create table bc 2_account_t ( user_nm varchar 2(8) not null, account_nbr varchar(7) not null, balance_amt numeric(8) not null ); update jay_account_t set balance_amt = balance_amt – 10 where user_nm = ‘jsissom’ and account_nbr = ‘SAVING’ update jay_account_t set balance_amt = balance_amt + 10 where user_nm = ‘jsissom’ and account_nbr = ‘CHECK’ Both have to happen or neither have to happen

Transactions n Database managed transactions (by default): n n n begin transaction (implied) update

Transactions n Database managed transactions (by default): n n n begin transaction (implied) update jay_account_t set balance_amt = balance_amt – 10 where user_nm = ‘jsissom’ and account_nbr = ‘SAVING’ commit (implied) begin transaction (implied) update jay_account_t set balance_amt = balance_amt + 10 where user_nm = ‘jsissom’ and account_nbr = ‘CHECK’ commit (implied)

Transactions n Developer managed transactions: n n n begin transaction update jay_account_t set balance_amt

Transactions n Developer managed transactions: n n n begin transaction update jay_account_t set balance_amt = balance_amt – 10 where user_nm = ‘jsissom’ and account_nbr = ‘SAVING’ update jay_account_t set balance_amt = balance_amt + 10 where user_nm = ‘jsissom’ and account_nbr = ‘CHECK’ commit If the commit never happens, the database will rollback the transaction The developer can rollback the transaction if there is a problem

jrf Transactions n n By default, jrf will automatically begin transactions, commit transactions or

jrf Transactions n n By default, jrf will automatically begin transactions, commit transactions or rollback for each database operation by itself Each operation has it’s own transaction

jrf Transactions n n n Each database action in jrf can possibly use a

jrf Transactions n n n Each database action in jrf can possibly use a different connection to the database because connections come from the pool A transaction cannot span multiple connections To manage a transaction, you also need to manage the connection

jrf Transactions n Example jrf code without transactions: JDBCHelper jdbc. Helper = get. JDBCHelper();

jrf Transactions n Example jrf code without transactions: JDBCHelper jdbc. Helper = get. JDBCHelper(); checking. Account. set. Balance_amt(checking. Account. get. Balance_amt() try { Account n. Account 1 = a. Domain. save(checking. Account, jdbc. Helper); }… saving. Account. set. Balance_amt(saving. Account. get. Balance_amt()+10) try { Account n. Account 2 = a. Domain. save(saving. Account, jdbc. Helper); }… jdbc. Helper. close();

jrf Transactions n Example code WITH transactions: JDBCHelper jdbc. Helper = get. JDBCHelper(); jdbc.

jrf Transactions n Example code WITH transactions: JDBCHelper jdbc. Helper = get. JDBCHelper(); jdbc. Helper. begin. Transaction(); checking. Account. set. Balance_amt(checking. Account. get. Balance_amt try { Account n. Account 1 = a. Domain. save(checking. Account, jdbc. Helper); }… saving. Account. set. Balance_amt(saving. Account. get. Balance_amt()+10 try { Account n. Account 2 = a. Domain. save(saving. Account, jdbc. Helper); }… jdbc. Helper. end. Transaction(); jdbc. Helper. close();

jrf Transactions n n Oracle (and most other RDBMS’s) by default will “hide” any

jrf Transactions n n Oracle (and most other RDBMS’s) by default will “hide” any changes made within a transaction until the transaction is finished Other database connections won’t see these changes during the transaction

j. RF 2. 0 Beta n n n j. RF 2. 0 Beta is

j. RF 2. 0 Beta n n n j. RF 2. 0 Beta is out It is not 100% backwards compatible with 1. 7 Check http: //jrf. sourceforge. net for more information

j. RF Summary n j. RF is a good lightweight framework for mapping objects

j. RF Summary n j. RF is a good lightweight framework for mapping objects to tables

j. Unit n n Unit Tests are a series of tests that verify each

j. Unit n n Unit Tests are a series of tests that verify each component of your application j. Unit is a framework to help standardize these tests j. Unit can help automate tests so it is easy to see if a component works j. Unit can be integrated into ant

Why Unit Test? n n n Find bugs soon after code is written Save

Why Unit Test? n n n Find bugs soon after code is written Save other team members’ time Prove that finished code works Make future maintenance easier Example of how to use code

Unit testing goals n n n Each class has tests for all public methods

Unit testing goals n n n Each class has tests for all public methods Tests not only test successes, but also test failures Tests are organized so they are easy to run Tests are run often Each test is completely independent of other tests Each time a bug is found, write an additional test to check for that bug, then fix the bug

j. Unit Concepts n Test. Case – a series of related tests n n

j. Unit Concepts n Test. Case – a series of related tests n n n All the tests for an object All the tests for a method Test. Suite – a series of related test cases n n All tests for a package All tests for an application

j. Unit Concepts n Fixtures – routines that setup the environment for each test

j. Unit Concepts n Fixtures – routines that setup the environment for each test n n n Create database connections Initialize the environment Test. Runner – j. Unit code that runs tests n n Command line Swing

j. Unit Addons n n Dbunit – code to initialize a database to a

j. Unit Addons n n Dbunit – code to initialize a database to a known state before testing Struts test case – Test Struts specific code using mock objects Cactus – Test HTTP applications using mock objects Http. Unit – Test HTTP applications based on an embedded servlet container

Writing j. Unit tests 1. 2. 3. 4. Subclass junit. framework. Test. Case Create

Writing j. Unit tests 1. 2. 3. 4. Subclass junit. framework. Test. Case Create a constructor with a single String parameter. Call super(string) in this constructor Write tests in methods that return void and start with test as their name Call fail, assert. X in tests as necessary

Test success/failure n assert. X methods test for the correct values. Examples: n n

Test success/failure n assert. X methods test for the correct values. Examples: n n assert. True/assert. False assert. Null/assert. Not. Null assert. Equals Fail method stops the test and marks it as a failure

Test success/failure n n The assert. X and fail methods will take an optional

Test success/failure n n The assert. X and fail methods will take an optional string to describe the test I recommend you ALWAYS use this string to document the tests

Example test /** * Test searching for someone that doesn't exist **/ public void

Example test /** * Test searching for someone that doesn't exist **/ public void test. Get. Person 1() { try { Business. Logic. Int bli = Business. Logic. Factory. get. Instance(get. Implementation. Class()); Person p = bli. get. Person("Unknown"); assert. Null("Unknown person should be null", p); } catch (Exception e) { fail(e. get. Message()); } }

j. Unit Example n Look at example program

j. Unit Example n Look at example program

j. Unit Summary n n j. Unit helps you create higher quality software Time

j. Unit Summary n n j. Unit helps you create higher quality software Time spent by writing tests will be recovered many times over during future maintenance

What is Struts? n n Open Source Framework User Interface Framework based on Model.

What is Struts? n n Open Source Framework User Interface Framework based on Model. View-Controller model (MVC or Model 2) Part of the Jakarta project sponsored by the Apache Group We will talk about Struts 1. 0. 2. 1. 1 b 2 has been released with many new features

Why use Struts n n Consistency across applications Split up HTML from Java code

Why use Struts n n Consistency across applications Split up HTML from Java code Make Maintenance of applications easier Take advantage of code in the framework

What is Struts?

What is Struts?

Struts Components n n n n Struts Servlet Action Object (Controller) Form Object (Model)

Struts Components n n n n Struts Servlet Action Object (Controller) Form Object (Model) JSP Page (View) Tag Libraries Configuration File Application Resources

Struts Servlet n n n “Traffic Cop” for application Routes requests to appropriate object

Struts Servlet n n n “Traffic Cop” for application Routes requests to appropriate object Configuration comes from configuration file (struts-config. xml)

Action Object (Controller) n n Action objects handle every request Each request type should

Action Object (Controller) n n Action objects handle every request Each request type should have an action object These are NOT Servlets They are called by the Struts Servlet

Form Object (Model) n n n Form objects store state information Data can be

Form Object (Model) n n n Form objects store state information Data can be passed from action objects (controllers) to JSP’s (views) and back Form objects are Java. Beans

JSP Page (View) n n JSP Pages contain all the HTML They use Form

JSP Page (View) n n JSP Pages contain all the HTML They use Form objects to display data HTML Forms put their data into Form objects Tag Libraries contain lots of functionality you can use

Tag Libraries n n Struts comes with many tags These tags allow you to

Tag Libraries n n Struts comes with many tags These tags allow you to n n n manipulate form beans provide i 18 n have conditional parts of page iterate through lists of data You can add your own tag libraries also Look at the JSTL – Java Standard Tag Library

Configuration File n n Allows the developer to define the flow of an application

Configuration File n n Allows the developer to define the flow of an application declaratively instead of in the code The flow of an application can be changed without recompiling code

Application Resources n n An application resources file can contain all of the messages

Application Resources n n An application resources file can contain all of the messages that appear in your application This file can be translated into other languages to provide i 18 n support Helps in writing documentation and making messages consistent This file goes where your Java source code goes – it goes in a package

Application Resources n Sample File: Variable application. title=My Application group. error=The group {0} is

Application Resources n Sample File: Variable application. title=My Application group. error=The group {0} is invalid error. username. missing=You must type in a username error. password. missing=You must type in a password username. message=Username: password. message=Password: submit. button. message=Save

Tag Libraries n n n struts-bean – Define new beans, render beans/properties struts-html –

Tag Libraries n n n struts-bean – Define new beans, render beans/properties struts-html – Create forms struts-logic – Conditional page generation, looping

Using Struts Tag Libraries Insert these lines at the beginning of each. JSP that

Using Struts Tag Libraries Insert these lines at the beginning of each. JSP that will use these tag libraries <%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-bean. tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-html. tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-logic. tld" prefix="logic" %>

struts-bean n Contains tags that n n manipulate the servlet context environment write out

struts-bean n Contains tags that n n manipulate the servlet context environment write out bean information to page include/forward Display messages from our resources file

struts-bean Properties n n id – Name of scripting variable and scope key value

struts-bean Properties n n id – Name of scripting variable and scope key value name – Scope key value property – Java. Beans property name scope – Where to store or search for bean (page, request, session or application)

struts-bean <bean: message> n Display a message from the Message Resources <bean: message key=“application.

struts-bean <bean: message> n Display a message from the Message Resources <bean: message key=“application. name”/>

struts-bean <bean: write> n Print out a bean or bean property <bean: write name=“person”

struts-bean <bean: write> n Print out a bean or bean property <bean: write name=“person” property=“last. Name”/> <bean: write name=“username”/>

struts-html n Contain tags that n n handle form HTML elements handle re-writing HREF’s

struts-html n Contain tags that n n handle form HTML elements handle re-writing HREF’s display User Interface errors deal with user’s locales

struts-html <html> n Looks at browser’s locale setting and enables i 18 n based

struts-html <html> n Looks at browser’s locale setting and enables i 18 n based on user’s locale. <html: html locale=“true”>

struts-html <html: errors> n n Displays a single or all error messages saved in

struts-html <html: errors> n n Displays a single or all error messages saved in the servlet context Action object/Form object can add errors as necessary <html: errors/> <html: errors property=“username”/>

struts-html <html: form> n n n Start an HTML form where all input is

struts-html <html: form> n n n Start an HTML form where all input is sent to a Form object Uses Java. Script to set focus to first field (optional) POSTS or GETS to an action in strutsconfig. xml <html: form focus=“username” action=“/login. do”>

struts-html n Form Input tags n n n n button cancel checkbox hidden multibox

struts-html n Form Input tags n n n n button cancel checkbox hidden multibox options password radio reset select submit textarea All of these are just like their HTML counterparts with a property attribute that work with a Form. Bean

struts-html <html: link> n n Create <a href> and handle url rewriting Use to

struts-html <html: link> n n Create <a href> and handle url rewriting Use to provide links to locations within your application <html: link page=“/edit. Vendor. do”> <bean: message key=“vendor. edit”/> </html: link>

struts-logic n Contains tags that n n n Compare values Iterate Conditionally include parts

struts-logic n Contains tags that n n n Compare values Iterate Conditionally include parts of pages

struts-logic - Comparison n n equal, not. Equal greater. Equal, less. Equal greater. Than,

struts-logic - Comparison n n equal, not. Equal greater. Equal, less. Equal greater. Than, less. Than Compare a value to a cookie, header, property or name <logic: equal value=“en_US” header=“Accept-Language”> You speak English, dude! </logic: equal>

struts-logic - Exists n n n exists, not. Exists Tests if objects exist in

struts-logic - Exists n n n exists, not. Exists Tests if objects exist in page, request, session or application state Tests if a cookie exists <logic: not. Present name="org. apache. struts. action. ERROR"> <bean: message key=“message. noerrors"/> </logic: not. Present> <logic: present name="org. apache. struts. action. ERROR"> <B><html: errors/></B> </logic: present>

struts-logic – Substring Matching n n match, not. Match on substrings <logic: match header=“Referer”

struts-logic – Substring Matching n n match, not. Match on substrings <logic: match header=“Referer” value=“myiu. edu”> I’m glad you use the Portal to access this application! </logic: match> <logic: not. Match header=“Referer” value=“myiu. edu”> Next time, try to access this app via the Portal! </logic: not. Match>

struts-logic - iterate n Iterate through a list of items <logic: iterate id="my. Element"

struts-logic - iterate n Iterate through a list of items <logic: iterate id="my. Element" name="list"> <bean: write name="my. Element"/><br/> </logic: iterate>

Struts Configuration n n Configuration in XML file Sections of file n n data-sources

Struts Configuration n n Configuration in XML file Sections of file n n data-sources – JDBC Database sources form-beans – list of all form beans used in app global-forwards – list of forwards used throughout application action-mappings – list of all actions and how they map to views/forms

Action Mappings n Each action object needs to have an entry in the struts

Action Mappings n Each action object needs to have an entry in the struts config file <!-- Add Members --> <action path="/Add. New. Member" type="edu. iu. uis. sit. test. Add. Member. Action" <!– List Members --> name="Member. Form" <action path="/List. Members" scope="request“ type="edu. iu. uis. sit. test. List. Members. Actio input="Add. Member. jsp" validate="true"> <forward name="success" path="index. jsp"/> </action> Input/Edit Form List Rows Form

Action Definitions n n n n path – path of submitted request type –

Action Definitions n n n n path – path of submitted request type – Java class of Action object to call forward/include – path of servlet or JSP that will handle this request name – Name of form bean to use input – Path to input form in case of errors scope –area to be used form bean (“request” or “session”) validate – true/false – Validate form bean Bold - Required

Action Forwards n A forward is a logical definition of a path <forward name="success“

Action Forwards n A forward is a logical definition of a path <forward name="success“ path="index. jsp"/> • name = logical name • path = path to go to Your Action Object can refer to the logical name to transfer control. You don’t have to hardcode a destination path in your source code. return (mapping. find. Forward(“success"));

Action Forwards n Example – Wizard Interface n n If user presses Previous button,

Action Forwards n Example – Wizard Interface n n If user presses Previous button, go to previous screen If user presses Next button, go to next screen <forward name=“previous“ path=“page 1. jsp"/> <forward name=“next” path=“page 3. jsp”/>

Form Objects n Each form object needs to have an entry in the struts

Form Objects n Each form object needs to have an entry in the struts config file <form-bean name="Person. Form" type="edu. iu. uis. html 1. Person. Form"/>

Global Forwards n n Forwards that are used throughout your application Example: main menu

Global Forwards n n Forwards that are used throughout your application Example: main menu <global-forwards> <forward name="logoff" path="/logoff. do" /> <forward name="logon" path="/logon. jsp" /> <forward name=“menu" path="/main. Menu. jsp" /> </global-forwards> return (servlet. find. Forward(“menu"));

Before Calling the Action Object n The Struts Servlet will: n n Check in

Before Calling the Action Object n The Struts Servlet will: n n Check in the user’s session for an instance of a form bean listed in struts-config. xml If it doesn’t exist, create one Call the setter for each property that matches a form input field Pass the form bean to the perform method

Action Objects n n n Receives requests from client Runs appropriate business logic forwards

Action Objects n n n Receives requests from client Runs appropriate business logic forwards to view (JSP) for display

Application Architecture struts-config. xml Browser Struts Servlet BL Controllers Action Object Form Object Entities

Application Architecture struts-config. xml Browser Struts Servlet BL Controllers Action Object Form Object Entities Domains JSP Application. Resources Tag Libraries

Tiers UI Tier BL Tier Data Tier Action Form JSP Domain Boundary Controller Entity

Tiers UI Tier BL Tier Data Tier Action Form JSP Domain Boundary Controller Entity

Struts 1. 1 beta n New Features n n n Multiple struts-config. xml files

Struts 1. 1 beta n New Features n n n Multiple struts-config. xml files Dynamic beans Declarative exception handling Validation framework Tiles framework

Struts Summary n n Struts will save time as an application gets complex Struts

Struts Summary n n Struts will save time as an application gets complex Struts will save time in maintenance

Summary n By 2003, the use of open-source software will become a standard part

Summary n By 2003, the use of open-source software will become a standard part of all organizations utilizing Java… - Thomas Murphy METAgroup. com

Books

Books

Resources n n Ant – http: //jakarta. apache. org/ant Jrf – http: //jrf. sourceforge.

Resources n n Ant – http: //jakarta. apache. org/ant Jrf – http: //jrf. sourceforge. net/ j. Unit – http: //www. junit. org/ Struts – http: //jakarta. apache. org/struts

Other Resources n n n n Tomcat – http: //jakarta. apache. org/tomcat Hsql –

Other Resources n n n n Tomcat – http: //jakarta. apache. org/tomcat Hsql – http: //sourceforge. net/projects/hsqldb/ Log 4 j – http: //jakarta. apache. org/log 4 j Net. Beans – http: //www. netbeans. org/ Dbunit – http: //dbunit. sourceforge. net/ Struts test case – http: //strutstestcase. sourceforge. net/ HTTP Unit – http: //httpunit. sourceforge. net/ Cactus – http: //jakarta. apache. org/cactus

Q&A ?

Q&A ?