Advance Java Frame Work
Advance Java Frame Work
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
1/298
Document History
Date Version By Remarks
29 March. 2010 1.00 Swe Zin Hlaing Day 1
Nay Zar Chi Htoo Day 2 to 8
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
2/298
Contents at a Glance
1. Quick view of Fundamental Java <Day 1> .................................................................. 11
2. Web Application <Day 2-1> ......................................................................................... 51
Servlet <Day 2-2> ............................................................................................................... 87
3. JSP <Day 3> ............................................................................................................. 104
4. JDBC <Day 4>........................................................................................................... 130
5. J2EE architecture <Day 5> ........................................................................................ 153
6. Framework; Apache Struts <Day6>........................................................................... 171
7. Framework; Spring and Hibernate<Day 7> ............................................................... 209
8. Framework Application Development<Day 8>........................................................... 243
Tables and Figures ........................................................................................................... 293
Indexes ............................................................................................................................. 297
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
3/298
Table of Contents
1. Quick view of Fundamental Java <Day 1> .................................................................. 11
1.1. Introduction to Java .............................................................................................. 11
1.1.1. What is Java? ................................................................................................ 11
1.1.2. Starting with HelloWorld Program ................................................................. 11
1.1.3. Create a program .......................................................................................... 13
1.1.4. HelloWorld Program with Eclipse .................................................................. 14
1.2. Useful Packages and Data Structures .................................................................. 15
1.2.1. Array .............................................................................................................. 15
1.2.2. String ............................................................................................................. 17
1.2.3. Wrappers ....................................................................................................... 18
1.2.4. Collection ...................................................................................................... 19
1.2.5. Date............................................................................................................... 23
1.3. Flow Control ......................................................................................................... 27
1.3.1. if, elseif and else statements ......................................................................... 27
1.3.2. Switch statement ........................................................................................... 28
1.3.3. For loop ......................................................................................................... 29
1.3.4. While loop ..................................................................................................... 33
1.3.5. Do loop .......................................................................................................... 33
1.4. Exception; try{...} catch {...} finally {...} block......................................................... 34
1.4.1. Try, catch block ............................................................................................. 35
1.4.2. Throws .......................................................................................................... 35
1.4.3. Throwing exception ....................................................................................... 36
1.5. Class and Object .................................................................................................. 37
1.5.1. What is an object? ......................................................................................... 37
1.5.2. What is class? ............................................................................................... 38
1.5.3. Package ........................................................................................................ 39
1.5.4. Instance ......................................................................................................... 40
1.5.5. Constructor .................................................................................................... 42
1.5.6. Overloading ................................................................................................... 43
1.5.7. Inheritance .................................................................................................... 43
1.5.8. Abstract Class ............................................................................................... 44
1.5.9. Interface ........................................................................................................ 45
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
4/298
1.5.10. Overriding ...................................................................................................... 45
1.5.11. Polymorphism................................................................................................ 47
Exercise 1 – HelloWorld .................................................................................................. 47
2. Web Application <Day 2-1> ......................................................................................... 51
2.1. Characteristics of Java Web Application .............................................................. 51
2.1.1. A static web page .......................................................................................... 51
2.1.2. What a Web server can do and can not do? ................................................. 53
2.1.3. A dynamic web page ..................................................................................... 53
2.1.4. What is Web Application ............................................................................... 54
2.2. Servlet .................................................................................................................. 54
2.2.1. What is Servlet .............................................................................................. 54
2.2.2. What is the difference between CGI and Servlet ........................................... 55
2.2.3. Example code of HelloServlet ....................................................................... 56
2.2.4. What is JSP(Java Server Pages) .................................................................. 57
2.2.5. What is JavaScript......................................................................................... 57
2.2.6. What do you need for Servlet ........................................................................ 58
2.2.7. How to call Servlet......................................................................................... 58
2.2.8. What do you need for Servlet development .................................................. 58
2.2.9. How to develop Servlet ................................................................................. 59
2.3. Tomcat ................................................................................................................. 59
2.3.1. How to install Tomcat .................................................................................... 59
2.3.2. Tomcat configuration files ............................................................................. 60
2.3.3. Tomcat Common Library ............................................................................... 62
2.3.4. How to install Tomcat in Suse 11.2 ............................................................... 62
2.3.5. How to start Tomcat server in Suse 11.2 ...................................................... 63
2.3.6. How to stop Tomcat server in Suse 11.2 ....................................................... 64
2.3.7. Tomcat directory structure ............................................................................. 65
2.3.8. Install Sysdeo Eclipse Tomcat Launcher plugin in Suse 11.2 ....................... 65
Exercise 2 – Hello Servlet ............................................................................................... 73
Servlet <Day 2-2> ............................................................................................................... 87
2.4. Servlet mechanism ............................................................................................... 87
2.4.1. How Servlet works with web server ............................................................... 87
2.4.2. Servlet instance mechanism ......................................................................... 88
2.4.3. Servlet life cycle ............................................................................................ 89
2.4.4. Instance variables ......................................................................................... 90
2.5. Get/Post method .................................................................................................. 90
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
5/298
2.5.1. HTTP Get method ......................................................................................... 90
2.5.2. HTTP Post method ........................................................................................ 91
2.6. Servlet parameters ............................................................................................... 91
2.6.1. Servlet parameter mechanism....................................................................... 91
2.7. Servlet initialization parameters ............................................................................ 94
2.7.1. ServletConfig and ServletContext ................................................................. 94
2.7.2. How to configure the web.xml file .................................................................. 95
2.8. How to forward the request and response ............................................................ 95
2.8.1. What is Dispatch? ......................................................................................... 95
2.8.2. How to send HTML document from Servlet? ................................................. 96
2.9. Session................................................................................................................. 96
2.9.1. What is session? ........................................................................................... 96
2.9.2. Mechanism of session control ....................................................................... 98
2.9.3. How to use session data ............................................................................... 99
Exercise 3 – Servlet programming ................................................................................ 102
3. JSP <Day 3> ............................................................................................................. 104
3.1. What is JSP ........................................................................................................ 104
3.1.1. What is the difference between Servlet and JSP?....................................... 104
3.1.2. JSP flow ...................................................................................................... 105
3.1.3. What do you need for JSP .......................................................................... 106
3.1.4. How to call JSP ........................................................................................... 106
3.1.5. How to develop JSP .................................................................................... 106
3.1.6. How to write JSP ......................................................................................... 107
3.1.7. Components of JSP .................................................................................... 107
3.2. JSP grammar ..................................................................................................... 108
3.2.1. JSP comment .............................................................................................. 108
3.2.2. Scripting elements: Declarations ................................................................. 109
3.2.3. Scripting elements: Expression ................................................................... 109
3.2.4. Scripting elements: Scriptlet ........................................................................ 109
3.2.5. Directive: page directive .............................................................................. 110
3.2.6. Directive: include ......................................................................................... 111
3.2.7. Implicit object............................................................................................... 112
3.2.8. Standard action ........................................................................................... 113
3.3. JSTL (Java Server Pages Standard Tag Library) ............................................... 120
3.3.1. What is Tag Library ..................................................................................... 120
3.3.2. How to install JSTL...................................................................................... 121
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
6/298
3.3.3. How to work with JSTL ................................................................................ 122
3.3.4. Expression Language.................................................................................. 124
Exercise 4 – JSP programming ..................................................................................... 127
4. JDBC <Day 4>........................................................................................................... 130
4.1. JDBC .................................................................................................................. 130
4.1.1. What is JDBC .............................................................................................. 130
4.1.2. JDBC version and functionalities ................................................................. 130
4.1.3. How to install JDBC..................................................................................... 131
4.2. JDBC types ........................................................................................................ 131
4.2.1. Type1: JDBC-ODBC bridge ........................................................................ 131
4.2.2. Type2: Native Bridge ................................................................................... 132
4.2.3. Type3: Net protocol driver ........................................................................... 133
4.2.4. Type4: Native protocol driver ...................................................................... 134
4.3. How to connect to a database ............................................................................ 135
4.3.1. Load the JDBC driver .................................................................................. 135
4.3.2. URL String ................................................................................................... 135
4.3.3. DataSource ................................................................................................. 136
4.3.4. DataSource setting with Tomcat 5.X and Tomcat6.X .................................. 137
4.4. How to retrieve and modify data ......................................................................... 140
4.4.1. SQL ............................................................................................................. 140
4.4.2. executeQuery method ................................................................................. 140
4.4.3. How to modify data: executeUpdate............................................................ 142
4.4.4. Close the connection ................................................................................... 142
4.4.5. PreparedStatement ..................................................................................... 143
4.4.6. JDBC transaction ........................................................................................ 143
4.4.7. Scrollable cursor.......................................................................................... 145
4.4.8. Programmable update ................................................................................. 145
4.4.9. Batch updates ............................................................................................. 148
Exercise 5 – JDBC programming .................................................................................. 150
5. J2EE architecture <Day 5> ........................................................................................ 153
5.1. Application architecture ...................................................................................... 153
5.1.1. What is application architecture................................................................... 153
5.1.2. Multi Tiers design pattern of J2EE............................................................... 154
5.2. MVC architecture ................................................................................................ 157
5.2.1. What is MVC architecture ............................................................................ 157
5.2.2. Structure of MVC ......................................................................................... 157
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
7/298
5.2.3. Why MVC architecture ................................................................................ 158
5.2.4. Example of MVC application ....................................................................... 161
Exercise 6 – J2EE ......................................................................................................... 169
6. Framework; Apache Struts <Day6>........................................................................... 171
6.1. What is Struts Framework .................................................................................. 171
6.1.1. What is framework....................................................................................... 171
6.1.2. What is Struts .............................................................................................. 171
6.2. How Struts works................................................................................................ 172
6.2.1. How to set the Struts framework to your Web application ........................... 172
6.2.2. Mechanism of Struts framework .................................................................. 173
6.2.3. HelloWorld with Struts ................................................................................. 174
6.3. Struts Custom Tag.............................................................................................. 183
6.3.1. HTML Tag Library ....................................................................................... 184
6.3.2. Bean Tag Library ......................................................................................... 192
6.3.3. Logic Tag Library......................................................................................... 195
6.4. Struts Validation ................................................................................................. 198
6.4.1. Validate method .......................................................................................... 198
6.4.2. Struts Validator ............................................................................................ 201
Exercise 6: Apache Struts ............................................................................................. 207
7. Framework; Spring and Hibernate<Day 7> ............................................................... 209
7.1. What is Spring Framework ................................................................................. 209
7.1.1. How to install Spring.................................................................................... 209
7.2. Spring DI Container ............................................................................................ 209
7.2.1. What is DI Container ................................................................................... 209
7.2.2. Why DI Container ........................................................................................ 216
7.2.3. Spring Bean Factory.................................................................................... 216
7.3. Spring + Struts in Web Application ..................................................................... 217
7.3.1. Spring + Struts using DelegationActionProxy class..................................... 217
7.3.2. Sample program .......................................................................................... 218
7.4. Spring + Hibernate ............................................................................................. 224
7.4.1. What is O/R Mapping .................................................................................. 224
7.4.2. What is Hibernate ........................................................................................ 224
7.4.3. How to use Hibernate .................................................................................. 226
7.4.4. Sample Program of Spring + Hibernate....................................................... 231
Exercise 7: Spring + Hibernate ..................................................................................... 241
8. Framework Application Development<Day 8>........................................................... 243
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
8/298
8.1. Simplified Application Development ................................................................... 243
8.2. Designing and Creating the Database ................................................................ 243
8.2.1 Creating the database ...................................................................................... 243
8.3. Downloading the required software and integration into web application ........... 246
8.3.1 Setting up Development Directory ............................................................... 246
8.4. Creating hibernate mapping class by using Hibernate Synchronizer ................. 254
8.5. Login Specificaton .............................................................................................. 263
8.6. System Structure for Login Function .................................................................. 264
8.6.1. Project Structure.......................................................................................... 264
8.7. Developing Login Function ................................................................................. 265
8.7.1. Table Creation for Staff Login Function ....................................................... 265
8.7.2. Hibernate Configuration for Staff ................................................................. 265
8.7.3. DAO and DAO Implementation for Login Function ...................................... 271
8.7.4. Database Properties Creation ..................................................................... 272
8.7.5. Action-Servlet XML File for connecting the database .................................. 272
8.7.6. Web-Constant File Creation ........................................................................ 274
8.7.7. Check! ......................................................................................................... 275
8.7.8. Prepare Dao Test ........................................................................................ 275
8.7.9. Check! ......................................................................................................... 275
8.7.10. web.xml Creation......................................................................................... 276
8.7.11. struts-config xml File Creation ..................................................................... 277
8.7.12. struts-config xml File Creation ..................................................................... 278
8.7.13. action-servletAction XML File Creation ....................................................... 280
8.7.14. action-servletService XML File Creation ..................................................... 280
8.7.15. JSP Files Creation....................................................................................... 280
8.7.16. StaffForm Creation ...................................................................................... 282
8.7.17. Validation XML file Creation ........................................................................ 283
8.7.18. MessageResources Properties ................................................................... 284
8.7.19. BaseAction Creation.................................................................................... 284
8.7.20. LoginAction Creation ................................................................................... 290
8.7.21. LoginService Creation ................................................................................. 291
8.8. Context Path Creation at Tomcat Server ............................................................ 292
8.9. Check! ................................................................................................................ 292
Tables and Figures ........................................................................................................... 293
Figures .......................................................................................................................... 293
Tables ........................................................................................................................... 295
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
9/298
Indexes ............................................................................................................................. 297
Keywords ...................................................................................................................... 297
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
10/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Introduction to Java
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
11/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Introduction to Java
• Development tools
Development tools in bin directory are executable program files that can be used for
development, e.g. “javac” (compiler) or “java” (execute class files).They are installed
in JAVA_HOME/bin directory.
• Class Libraries
Class libraries are libraries where various useful functions are stored,e.g. network,
tcp/ip, mail, GUI, etc. They are installed in JAVA_HOME/lib.
✩ JAVA_HOME is a variable that is almost commonly used among JAVA application to
find out where the Java Home exists. It is recommended that the variable is not set as your
Environment Variable, but instead it is better to specify which version of JAVA should be
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
12/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Introduction to Java
used by each application in the startup executable file. In our class JAVA_HOME is set as
an environment variable. You can check which Java is called as defaut by printenv
command;
printenv JAVA_HOME
✩ You can also check which version of Java is used by the following command;
java -version
[HelloWorld.java]
• {} (braces)
A block can start with a block label and they are delimited by braces ({}). All the
action in Java happens between the context of a block, or multiple blocks. A block
can hold sentences or other blocks and the execution of the instructions inside them
is sequential, starting from the first line of the block. In our example we have 2
blocks, one inside another. When we define a block, we are also defining a context
or scope where the action takes place and the definitions are valid.
• public class HelloWorld
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
13/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Introduction to Java
This sentence represents that this block is a class and the name of class is
“HelloWorld”. The class name should coincide with source file name. “public” means
that this class is accessible from any other classes.
• main method
In Java, a program is processed from “main()” method. Method is like a function or
subroutine in procedural programs. The main method has “String[] args” a variable,
that is defined as a parameter of the main method. String[] is array of strings and
args has one command line parameter in each position of its index, that is, args[0]
has the first parameter, args[1] the second one, and so on.
- “public” means that the class is accessible from any other classes.
- “static” is a class attribute and means that it is a method on the class rather than
on instances of the class.
- “void” means that there is no return from this class.
☆ It is recommendable that you write a program with adequate indent to be clear and clean
although spaces or indent are flexible without any rule.
• System.out.println() method
Statement is an instruction unit and at the end of statement you should end with “;”.
System.out.println () is a message of printout to Standard output (usually console
window). println () means to print out the data inside the parenthesis and terminate
the current line by writing the line separator string.
• Package ictti
Package is a way of grouping classes. In the example the class HelloWorld is
grouped into the package named “ictti”.
• Comment area
Comment is expressed as follows;
- // This is comment for only one line
- /* This is also comment line
- You can write more than one line */
- /** This is a comment for Java Doc*/
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
14/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
can download free open source software from the following site that maches to your
platform:
http://www.eclipse.org/downloads/index.php
Eclipse works in various platforms: Windows, Linux, Solaris, AIX, HP, and MAC.
Let’s see how we can create and execute a program using Eclipse in the exercise.
[Tips of Eclipse]
• If you save the source file, automatically the source code is compiled. The compile
error will be displayed in the Problems view.
• If you put the cursor over some object, te javadoc will be displayed shortly.
• PF4 will show you the hierarchy of the type.
• By Ctrl + space the code assist works to complete the name of the class or
variables.
• You can set the JavaDoc location right clicking the rt.jar, so that in the javadoc view
appears more detail javadoc specification.
• By "Ctrl + Shift + f", the source code will be formatted.
• PF3 will open the Declation of the class, method or variable.
• Refactoring functions; change method name, extract constant, extract method
name, etc.
1.2.1. Array
We have learned about variables that store values temporally in the memory. But if there are
thousand of data you want to manage, by this way you have to declare the same
number(thousands) of valuables that is almost impossible. Array is a way to manage values
of the same type with index (number) instead of naming one by one, so that declaring only
array name you can manage thousands of data by index.
• Declaration of array
type name[];
type[] name;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
15/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
• Array creation
Array is created with size and allocated in the memory by “new” keyword. You must specify
the amount of storage you needs.
int[] counts={1,2,3};
or
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
16/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
1.2.2. String
java.lang.String class is oriented to handle string characters. There are following two ways
to declare string character.
The difference between two declarations is that the first statement of the “Hello” object is
created only once. If there is other variable that declare “Hello”, the string is shared. In the
second statement always an object “Hello” is created. If you create twice, there are two
“Hello” strings in the memory.
• Compare
The logical operator “==” compares the reference of the object. Note that it does NOT
compare the contents of the object.
[?] Is it true of false in the following example?
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
17/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
String a1;
boolean bl;
a1 = new String("Hello");
a2 = new String("Hello");
if (a1.equals(a2)){
bl = true;
}else{
bl = false;
}
System.out.println(bl);
1.2.3. Wrappers
The Wrapper class provides various functions for the primitive data. The wrapper class has
a lot of static method (you can use directly with the class name and method name without
instantiating the object).
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
18/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
• Integer
The Integer class is most used, especially for the conversion of data between String
and int.
1.2.4. Collection
To manage a collection of data there is a Collection Interface in the java.util package. The
main collection interfaces are Collection, List, Set, Map, Queue, SortedSet and SortedMap.
They are all included in java.util packages. There is quite big difference between Java 1.4
and Java1.5 function. Here we will see mainly the Java1.4 feature of collection.
• Collection
Collection is at the top of this hierarchy and includes the core methods add(),
clear(),iterator(), isEmpty(), remove(), size(), and toArray() as well as other less common
ones.
• List
The characteristic of this interface is guarantee of the order of data. Therefore all the classes
derived from their interface the order of the data are assured. AbstactList is an abstract
class that implements the List interface. List interface does not check the duplicate data
since it does not have the concept of key (so, duplicate data is OK).
• Map
This interface forces subclasses to associate key with value. Key should be identical (you
can not share the same key with other data). AbstractMap implements this interface.
• Iterator
Iterator is an interface that provides to move in fixed order within a collection. This is used to
refer data in a collection, especially from beginning to the end of data. This interface
provides the following methods.
Table 2 – Iterator method
• HashMap
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
19/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
This class derives from Map interface and quite frequently used.
[Characteristics of HashMap]
- Consists of key and value. Both should be object. You can not specify primitive type.
- The order of data is not guaranteed.
- Permits null values and the null key.
- Note that when you get the value or key from HashMap, object type is returned (in
Java 1.4). You have to cast to the adequate type.
[TestHashMapSample1.java]
/* TestHashMap */
import java.util.HashMap;
public class TestHashMapSample1{
public static void main (String[] args) {
// instantiate HashMap
HashMap hashMap = new HashMap();
// Set values
hashMap.put("Karaoke", "interesting");
hashMap.put("Study", "boring");
hashMap.put("Lunch", "delicious");
// Display hashMap
System.out.println("Display hashMap : " + hashMap);
// Get value
String str = (String)hashMap.get("Karaoke");
System.out.println("Get value of Karaoke is : " + str);
// Check key
if (hashMap.containsKey("Study")) {
System.out.println("ContainsKey: There is Study key");
}else{
System.out.println("ContainsKey: no Study key");
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
20/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
[The results]
✩ Note that the HashMap contents are displayed without order of insert data.
KeySet method of HashMap returns Set implementation containing keys of HashMap. Set
interface has iterator() method to returns an Iterator over the elements in this set. The
following code shows how to get all the keys and values in the HashMap,
• ArrayList
This class derives from List interface.
[Characteristics of ArrayList]
- ArrayList extends AbstractList interface.
- Represents an array of objects that can resize (grow and reduce) dynamically according
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
21/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
/* TestArrayList */
import java.util.ArrayList;
public class TestArrayListSample1 {
public static void main (String[] args) {
// Instantiate ArrayList
ArrayList arrayList = new ArrayList();
// Set values
arrayList.add("Star cola");
arrayList.add("Myanmar beer");
arrayList.add("Alpin");
// Display the contents of ArrayList
System.out.println("ArrayList contents: " + arrayList);
// Add element
String str = "Fantasy";
arrayList.add(1, str);
System.out.println("ArrayList content after addition : " + arrayList);
// remove element
arrayList.remove(0);
System.out.println("ArrayList content after deletion: " + arrayList);
// Get element
System.out.println("Get element : " + arrayList.get(2));
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
22/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
[The result]
✩ Note that the order of the data is guaranteed by its inserted order.
1.2.5. Date
Java has quite rich class libraries related to the dates;
- java.util.Date
- java.util.Calendar
- java util.GregorianCalendar.
- java.text.DateFormat
- java.text.SimpleDateFormat
There are several time and calendar related terminologies used in Java Packege.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
23/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
• Date class
The Date class is helpful when some specified date is shown although the major part of
Date class is already deprecated and recommended to use Calender class which is more
precise in expressing dates. The Date class has some methods to compare two dates.
- after()
-before()
- compareTo()
- equals()
[DateExample.java]
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
Date date1 = new Date();
long now = date1.getTime();
Date date2 = new Date(now + 1000);
System.out.println("date1 is after date2? " + date1.after(date2));
System.out.println("date1 is before date2? " + date1.before(date2));
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
24/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
✩The after() or before() method returns true or false. The compareTo() method returns the
value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before
the Date argument; and a value greater than 0 if this Date is after the Date argument.
• Calendar class
The Calendar class is an abstract class that provides methods for manipulating the calendar
fields, such as getting the date of the next week. It also converts between a specific instance
in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR.
[CalendarExample.java]
import java.util.Calendar;
public class CalendarExample {
public static void main(String[] args) {
Calendar c1 = Calendar.getInstance();
Object obj = Calendar.getInstance().getClass();
System.out.println("Calendar Instance;" + c1);
System.out.println("Calendar getClass;" + obj);
System.out.println("Show date; " + c1.get(Calendar.YEAR) +"/" + c1.get(Calendar.MONTH) +"/"
+ c1.get(Calendar.DATE));
}}
[results]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
25/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Useful Packages and Data Structures
CalendarInstance;java.util.GregorianCalendar
[time=1270383536341,areFieldsSet=true,areAllFieldsSet=true,
lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Rangoon",
offset=23400000,dstSavings=0,useDaylight=false,transitions=5,
lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,
ERA=1,YEAR=2010,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,
DAY_OF_MONTH=4,DAY_OF_YEAR=94,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,
AM_PM=1,HOUR=6,HOUR_OF_DAY=18,MINUTE=48,SECOND=56,MILLISECOND=341,
ZONE_OFFSET=23400000,DST_OFFSET=0]
Calendar getClass;class java.util.GregorianCalendar
Show date; 2010/3/4
Since the Calenda class is an abstract class, it can not be instantiated but by way of
getInstance() method, the object is created, getting back the GregorianCalendar
implemented object.
✩ The first month of the year is JANUARY which starts from 0.
• SimpleDateFormat class
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive
manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. In
the JavaDoc specification, you can check how the date and time patterns are. For example,
using a pattern of "MM/dd/yy" and a SimpleDateFormat instance creates the date
"2010/04/04".
[SimpleDateFormatExample.java]
import java.text.SimpleDateFormat;
import java.util.Date;
class SimpleDateFormatExample {
public static void main(String[] args) {
Date date1 = new Date();
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
26/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
// Create SimpleDateFormat
SimpleDateFormat sdf1 = new SimpleDateFormat("'year'yyyy'month'MM' day'dd");
System.out.println(sdf1.format(date1));
// Change pattern
sdf1.applyPattern("yyyy/MM/dd");
System.out.println(sdf1.format(date1));
}
}
[results]
The Flow Control allows you to execute one of several actions based on the value of a
logical or relational expression. They are very important structures since they're the ones in
charge of flow control of the system.
if ( condition ) {
/* Instructions to execute if condition is true */
}
If the condition evaluates to true, then the code inside the braces is executed. If the
condition is false, it is omitted. Sometimes it is needed to execute some instructions if
certain condition is true and others if it is false. We use if/else statements for this.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
27/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
if ( condition ) {
/* Instructions to execute if condition is true */
} else {
/* Instructions to execute if condition is false */
}
class GrammerIf {
public static void main (String[] args) {
if(args.length > 0){
System.out.println("Hello " + args[0]);
}else{
System.out.println("You must pass a parameter!");
}}}
It checks if there is a parameter passed from console at runtime. It verifies that there is at
least one element in args[]. If the condition is false it means that there are no parameters,
we print a message requiring to the user to specify a parameter.
switch (variable) {
case value1: statements1;break;
case value2: statements2;break;
case value3: statements3;break;
case value4: statements4;break;
case value5: statements5;break;
case value6: statements6;break;
[default: statements7;]
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
28/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
class GrammarFor {
public static void main (String[] args) {
int x = Integer.parseInt(args[0]);
int i;
for (i=0; i<=x; i++) {
System.out.println(i);
}
}
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
29/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
When Java program is executed from command line, parameters can be set to pass to the
program separated by space in the following format.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
30/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
The following code converts the first command line parameter from String to int and assigns
it to “x”. The “for” sentence is the iterator itself and it has the following structure:
int x = Integer.parseInt(args[0]);
In our example we initialize the “i” variable to 0. The for will iterate until the loop condition is
false, and each step will perform the increment specified of the variable in the step, in this
case i++, that means increment “i” in 1.
The order of actions in a “for” loop is the following:
1) initialization
2) check loop condition: if true perform 3) else 5)
3) execute code_block
4) goto 2).
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
31/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
for(;;) {
// code_block;
}
This will loop code_block forever. The break statement can be employed when it meets
some condition.
[GrammarFor1.java]
class GrammarFor1 {
public static void main (String[] args) {
if (args.length > 0) {
int x = Integer.parseInt(args[0]);
int i = 0;
for (;;){
if(i<=x){
System.out.println(i);
i++;
} else {
break;
}
}
} else {
System.out.println("You must specify a number in the command line.");
}}}
This program behaves similarly as the previous example but the initialization is done before
the for loop, and the condition is tested inside an if/else statement. In the case it is false, it
executes the break and exits the loop.
✩ Note that now the program checks if there is a parameter argument specified from the
command line.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
32/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Flow Control
If we want to exit the while loop anywhere inside the code_block we can use the break
statement.
[GrammarWhile.java]
class GrammarWhile {
public static void main (String[] args) {
if (args.length > 0) {
int x = 0;
try{
x = Integer.parseInt(args[0]);
}catch (Exception e){
System.out.println("You must specify a number in the command line.");
}
int i = 0;
while (i<=x) {
System.out.println(i);
i++;
}
} else {
System.out.println("You must specify anumber in the command line.");
}}}
✩ Note that now try catch statement is inserted to check if the passed parameter argument
is other than number to process Exception.
1.3.5. Do loop
“do” loop is quite similar as “while” loop except code block is performed at least once
before logical check of condition.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
33/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exception; try{...} catch {...} finally {...} block
do {
// code_block
}while (condition)
[GrammarDo.java]
class GrammarDo {
public static void main (String[] args) {
if (args.length > 0) {
int x = Integer.parseInt(args[0]);
int i = 0;
do {
System.out.println(i);
i++;
} while (i<=x);
} else {
System.out.println("You must specify a number in the command line.");
}}}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
34/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exception; try{...} catch {...} finally {...} block
void method1() {
try {
// Code that can throw
//IOException and MyException exceptions
} catch (IOException e1) {
// It handles IOException by just displaying a message
System.out.println(e1.getMessage());
} catch (MyException e2) {
// It handles MyException giving a message and
ending the function.
System.out.println(e2.getMessage()); return;
} finally {
// Sentences that will execute in any case.
}
} // End of method1
1.4.2. Throws
In the case a program prefers not managing error exception inside the method, it is
necessary that the system passes the exception to the method from which it has been
called. This is done by means of the keyword throws followed by the name of the exception
after the list of arguments of the method. The superior method will have to include the
try/catch blocks or to pass the exception as well. This way it is possible to pass the
exception from a method to another until the last method of the program is reached, that is,
the main () method.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
35/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exception; try{...} catch {...} finally {...} block
int i = 0, sum = 0;
int[] count = new int[3];
try {
for (;;) sum += count[i++];
}catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
[example of printStackTrace ]
java.lang.ArrayIndexOutOfBoundsException: 3
at Primitive.main(MyException.java:40)
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
36/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
…
try{
evokeException();
}catch (Exception e){
System.out.println("The exception is caught because
of " +
e.getMessage(); )
}
…
• Message
we need to take an action for an object to work. This action to invoke the behavior of the
object is called “send message or “message passing”, e.g. we take an action to accelerate a
car, to change the channel of the television. In a program send message is to call a method
of an object.
• Access Modifier
Access modifier indicates access level from other classes. One of “public”, “protected”,
“private” and default(not specified) is specified.
• Class Modifier
Table 5 – Class Modifier
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
38/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
1.5.3. Package
In JAVA Language package is a kind of container to classify classes together, similar to the
concept of folders of files.
1) Purpose
A class is generally grouped into packages for the following purpose:
¾ To identify the name of class uniquely with package name in order not to have
conflict with other class of the same name. A class with correct package name can
be referred without any conflict in the world. For example;
- java.io.writer.FileWriter Sun Microsystems FileWriter class
- mm.ictti.io.FileWriter mm.ictti.io (private) package
¾ To be able for user to understand the main function of the class by grouping with
package name. Example of packages:
- database
- util
- network
- io
Package is used with domain name to be unique, e.g. if your domain name is jica.it.mm and
a class is related with database and class name is “DBAccess”, the entire name of class
with package name can be:
mm.it.jica.database.DBAccess
2) How to declare
package package_name
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
39/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
3) Import statement
When you want to use classes of the other package in a program, you have to write
“import” statement, e.g.;
import java.io.Writer.FileWriter;
if you want to import multiple classes from a package, you can specify with asterisk (*);
import java.io.*
1.5.4. Instance
An object is a concrete identity of a class. In the program an object is created in the memory
in order to manage concrete data of the object. An object is created by copying from a class
that does not have concrete data yet. This creation of an object is called instantiation. To
use variables or methods of an object you need to instantiate a class. After you get an
instance of a class, you can call methods to request to do something.
• How to code
In Java you can create instances of a class using the keyword new.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
40/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
¾ [access modifier]
The same access modifier explained in the class declaration.
¾ [method modifier]
¾ return_type
Table 7 – Return Type
Return Type Description
void indicates that there is no data returned from this
method.
data type indicates that the specified data type is returned
from this method.
¾ Parameter lists
Set parameter lists as follows;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
41/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
¾ [Exception]
throws; indicates that the method throws specified exception.
1.5.5. Constructor
A constructor is used in the creation of an object to set initial values to the object. When an
instance is created by “new” keyword, one constructor is called to allocate memory and
initialize variables. If the class does not have constructor, super class constructor is called.
Unless the class has super class, the constructor of Object class, the top hierarchy of the
class will be called.
The superclass constructor can be called by super keyword as follow.
The keyword this is used to the object the method is called upon.
class MyClass {
int value;
MyClass (int value){
this.value = value;
}
}
class President {
int iBaseSalary;
public President (int a_BaseSalary){
iBaseSalary = a_BaseSalary;
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
42/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
public President(){
iBaseSalary = 5000;
}
}
1.5.6. Overloading
Overloaded methods are methods with the same name signature but either a different
number of parameters or different types in the parameter list. Although methods have the
same name, its behaviors are different setting different parameters. The caller program
selects one of overloaded methods to get the desired result.
[Example code ]
setValue(int i);
setValue(String str);
setValue(int I, String str);
1.5.7. Inheritance
Inheritance is a generalization of the objects. It has a relationship between classes where
one class is the parent class of another.
Inheritance provides and can be used as an is-a-kind-of (or is-a) relationship. For example a
dog is animal. In this case animal can be parent class and dog is subclass.
Another example, Copy machine is a machine. Computer is also a machine. So computer is
generalized as a concept of copy machine and computer.
Figure 4 – Inheritance
The super class contains variables and methods common to all of the subclasses.
• How to code
Use “extends” keyword in subclass.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
43/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
Animal{
void eat(){
//you have to code here
}
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
44/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
1.5.9. Interface
Interface is an abstract type without any code associated with it and contains only a list of
methods. These methods do not have any functionality but force the programmer to define
them at the class which implements that interface. The difference between abstract and
interface is that abstract class contains non-abstract methods, while interface consists of all
abstract methods.
• How to code
Use “interface” key word for super class. In the interface you declare only the method
without functionality. In the subclasses, use “implements” keyword and implement the
functionality.
1.5.10. Overriding
Overriding means to create a new set of method statements for the same method signature
(name and parameters). If a subclass overrides the super class method, subclass method is
processed and the super class method is ignored. You can also redefine the method in the
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
45/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Class and Object
subclasses including “super()” to process super class methods and add your own code to
expand the functionality in the constructor.
[Caller program]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
46/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exercise 1 – HelloWorld
1.5.11. Polymorphism
Via the message sending, polymorphism is to get the different reaction depending on the
object to where the message is sent. If you send a message “getCPUType” to the notebook
object, it returns you Notebook CPU Type while sending it to the desktop machine object, it
responds you with its Desktop CPU type.
Figure 5 – Polymorphism
Exercise 1 – HelloWorld
(1) Make two arrays(Menu and Price) and store the following data for each array.
Menu table
Menu Price
Coffee 180
Tea 160
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
47/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exercise 1 – HelloWorld
Juice 150
Ice cream 220
(1) Store the above data (MenuTable) in HashMap. The class HashMap is
defined in the java.util package. To use a class of some package insert the
following line in the beginning of your class.
import java.util.HashMap
(2) Get the all value of the HashMap. You can use “keySet()” method getting the
key parts of the HashMap, or you can get the value specifying the key
get(“key_name”).
(3) In the calcSalary method write a code that returns total salary by adding two
parameters.
int calcSalary(int iBase, int iFamily){
return iBase + iFamily;
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
48/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exercise 1 – HelloWorld
(4) Create a class “MySalary” with main() class, and call calcSalary() of
SalaryBase class setting parameters for base and family. Check if the
calculation is correct.
SalaryBase
MySalary
CalcSalary()
CalcSalary()
SalaryEmployee
MySalary
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
49/298
S-EA-A-1.0
Quick view of Fundamental Java <Day 1>
Exercise 1 – HelloWorld
SalaryBase
CalcSalary()
SalaryPresident
MySalary
CalcSalary()
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
50/298
S-EA-A-1.0
Web Application <Day 2-1>
Characteristics of Java Web Application
Internet
index.html
Browser Response
Web Server
The static pages show just information without any interaction with the user. Some tourist
information, government information, news, homepages are static web pages.
Client and server communicate each other by HTTP (HyperText Transfer Protocol) protocol
for data transmission.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
51/298
S-EA-A-1.0
Web Application <Day 2-1>
Characteristics of Java Web Application
<html>
<head><title>Hello World!</title></head>
<body>
<h1>This is my Hello html </h1>
<p>
Hello from Hello.html!
</p>
</body>
</html>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
52/298
S-EA-A-1.0
Web Application <Day 2-1>
Characteristics of Java Web Application
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
53/298
S-EA-A-1.0
Web Application <Day 2-1>
Servlet
2.2. Servlet
2.2.1. What is Servlet
Servlet is one of the components of Java 2 Platform, Enterprise Edition J2EE specified by
Sun Microsystems for the server side Java web application. The Java web application is
composed of three tiers.
z First tier
This tier is input and output on the client machine, such as web browser.
z Second tier
Business logic and view control belong to this tier. Servlet containers, JSP container,
Java Bean or JSP are the components of this tier
z Third tier
Database system belongs to this tier.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
54/298
S-EA-A-1.0
Web Application <Day 2-1>
Servlet
HTTP JSP
Bean
ProcessA ServletA
Thread2
ProcessA Thread1
ProcessA
ServletB
ProcessB
Thread1
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
55/298
S-EA-A-1.0
Web Application <Day 2-1>
Servlet
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
56/298
S-EA-A-1.0
Web Application <Day 2-1>
Servlet
<form>
<input type="button" name="ButtonCtrl" value="click here"
onClick="event()">
</form>
</body>
</html>
[Example]
http://localhost:8080/webhello/ictti.Hello
z Context-path
The character string that represents Web Application name
z Servlet-path
The character string represents Servlet path name.
z Servlet name
The name of Servlet.
2.3. Tomcat
Tomcat is a middleware that provides Web server, Servlet Container and JSP container for
Web Applications. It is a web container developed at the Apache Software Foundation and
implements the Servlet and JSP specifications from Sun Microsystems. There are packages
both for Windows and Unix environment.
(1) Tomcat is Reference Implementation of Servlet and JSP.
(2) Open Source
(3) Tomcat5.X implements Servlet 2.4 and JSP 2.0 specifications.
(4) Tomcat6.X implements Servlet 2.5 and JSP 2.1 specifications.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
59/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
☆ If you use Tomcat independently without any IDE, be sure to set the JAVA_HOME
environment variable adequately.
☆ 4) Type the following URL from the browser;
☆ http://localhost:8080
☆ 5) If the first page of Tomcat appears, your installation has succeeded.
☆
Figure 14 – Tomcat First Page
z web.xml
The web.xml file is a configuration file for each web application. It is located always under
/WEB-INF directory of web application. The file always starts with <web-app> tag and ends
with </web-app>. There are two ways to define Servlet from Tomcat using this file.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
60/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>ictti.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/ictti.Hello</url-pattern>
</servlet-mapping>
</web-app>
<web-app>
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
61/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
</web-app>
☆In starting Tomcat6, a web application needs to be privileged in order for the invoker
servlet to work. Modify context file in your web application as the following context file.Add
privileged=”true” in the context tag.
☆Each time you modify the configuration files, you have to restart Tomcat to be reflected
the modifications.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
62/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
✩ You need to have root permission to run Tomcat application (as default) in Linux
environment.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
63/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
64/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
%TomcatInstallDirectory%
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
65/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
2. Unzip the downloaded file and extract them to ECLIPSE_HOME∖plugins (copy whole
directory of com.sysdeo.eclipse.Tomcat_3.2.0.beta2).
3. Start Eclipse.
4. From the menu, select Window -> Preferences -> Tomcat. Set Tomcat version, Tomcat
home. Choose Context files for Tomcat6.X and "choose Context" files for Tomcat6.X.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
66/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
67/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
6. Check the Installed JRE of the eclipse environment from "Window" -> "Preferences"->
"Java" -> "Installed JREs". If the installed JDK library is not pointed out, add your installed
SDK location.
7. Check the Compiler of Eclipse environment from "Window" -> "Preferences"-> "Java" ->
"Compiler". If the compiler compliance level is not correct, change it to "1.6".
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
68/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
69/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
9. You have finished the configuration for Tomcat. Now you can start Tomcat clicking on
Tomcat start button on the menu. You can also select from the menu Tomcat-> Start
Tomcat.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
70/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
71/298
S-EA-A-1.0
Web Application <Day 2-1>
Tomcat
http://127.0.0.1:8080
12. If the Tomcat first page appears, the Eclipse-Tomcat plugin has been set correctly.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
72/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
[Software versions]
Suse Linux 11.2
Tomcat 6.0.18
Eclipse 3.4
Tomcat-Eclipse plugin V32
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
73/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
4) Set project name as "webhello". Set also the Tomcat webapps directory and the project
name in the "Directory" text box. Do not forget to set until the web directory name in the
"Location".
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
74/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
75/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
7) Check the "server.xml" and Tomcat directory to see how the webhello project is created
by Eclipse.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
76/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
77/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
4. Type "https" in the text box of "choose a type" and matching types appear below. Select
"HTTPServlet" and click on "OK".
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
78/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
79/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
6. Right-click the "project" -> "Tomcat project" -> "Update context definition" to update the
definition of Tomcat.
✩ Your project configuration of "webhello.xml" will be created under context directory of
"/etc/tomcat6/Catalina/localhost/".
7. When you save the project, automatically the class will be compiled.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
80/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
✩ Eclipse supports Code Assist. For example type "out." in the editor. Code assist
prompts you with possible completions (if automatically does not appear code assist, press
Ctrl+Space).
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
81/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
3) Drag the following file and drop it in the project’s WEB-INF folder.
%TomcatInstallDirectory%/webapps/ROOT/WEB-INF
The web.xml file will be imported. The web.xml file is a Tomcat configuration file for Web
Application.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
82/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
4) Open the "web.xml" file and change the contents of <web-app> tags like this.
<?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">
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>ictti.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
83/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
84/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
(2) %TomcatInstallDirectory%/conf/Catalina/localhost/xxxxx.xml
Eclipse creates an application context file with the application name. For example
if you create the application "webhello", then your context file is created as
%TomcatInstallDirectory%/conf/Catalina/localhost/webhello.xml
[sample of web.xml]
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
Servlet name for the
<servlet>
reference
<servlet-name>HelloServlet</servlet-name>
<servlet-class>ictti.HelloServlet</servlet-class> Servlet class name with
</servlet> package
4. Call the Servlet from html file. Follow the following instructions.
1) Create an html file "Hello.html" following the [Example of HTML code: Hello.html] in the
textbook. Save it under "webhello" project.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
85/298
S-EA-A-1.0
Web Application <Day 2-1>
Exercise 2 – Hello Servlet
2) Call the "Hello.html" from the browser and check if it is displayed correctly. Let's think how
to call the html file from the browser.
3) Add the following form tag after </p> code of the "Hello.html".
<form action = "Hello" method = "GET">
<INPUT TYPE="submit" value="Click here">
</form>
Call the above "Hello.html" from the browser. Click the button to see if the "HelloServlet" is
called.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
86/298
S-EA-A-1.0
Servlet <Day 2-2>
Servlet mechanism
Web Browser
http://jica.co.jp/index.html Server (jica.co.jp)
Web Servlet
HTTP Request
Server Container
HTTP Response
Web Browser HTML,gif,txt
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
87/298
S-EA-A-1.0
Servlet <Day 2-2>
Servlet mechanism
For the
Servlet class first time to
Web Browser be called,
HTTP Web
the Servlet
Server
is loaded.
ServletA
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
88/298
S-EA-A-1.0
Servlet <Day 2-2>
Servlet mechanism
Request
(3) HttpRequest
method
HttpRequest
method
HttpRequest
method
(1) The Servlet is loaded and instantiated by calling init() method for the first time of request.
(2) The Servlet calls service() method that transfers control to the HTTP request method.
(3) The Servlet is released from the request handling and waits for receiving another client
request.
(4) The destroy() method is called to destroy Servlet. This occurs when Servlet container of
application is shut down.
☆ The Servlet itself remains on the memory waiting for another client request until it is
destroyed. This contributes to realize high performance of request handling.
☆ The Servlet is performed as thread. Servlet instance variables are shared among the
thread.
The abstract methods init(), service(), destroy() are located in the "javax.servlet.Servlet"
Interface. The "javax.servlet.http.HttpServlet" is a class that implements the abstract
methods. You can override the methods in your own Servlets. Since the service() method
calls doGet() and doPost() method, you can override them instead of calling service()
method to handle different operations.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
89/298
S-EA-A-1.0
Servlet <Day 2-2>
Get/Post method
[ExampleGet.html]
<html>
<head><title>Test GET method</title></head>
<body>
<h1>This page is to test GET method</h1>
<form method="GET"
action="/webhello/servlet/HelloServlet ">
Name: <input type="text" name="name"> <br>
Age : <input type="text" name="age"> <br>
<input type="submit" value="Click here">
</form>
</body>
</html>
http://localhost/webhello/servlet/HelloServlet?name=Pablo&age=42
The name and age parameters are the names of parameter and after the "=" shows its value.
These parameters are passed to the Web server who passes it to Servlet. Finally doGet ()
method of the Servlet is called if the method is set to GET in the form tag.
☆ Since the parameters are shown after the URL address, working with sensitive data such
as password should not use Get method.
[Example]
<form action="registration" method="POST">
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
91/298
S-EA-A-1.0
Servlet <Day 2-2>
Servlet parameters
client Servlet
Please input your name Parameter “Pablo” protected void doPost(…)
TestParam.html ParamServlet.java
client
[TestParam.html]
<html>
<head><title>TestParam</title></head>
<body>
<form action="servlet/ictti.ParamServlet" method="POST">
Please input your name.
<input type="text" name="Name" /> <br>
Please input your password.
<input type="password" name="Pass" /><br>
<input type="submit" value="send" />
</form>
</body>
</html>
z In the action attribute of form tag, the Servlet URL is specified. Here the Http Post
method is applied. You can also specify absolute URL.
<form
action="http://localhost:8080/servletProj/Servlet/ictti.ParamServ
let" method="POST">
z Element type of form tag is text box. The name of text box is "Name". This name is
referred in the Servlet to get the value.
<input type="text" name="Name" >
z Input type with "password" does not show your input content.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
92/298
S-EA-A-1.0
Servlet <Day 2-2>
Servlet parameters
[ParamServlet.java]
package ictti;
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
✩ you have to filter the specified message string for characters that are sensitive
in HTML such as "<", ">" to "<", ">" to avoid potential attacks caused by including
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
93/298
S-EA-A-1.0
Servlet <Day 2-2>
Servlet initialization parameters
2) Context initialization is available to all servlets. First call the getServletContext method
that returns the ServletContext object. Then call the getInitParameter() of the ServletContext
to get Context Initialization Parameters.
☆ You can call getServletConfig() method anywhere from the Servlet if the following
method is called in the beginning of the Servlet instantiation. The init() method of super
class (= GenericServlet class) will store the ServletConfig object it receives from the
servlet container for later use. What is needed is to override the method of super class.
public void init(ServletConfig config)
throws ServletException{
super.init(config);
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
94/298
S-EA-A-1.0
Servlet <Day 2-2>
How to forward the request and response
[web.xml]
<web-app>
<context-param> Context initialization parameter
<param-name>DBConnect</param-name>
<param-value>jdbc:oracle:thin:@127.0.0.1:1521:ORCL</param-v
alue>
</context-param>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>ictti.HelloServlet</servlet-class>
<init-param> Servlet initialization parameter
<param-name>PARAM1</param-name>
<param-value> Parameter test from web.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/ictti.Hello</url-pattern>
</servlet-mapping>
</web-app>
z Servlet initialization parameters are coded within <init-param> element of <servlet> tag.
z Context initialization parameters are described within <param-name> and
<param-value> of <context-param>.
z servlet-mapping is to map URL name to a Servlet. <Servlet-name> specifies the name
of Servlet used in the web.xml file.
z <servlet-class> is where the Servlet class name with package name is defined.
z <url-pattern> specifies URL pattern name that is called from the browser.
RequestDispatcher rd = request.getRequestDispatcher("/Hello.jsp");
rd.forward(request, response);
The forward method transfers control to a resource such as Servlet and JSP on the same
server.
2.9. Session
2.9.1. What is session?
Http protocol is a stateless protocol, that is, a round trip of request from client and response
from the server. After the server returns the response the connection finishes. Although
another connection starts with client another request, there is no way to associate with the
data of previous connection. For example, if the server gets user name after login page, on
the second page the server cannot identify if the connection comes from the same user as
who logged in the previous connection.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
96/298
S-EA-A-1.0
Servlet <Day 2-2>
Session
Servlet
Login
User=Smith
Smith is OK
Login
response
A session is to keep track of user information during the user’s navigation in the same
Internet site. For example, in a shopping cart application, you may put in the cart the product
you want to buy in the different pages. Finally you may decide to pay check by credit car. In
this case your data and products you put in the cart must be kept to calculate the check until
you want to finish using the service in that site.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
97/298
S-EA-A-1.0
Servlet <Day 2-2>
Session
[example of session]
Servlet
Login
User=Smith
OK
SessionID=123
OK because same
user
Session Object
SessionID=123
Buy some
SessionID=123 products
OK because same
user
Browser
- URLRewriting
The SessionID is appended in the URL for each page. The use of URLRewriting is
limited only when the cookie is disabled.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
98/298
S-EA-A-1.0
Servlet <Day 2-2>
Session
z getSession(true)
Creates the session if the session does not exist. This is used for the first time of
session, e.g. login page.
getSession(false)
Returns null if the session does not exist. Usually it is used to check if a user has
logged in correctly.
z setAttribute(name, value)
Store the value with the specified name in the session object.
z getAttribute(name)
Obtain the value of the specified parameter from the session object. The name should
be the same as used to store value with setAttribute() method.
1) for new session (for the first time to enter the site)
// create session if a session object does not exist
request.getSession(true)
// set session data
SessionObject.setAttribute(name,value)
The parameter true creates new session if a session does not exist. If the session already
exits, return it. With setAttribute() method, session name and value are set.
[Example]
protected void doPost( HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String strName=req.getParameter("Name");
// create session object
HttpSession session=req.getSession(true);
// set information to the session object
session.setAttribute("Name", strName);
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
99/298
S-EA-A-1.0
Servlet <Day 2-2>
Session
The "getAttribute()" method returns the value with object type. It is required to cast each
object to the appropriate class.
String strName = (String)session.getAttribute("Name");
3) Finish session
HttpSession session = req.getSession(false);
if (session!=null){
session.invalidate();
}
By session.invalidate() method, session will be invalidated and the object will be deleted
(target of garbage collection).
✩ A session also finishes automatically after certain minutes have passed without any
interaction from the user according to the configuration set in 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">
<web-app>
<!-- Define the default session timeout for your application,
in minutes. From a servlet or JSP page, you can modify
the timeout for a particular session dynamically by using
HttpSession.getMaxInactiveInterval(). -->
<session-config>
<session-timeout>30</session-timeout> <!-- 30 minutes -->
</session-config>
</web-app>
The following code shows the sample of the first page (usually the Login check page).
[First Page]
protected void doPost(HttpRequest req, HttpServetResponse res)
throws ServletException, IOException{
// Get user input parameters from browser
String strName = req.getParameter("UserID");
String strPwd = req.getParameter("PASSWORD");
The following code shows the sample code after the first page.
[Second Page]
protected void doPost(HttpRequest req, HttpServetResponse res)
throws ServletException, IOException{
✩ You are storing data into session object in the memory for each session . It is important
to consider how much memory will be wasted which depends on how many users will be
accessed at the same time.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
101/298
S-EA-A-1.0
Servlet <Day 2-2>
Exercise 3 – Servlet programming
2) Create the "ParamServlet.java" Servlet program of the textbook with package name
"ictti".
3) Configure the "web.xml" file using the "Invoker" Servlet to be able to call anonymous
Servlet.
4) Call the "TestParam.html" from your browser. Input any name in the text box and click
the button to see if the Servlet can obtain the parameters you input.
<servlet-mapping>
<servlet-name>TestInitParam</servlet-name>
<url-pattern>/MyInitParam</url-pattern>
</servlet-mapping>
3) Define both "Servlet Initialization" and "Context Initialization" following the textbook in the
"web.xml".
4) Create a Servlet "TestInitParam.java" with package name "ictti". Obtain the Initialization
parameters you set in the "web.xml" file in the "doGet" method. Print out the parameters to
the console. Do not forget to import the correct javax.servlet package to be able to refer
ServletConfig and ServletContext classes.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
102/298
S-EA-A-1.0
Servlet <Day 2-2>
Exercise 3 – Servlet programming
3) Call the "TestInitParam" Servlet from the browser and check if the Servlet gets correctly
the initialization parameters.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
103/298
S-EA-A-1.0
JSP <Day 3>
What is JSP
Although a Servlet can cover all the above functions, there are the following disadvantages
of Servlet to code HTML tags inside the program.
[Disadvantages of Servlet]
1) HTML code is embedded in the Servlet program. Therefore all the HTML code in the
Servlet should be described in a program.
2) The Servlet program becomes less clear and difficult to maintain when the Web page
design is complicated.
3) Servlet should be compiled to be executed. Each time the HTML design is modified in
spite of slight change, the compilation is required.
[Advantage of JSP]
z JSP is embedded in HTML. The mayor part in JSP can be described with HTML code,
which results easier than Java code. Only minimum code for dynamic information is
written in JSP.
z The HTML code is separated from Servlet. Servlet program remains only with business
functionality while JSP is responsible of the view functionality.
z If the HTML code is separated, a web designer can work with HTML document while
programmers can concentrate on working with the implementation of business
functions.
z JSP does not require compilation. Any modification can be done just modifying the file.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
104/298
S-EA-A-1.0
JSP <Day 3>
What is JSP
Servlet <HTML>
<HEAD>
<HTML>
<jsp:…>
<HEAD>
…
</HTML>
</HEAD>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
105/298
S-EA-A-1.0
JSP <Day 3>
What is JSP
JSP Container
Web Browser
http://jica.co.jp/hello.jsp
HTTP N
Class exists?
Web
Y
Server
Y
Web Browser Changed?
N
Compile
HTTP
Execute Servlet
[Example]
http://localhost:8080/webhello/jsp/Hello.jsp
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
106/298
S-EA-A-1.0
JSP <Day 3>
What is JSP
4) Test
JSP is compiled automatically when the file is called for the first time. You can test JSP just
calling from the browser or Servlet.
[Mingalarbar.jsp]
<html>
<head>
<%! public int i; %>
<title>Hello JSP</title></head>
<body>
<h1>
<% for (i=0; i<=2; i++){
out.println ("Min ga lar bar from JSP <br>");
}%>
</h1>
</body>
</html>
2) Scripting elements
z Declarations
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
107/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
<%! %>
z Expression
<%= %>
z Scriptlet
<% %>
3) Directives
z page directives
<%@ page %>
z include
<%@ include %>
4) Implicit objects
- request
- response
- out
5) Standard actions
- useBean
- getProperty
- setProperty
- include
- forward
- param
[Example]
<%!
public int calc(int i){
return i++;
}
%>
[Syntax]
<%= expression %>
[Example]
<%= strName %>
<%= employee.calc() %>
<%= x + y %>
[Syntax]
<% script %>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
109/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
[Example]
<% String strA = "Hello";
String strB = " JSP";
String str=strA + strB;
%>
<%
GregorianCalendar calendar = new GregorianCalendar();
if (calendar.get(calendar.AM_PM)==calendar.AM){ %>
<p>Good morning! </p>
<% }else{ %>
<p>Good afternoon!</p>
<%}%>
The scriptlet is embedded between HTML codes in the above example.
import Imports java classes that are available in the actual page.
session Indicates whether the session will be used in the JSP page.
The default is true. The session is created if it does not exist
in case of true.
contentType Specify MIME type and encoding type. If the contentType is
omitted, "ISO-8859-1" is considered for enconding type.
[Syntax]
<%@ page attribute %>
[Example]
<%-- import the necessary classes --%>
<%@ page import="java.io.*" %>
<%@ page import="webhello" %>
<%@ page import="java.io.*,webhello"%>
<%-- specify the contentType for the actual JSP page --%>
<%@ page contentType="text/html;charset=Windows-31J" %>
[TestDirectiveInclude.jsp]
<html>
<body>
<h1>Sample of Include Directive of JSP</h1>
</body>
<%@ include file= "/include/footer.txt" %>
</html>
[/include/footer.txt]
<%@ page import="java.util.Date" %>
<p>Executed in <%= new Date() %> </p>
[result]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
111/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
112/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
[Example]
<%= request.getParameter("firstName")%>
The input parameter "firstName" is obtained from request object.
[Syntax]
<prefix:tagname>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
113/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
1) jsp:useBean
A Java Bean is a Java class that is developed for business objects, especially to enable
access to the variable data. It contains instance variables and get/set method for all the
variables. The useBean is a tag to access to a Java Bean in order to get or set variables.
The Java Bean is especially useful for data exchange between:
z database access class and Servlet
z Servlet and JSP
[example of JavaBean]
private String strName;
// getter/setter method for strName
public String getStrName(){return strName;}
public String setStrName(String Name){strName=Name;}
For example, a database access class returns to the Servlet the Java Bean class that
contains the result data retrieved from a database. The Servlet sends the Java Bean to JSP
so that JSP can extracts necessary data from it. Then the JSP sets the dynamic data to the
HTML to show on the Browser.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
114/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
object that is accessed by Servlets and JSP. Session object is not created
automatically. It is created by getSession(true) method of RequestObject.
application The bean is stored in the ServletContext object. It is available to the web
application object that is accessed by Servlets and JSP.
[example]
<jsp:useBean id="object1"
class="Beans.ExBean"
scope="session" />
<%-- Create object1 of the ExBean object.
Scope is session. --%>
In the above case, if the object exists in the scope, already declared object is obtained. If the
object does not exist, it will be newly created. It is important to remember that JSP pages
and servlets in the same web application share the same sets of bean collections. For
example, a bean stored as a request attribute in a servlet like this:
This object stored to the session attribute is visible from the JSP by standard action tag;
<jsp:useBean id="object1"
class="Beans.ExBean"
scope="session" />
<%-- Get the ExBean object stored in the session with the name "object1"
--%>
<% ExBean object1 = session.getAttribute("objet1"); %>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
115/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
2) jsp:getProperty
Get the property value of the JavaBeans using Getter method of the property which is
composed of "get" + "PropertyName". It is required that the JavaBeans is already
instantiated (obtained) by <jsp:useBean> tag.
Java Bean
public class MyBean{
private String name;
public String getName(){ <jsp:useBean id="testBean" class="MyBean">
3) jsp:setProperty
Set the property value of the JavaBeans using Setter method of the property which is
composed of "set" + "PropertyName". It is required that the JavaBeans is already
instantiated (obtained) by <jsp:useBean> tag.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
116/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
[example]
<jsp:setProperty name="object1"
property="id"
param="myParam" />
4) jsp:include
z The include tag includes the indicated resource to the JSP current page dynamically.
z The resources are included each time JSP receives request. Therefore, the
modification of included resource is always reflected to JSP.
[Example]
<html>
<body>
<jsp:include page="Hello.jsp" flush="true" />
</body>
</html>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
117/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
✩ The difference between <jsp:include> and "include directive" is that "include directive"
includes the file at the compile time, while <jsp:include> includes it when a client sends
request. As a result, <jsp:include> is convenient when an included file is decided
dynamically at run time. Another difference is that include directive can refer the variables
and methods defined in the original file, while <jsp:include> can not.
[TestJSPInclude.jsp]
<HTML>
<BODY>
<%-- declare boolean and set to true --%>
<%! boolean bl = true; %>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
118/298
S-EA-A-1.0
JSP <Day 3>
JSP grammar
%>
</BODY>
</HTML>
[true.txt]
true is selected.
[false.txt]
false is selected.
[result]
5) jsp:forward
z The forward tag transfers control to the indicated resources.
z The results of the resources are displayed.
z Similar to the RequestDispatcher of the Servlet forward method (see 2.8.1)
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
119/298
S-EA-A-1.0
JSP <Day 3>
JSTL (Java Server Pages Standard Tag Library)
[Example]
<jsp:forward page="error.jsp" />
6) jsp:param
The param tag provides parameters to include and forward tags.
[Example]
<jsp:forward page="error.jsp" >
<jsp:param name="err1" value="I/O error has occurred" />
<jsp:param name="err2" value="File not found" />
</jsp:forward>
[error.jsp]
<html>
<head><title>Error JSP</title></head>
<body>
<h1>Test JSP PARAMETER ; The following error has occurred;</h1>
<%= request.getParameter("err1") %>
</html>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
120/298
S-EA-A-1.0
JSP <Day 3>
JSTL (Java Server Pages Standard Tag Library)
3) Configure the JSP File declaring tag library in the JSP file
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
121/298
S-EA-A-1.0
JSP <Day 3>
JSTL (Java Server Pages Standard Tag Library)
[Example]
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
z uri
Indicates the URI of TLD file.
z prefix
Table 14 - Prefix and uri of JSTL
prefix URI description
c http://java.sun.com/jsp/jstl/core core library. This includes store data, if condition,
loop, import page, etc
fmt http://java.sun.com/jstl/fmt Internationalization, date format, obtain
resources, etc
sql http://java.sun.com/jstl/sql SQL access, execute SQL query.
xml http://java.sun.com/jstl/xml process XML on the JSP
[Syntax]
<c:set var="variable_name" value="value or expression" />
[Example]
<c:set var="a" value="0"/>
<c:set var="a">0</c:set>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
122/298
S-EA-A-1.0
JSP <Day 3>
JSTL (Java Server Pages Standard Tag Library)
[Syntax]
<c:out value="value or variable" [default=default value]
[escapeXml=true/false]>
z The escapeXML is true when you want to display strings such as "<",">","&".
z The escapeXML is false when HTML tags such as <b>, <br> should be recognized as
HTML tags.
z default value is set when the value is null.
[Example]
<c:out value="<h1> this is standard tag</h1>" escapeXml="false" />
[/jsp/Coretag.jsp]
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head></head>
<body>
<c:set var="strMessage">
Hello, This is JSTL core tag lib test page
</c:set>
<c:out value="${strMessage}" escapeXml="true" />
</body>
</html>
The above example shows that "strMessage" is a variable where the "Hello, …" message is
stored with <c:set > tag. In the next line the content of the variable is output by <c:out> tag.
4) Core tag:<c:forEach>
The <c:forEach> is a tag to repeat process.
[Syntax1]
<c:forEach var="variable_name" begin="start_value" end="end_value"
step="incremental value">
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
123/298
S-EA-A-1.0
JSP <Day 3>
JSTL (Java Server Pages Standard Tag Library)
[Example]
<c:forEach var="i" begin="1" end="5" step="1">
<c:out value="hello" /><br>
</c:forEach>
5) Core tag:<c:if>
The <c:if> is a tag for if conditional sentence.
[Syntax]
<c:if test="conditional_expression" var="variable_name" />
In the variable_name the result of the conditional sentence is set.
[Example]
<c:if test="${1< 5}" var="myVar">
<c:out value=" 1< 5 is ${myVar}" /><br>
</c:if>
[Declaration of variable]
${variables or objects}
[Example]
<c:forEach var="i" begin="1" end="5" step="1">
Hello JSTL tag ${i}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
124/298
S-EA-A-1.0
JSP <Day 3>
JSTL (Java Server Pages Standard Tag Library)
<br>
</c:forEach>
In the above case the variable is output directly in the middle of HTML code.
<html>
<head>
<title>Expression Language Sample</title>
</head>
<body>
<c:set var="myVar5" value="5" />
<c:set var="myVar8" value="8" />
<c:set var="myResult" value="${myVar5 * myVar8}" />
<c:out value="${myResult}" /> <br/>
<c:if test="${myResult < 50 }">
<c:out value="${myResult} results less than 50" />
</c:if>
</body>
</html>
%>
${param.name} <% String value = request. Get the parameter of "name" sent from the
getParameter("name"); previous page
%>
${paramValues.myCheck} <% String[ ] values = request. Get the value of checkbox named "myCheck"
getParameterValues("family"); sent from the previous page.
%>
Table 16 - Scopes in EL
Scope Description example
pageScope Valid only inside the actual JSP page. ${pabeScope.user}
Refer to the user object that resides
in page scope.
requestScope Scope for pages of request scope. This is ${requestScope.name}
valid between the original page and the Refer to the user object that resides
destination page. This is used to share in request scope.
between those pages
sessionScope Scope for session that is hold for certain ${sessionScope. .id}
period until session is closed, browser is Refer to the id object that resides in
closed or fixed time has passed. This is session scope.
used to keep information such as ID or
password.
applicationScope Application scope is hold until JSP ${applicationScope.configA}
container is shutdown. This is created only Refer to the configA object that is
one object for each application and shared held in application scope.
by all.
✩ You can get JSP Syntax reference and Standard Tag Library 1.1. implementation
from:
z http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html
z http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html
z http://java.sun.com/developer/technicalArticles/javaserverpages/faster/
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
126/298
S-EA-A-1.0
JSP <Day 3>
Exercise 4 – JSP programming
3) Declare int type "i" variable in a Declaration tag. This variable is used for a counter.
4) Write a for loop that repeats five times to write out the string "Hello JSP with Scriptlets"
and variable counter using Scriptlets and HTML tags. Use the variable declared with
Declaration tag.
[output image]
Hello JSP with Scriptlets 1
Hello JSP with Scriptlets 2
…
5) Write another loop program using "out" of implicit object. Print out the string "Hello JSP
with implicit object" and the loop counter.
[output image]
Hello JSP with implicit object 1
Hello JSP with implicit object 2
…
2) Create a text file "header.txt" in the "include" directory. Write the following html tags.
<title> ICTTI Software Development: Java Programming Advanced
</title>
<head> JSP programming: practice of Include Directive and Standard
Action Include
</head>
3) Create another text file "footer.txt" and save it in the "include" directory. Write the
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
127/298
S-EA-A-1.0
JSP <Day 3>
Exercise 4 – JSP programming
4) Create a jsp file "TestInclude.jsp" and save it in the "jsp" directory. Write just <html>
</html>tags and <body></body> tags correctly.
5) Include "header.txt" to the "TestInclude.jsp" using <jsp:include > tag of "Standard Action"
between <html> and <body>.
6) Include "footer.txt" to the "TestInclude.jsp" using <%@ include > of Directive next to the
<body> tag.
6) Call the "TestInclude.jsp" from the Browser and check if the both text files are correctly
included.
✩ You have to import into the JSP page the necessary classes to refer.
3. JSTL programming.
1) Check if the "standard.jar" and "jstl.jar" are installed in the "LIB" directory of "WEB-INF" of
your project.
3) Write JSTL core taglib <%@ taglib …> with prefix and uri for core taglib in the
"TestJSTLLoop.jsp"
4) Write a "for" loop that repeats five times to write out the string "Hello JSTL Tag " and
variable counter using JSTL <c:forEach> and <c:out> tags.
4. Create a Servlet that dispatches the JSP page. Use the same input parameters of
"TestParam.html" (name and password).
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
128/298
S-EA-A-1.0
JSP <Day 3>
Exercise 4 – JSP programming
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
129/298
S-EA-A-1.0
JDBC <Day 4>
JDBC
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
130/298
S-EA-A-1.0
JDBC <Day 4>
JDBC types
[Example of database]
- Microsoft Access
[Advantage]
z It is useful if the ODBC driver for the specific database is provided
z It can be applied for the database which JDBC driver is not provided but ODBC is
offered by the vendor, e.g. Microsoft Access.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
131/298
S-EA-A-1.0
JDBC <Day 4>
JDBC types
[Disadvantages]
z Both JDBC for ODBC and ODBC driver for Database are required to be installed in a
client machine.
z To connect with Database, it is necessary to pass two drivers. It takes more time and
the functions are limited to what both drivers have.
Client Machine
JDBC-ODBC ODBC DB
Java Application
driver driver
[Advantage]
z ODBC driver is not required.
z Since the type2 does not have the overhead of the additional ODBC function calls, it
provides more functionality and performance..
[Disadvantage]
z DBMS binary code should be installed and running on the client machine. For Oracle,
Net8 client service should be running.
z Can not be used in the Internet from the browser because the client software is needed.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
132/298
S-EA-A-1.0
JDBC <Day 4>
JDBC types
Client Machine
DB
Java Partly Java Native API
Application driver driver
[Example of database]
- Oracle OCI (Oracle Call Interface) driver is Type 2. The Oracle net client library should be
installed on the client machine. Therefore the OCI driver is Oracle platform-specific.
[Advantages]
z Net protocol driver is quite light.
z The Middleware Server can provide typical middleware services like connections,
query results, load balancing, logging, auditing etc.
z No need of vendor specific JDBC driver.
z Client machine can be light while the middle service program has high functionality
and performance
[Disadvantage]
z The middle service program should be running on the server machine.
z Another additional tier for Middleware Server.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
133/298
S-EA-A-1.0
JDBC <Day 4>
JDBC types
DB
Java Network Middle Service
Application Protocol Driver Program
DB
JDBC Driver Manager
Different vendors
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
134/298
S-EA-A-1.0
JDBC <Day 4>
How to connect to a database
Client Machine
DB
Java Application Native Protocol
driver
z Connection
The getConnection() method of the DriverManager class connects to the database and
returns a Connection object. URL string, userID, and password are supplied for the
connection.
[Example]
try {
Class.forName("com.mysql.jdbc.Driver");
String strURL = "jdbc:mysql://localhost/ictti";
Connection con =
DriverManager.getConnection(strURL,"root", "root");
System.out.println("connection succeeded.");
}catch (Exception e){
// error code
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
135/298
S-EA-A-1.0
JDBC <Day 4>
How to connect to a database
z Syntax
jdbc:subprotocol:subname
4.3.3. DataSource
A DataSource is an interface of javax.sql.DataSource which is implemented by a dviver
vendor. This is an alternative connection to the DriverManager facility providing connection
pooling. Usually an object that implements the DataSource is registered as JNDI (Java
Naming and Directory Interface) using InitialContext specification. A DataSource object is
the preferred means of getting a connection since the connection or driver information is
obtained from external configuration file. This enables the program to refer to only the data
source name and allows system to change server or DBMS without any change in the
program. This is quite important from the portability point of view. .
[Example]
InitialContext ic = new InitialContext();
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
Connection con = ds.getConnection();
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
136/298
S-EA-A-1.0
JDBC <Day 4>
How to connect to a database
[Connection Pooling]
Connection Pooling is a technique to create and handle a pool of connections that are
shared by threads who get access to JDBC. This is based on the facts that applications
usually process a transaction that takes only few milliseconds to complete. When the
transaction has finished, the connection is returned to the connection pooling. Then the
connection pooling remains idle to be used by some other thread. The benefits of
connection pooling are;
z Reduce the connection time
z Simplified the programming code
z Reduce the resource usage,and overhead (memory, CPU, context switches, etc)
<value>4</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
</ResourceParams>
Hostname DBName
driverClassName="com.mysql.jdbc.Driver" username="root"
password="root" maxIdle="5" maxActive="50" />
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
138/298
S-EA-A-1.0
JDBC <Day 4>
How to connect to a database
[webhello2/MysqlConnectDataSourceTest.java]
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
if (ds != null) {
Connection conn = ds.getConnection();
if (conn != null) {
name = "Got Connection " + conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst = stmt
.executeQuery("select id, name from
book");
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
139/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
while (rst.next()) {
name = rst.getString(2);
id = rst.getInt(1);
System.out.println("name = " + name);
System.out.println("id = " + id);
}
conn.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<servlet-mapping>
<servlet-name>MysqlConnectDatasourceTest</servlet-name>
<url-pattern>/mysql</url-pattern>
</servlet-mapping>
[Example]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
140/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
All the rows and columns of the result of retrieving data are set in ResultSet Object. The
data of one row is obtained by calling next() method. Calling another next() method moves
cursor (pointer of the data) to the next row, so that the data of the next row can be referred.
next()
ID Name Password
next()
0001 John ******
next() 0002 Pablo ******
0003 Susana ******
Figure 54 – JDBC next method of ResultSet
When the ResulSet is created, the first row is pointed by calling first next() method. After that
it points to the data of next row. While the row is valid, the next() method returns true. It
returns false when it arrives at the end of data.
The getter method is to retrieve the data in the columns of the "ResultSet". The data in the
actual row is obtained either by column number or by column name. The getter method has
getXXX format for all eight primitive types. For example getInt() method returns int type and
getLong() returns long type. The getDate() and getTime() returns Date and Time of
"java.sql" package respectively.
[Example of ResultSet]
String strQuery = "SELECT * FROM emp";
ResultSet rs = stmt.executeQuery(strQuery);
int i_ID;
String strName;
String strPwd;
while(rs.next()){
i_ID = rs.getInt("ID");
strName=rs.getString("NAME");
strPwd=rs.getString(3); // Get the third column
}
✩ You can get the data from "ResultSet" by column name or by column number.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
141/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
☆ Inside the SQL string, single quotation (') is used to indicate the value.
☆ When executeUpdate() method is called, it returns an int value that identifies the number
count of modified rows by SQL statement.
}finally{
try {
rs.close();
stmt.close();
conn.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
✩ In this manual this connection close is not always described due to saving of coding
space, but if you implement some database access, it is better follow this way of close
connection.
4.4.5. PreparedStatement
PreparedStatement is a statement prepared before the execution of SQL statements. The
database server checks the statement for syntax error, prepare a plan and execute it. The
SQL is precompiled in PreparedStatement. This improves the performance at the time of
execution.
[Example]
PreparedStatement ps = con.prepareStatement(
"UPDATE emp SET name=? WHERE id=?");
ps.setString(1,"Smith");// replace the first question mark
ps.setInt(2,12345); // replace the second question mark
ps.executeUpdate();
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
143/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
1) Auto-commit mode
JDBC is set to auto-commit mode by default. The statement is automatically committed right
after it is executed individually.
2) Committing a transaction
z Start of transaction
- setAutoCommit(false)
z End of transaction
- commit()
The statements are committed together as a unit
- rollback()
The transaction is aborted and the values modified by SQL statements are
returned to the previous values
[MysqlTransactionTest.java]
import java.sql.*;
String url =
"jdbc:mysql://localhost/ictti?user=root&password=root";
Connection conn = null;
Statement stmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
strSQL = "INSERT INTO emp(empno, ename, sal)" +
"values (102, 'Commit2', 0102)";
iRowCount= stmt.executeUpdate(strSQL);
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
144/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
conn.commit();
}catch (SQLException e){
e.printStackTrace();
try {
conn.rollback();
System.out.println("The data is roll backed.");
} catch (SQLException e1) {
e1.printStackTrace();
}
}catch (ClassNotFoundException e){
System.out.println("The JDBC driver not found" +
e.getMessage());
}
}
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
145/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
rs.absolute(3);
rs.updateString(2, "Clinton"); ID Name Password
rs.updateRow(); 0001 John ******
0002 Pablo ******
0003 Clinton ******
0004 Camila ******
[MysqlResultsetUpdateTest.java]
import java.sql.*;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
146/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
conn.close();
stmt.close();
rs.close();
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFound in
Class.forName()");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Creates a Statement object that will generate ResultSet objects with the given type and
concurrency.
The first parameter represents resultSetType and the second parameter represents
resultSetConcurrency:
Table 19 - resultSetType
resultSetType Description
ResultSet.TYPE_FORWARD_ONLY Cursor movement forward only
ResultSet.TYPE_SCROLL_INSENSITIVE scrollable but generally not sensitive to
changes made by others
ResultSet.TYPE_SCROLL_SENSITIVE scrollable and generally sensitive to changes
made by others
Table 20 - resultSetConcurrency
resultSetConcurrency Description
ResultSet.CONCUR_READ_ONLY may NOT be updated
ResultSet.CONCUR_UPDATABLE may be updated
2) Add by ResultSet
-moveToInsertRow
-insertRow
[Example]
rs.moveToInsertRow(); //move to the InsertRow
rs.updateInt(1,0005); //set the column
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
147/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
rs.updateString(2,"Bush");
rs.updateString(3,"pwd001");
rs.insertRow();
ID Name Password
0001 John ******
0002 Pablo ******
0003 Clinton ******
0004 Camila ******
0005 Bush pwd001
3) Delete by ResultSet
-deleteRow
[Example]
rs.absolute(5);
rs.deleteRow();
ID Name Password
0001 John ******
0002 Pablo ******
0003 Clinton ******
0004 Camila ******
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
148/298
S-EA-A-1.0
JDBC <Day 4>
How to retrieve and modify data
rather than sending each update separately. This will improve the performance because of
the traffic cut between the server and client. The transaction should be set false to
auto-commit mode so that the multiple statements can be sent together as the same
transaction.
// Set transaction to manual mode
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO emp VALUES (1001, 'Pablo')");
stmt.addBatch("INSERT INTO departments VALUES (10, 'Product')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1001,10)");
int [] updateCounts = stmt.executeBatch();
// Commit all the insert statement together
con.commit();
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
149/298
S-EA-A-1.0
JDBC <Day 4>
Exercise 5 – JDBC programming
The "emp" table and web application structure that are used in this exercise are as follows:
☆ Please replace "localhost" to the database name if the database server is not located in
your own machine.
- EMPNO; 10
- ENAME; "Pablo"
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
150/298
S-EA-A-1.0
JDBC <Day 4>
Exercise 5 – JDBC programming
- SAL; 9999
(6) Print out the data retrieved from the above data.
In the template "web.xml", the servlet is configured to be able to be called with "servlet"
mapping name.
☆You can not insert twice the same data to the database since the "empno" column is a key
of the table. You have to delete the data before execution if the data already exists.
(4) Print out all data retrieved from the above data.
- EMPNO; 10
- ENAME; Smith
[PreparedStatement]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
151/298
S-EA-A-1.0
JDBC <Day 4>
Exercise 5 – JDBC programming
2) Retrieve the data and print them out the same way as the previous exercise.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
152/298
S-EA-A-1.0
J2EE architecture <Day 5>
Application architecture
z Reusability
Application architecture designs the reusability of the component, such as the business
logic that can be shared and reused in the enterprise.
[example]
- Session logic of the User Interface
- User control of the User Interface
- Validation of the input parameter of the User Interface
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
153/298
S-EA-A-1.0
J2EE architecture <Day 5>
Application architecture
- Tax calculation
-
z Scalability and maintainability
Generally a user requirement tends to change or expand according to the market
demand during the system life cycle. If all logics such as user interface, database
access, and business logics are included in one component together, it is quite
complicated to expand and modify the system. In case some exception happens, it
takes a lot of time to locate where the problem resides. It is also possible that another
web server or web application server will be installed additionally due to the increase of
user access. The purpose of application architecture is to be expandable considering
the scalability and maintainability of the system.
[example]
- Load balancing of Web server
- Integration to other external system (ERP, Legacy system, Other platform, etc)
- Clustering of Web Application Server
- Mirroring system of DBMS (Always having mirror of the Database)
z Portability
According to the requirements of scalability and maintainability, sometimes the
immigration or replacement from one physical component to another will occur. In that
case, if the software component resists to those changes of platform, dramatically the
time and cost are saved. The application architecture also discusses the possibility of
the portability, for example in case of changing DBMS, if the data access component is
made independent to the DBMS, the high portability is expected. If the business logic
components are limitedly placed in the business tier, changing application server will
not affect to the business logic, The idea of multi tiers is one of the examples to be able
to realize the portability.
[example]
- Replace application server of Tomcat to JBoss
- Replace PostgreSQL to Oracle
- Replace Mycrosoft to Linux
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
154/298
S-EA-A-1.0
J2EE architecture <Day 5>
Application architecture
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
155/298
S-EA-A-1.0
J2EE architecture <Day 5>
Application architecture
Business logic,
Business tier
transactions
Session Bean Entity Bean
The multi tiered architecture represents logical tiers for the distributed Web application. The
software components are placed in the tier according to its character of the service or
process. The tier is also convenient to apply to physical tiers in order to discuss how to
distribute the physical components.
The tier represents the independency of software and hardware to any other tier. For
example the software component that implements the business logic is confined just inside
the Business tier so that in case of any modification of this tier does not affect to other tiers.
The developer can quickly find where to modify, which source to change in those cases.
This contributes to the maintainability and scalability.
✩ Sharing some details with other tier increases coupling between tiers. For example,
HttpServletRequest is a Presentation-tier data structure, that should not be passed to the
next tier of Business tier same as the object ReIsultSet, the data structure of JDBC should
be confined inside the Business Logic, and should not be passed to the JSP or Servlet as a
raw data.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
156/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
✩ The tier is also applicable from the portability point of view, since it is independent
physically. For example, the Presentation tier corresponds to the Web tier where Web
Application Server is located. The Business tier corresponds to the Enterprise Java Bean
tier where EJB container can be located. In case of some replacement from one application
server to another server, or from POJO(Plain Old Java Object) to EJB or Vice Versa, this
logical independency contributes to high portability and scalability.
Model
(Bean)
View Controller
(JSP) (Servlet)
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
157/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
Business
logic
Generate view Select next view
Servlet
get DB data
HTML output
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
158/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
z JSP Model1
JSP first appeared in 1998. The official versions, 1.0 and 1.1, both appeared in 1999. Since
Java code can be embedded into static HTML content without need to compile, the JSP
technique was widely accepted. It is possible to include all the business logic, or database
access logic in JSP tags. A Model 1 architecture consists of a Web browser directly
accessing Web-tier JSP pages
JSP
get DB data
HTML output
z JSPModel1.5
Another model of JSP is that POJO(Plain Old Java Object) is used to separate the business
logic and database access logic. The JSP pages access to Java Objects that represent the
application model,
JSP POJO
get POJO
get DB Data
HTMLdesign
z JSPModel2(MVC2)
Model 2 architecture introduces a controller servlet between the browser and the JSP pages.
As a business layer, Plain Old Java Object (not EJB) is introduced.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
159/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
Servlet POJO
call POJO
get DB Data
call next jsp
JSP
get POJO
HTMLdesign
Servlet EJB
call POJO
get DB Data
call next jsp
JSP
get POJO
HTMLdesign
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
160/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
z Reusability
Since the each element is concentrated in each role, it can be reusable in other systems or
other applications. Especially if the business logic is described independently, the reusability
is quite high.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
161/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
MVC.html
(1)
EmpServlet EmpAccess
emp
Get request Get Data table
from browser
Generate Set data (3)
EmpAccess to (2) to EmpBean
process data
salary.jsp Bean is returned (4)
Get data from with necessary EmpBean
Bean (6) data. (5)
Set data to the Transfer control name
dynamic part to JSP together
and convert the with EmpBean salary
file to HTML
get/set
(7)
salary.jsp
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
162/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
(2) The EmpServlet (= Controller) receives the request from the browser. It obtains the
Name parameter. The Servlet then instantiates the EmpAccess class (= Model) passing the
Name parameter to process data.
(3) The EmpAccess class gets the salary data from the emp table.
(4) The EmpAccess class sets the salary data to the EmpBean by setSalary() method.
(5) The EmpServlet gets return of EmpBean that contains salary data.
(6) The EmpServlet sets the EmpBean to the request object and transfers control to
sajary.jsp (=View).
(7) The salary.jsp sets salary data to the jsp tags and converts it to HTML. The jsp sends
the response to the browser.
(8) The result page of salary.jsp is shown displaying the salary of the employee.
[mvc.html]
<html>
<head>
<title>MVC Exercise</title>
</head>
<body>
<h1>Salary of employee</h1>
Input the name of employee whose salary you want to know.<br>
<form action="servlet/controller.EmpServlet" method="POST">
Name:<input type="text" name="Name">
<input type="submit" value="get salary" >
</form>
</body>
</html>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
163/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
[EmpServlet.java]
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.EmpAccess;
import model.EmpBean;
req.setAttribute("myBean", empBean);
The setAttribute() method stores an attribute in this request. This method is most often used
in conjunction with RequestDispatcher class. The first parameter specifies the name of the
attribute and is referred with this name. The second parameter specifies the object to be
stored.
[EmpAccess.java]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
164/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
String strSQL;
// select row
strSQL = "SELECT sal from emp where ename= '" + a_strName
+ "'";
System.out.println("SQL Statement; " + strSQL);
rs = stmt.executeQuery(strSQL);
int iSal = 0;
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
165/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
e.printStackTrace();
} finally {
try {
// Close the objects
rs.close();
stmt.close();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return empBean;
}
}
[EmpBean.java]
package model;
[salary.jsp]
<jsp:useBean id="myBean" class="model.EmpBean" scope="request"/>
<html>
<head>
<title>MVC Exercise</title>
<head>
<body>
<h1>The result of the MVC exercise </h1>
<table border="1">
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
166/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
<tr>
<td>Employee name </td>
<td><jsp:getProperty name="myBean" property="name"/></td>
</tr>
<tr>
<td>Salary</td>
<td><jsp:getProperty name="myBean" property="salary"/></td>
</tr>
</table>
<input type="button" value="return"
onclick="javascript:history.back()">
</body>
</html>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
167/298
S-EA-A-1.0
J2EE architecture <Day 5>
MVC architecture
WebApplication directory
mvc.html
jsp
salary.jsp
WEB-INF
src
controller
EmpServlet.java
model
EmpAccess.java
EmpBean.java
web.xml
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
168/298
S-EA-A-1.0
J2EE architecture <Day 5>
Exercise 6 – J2EE
Exercise 6 – J2EE
1. Practice the Web application "Salary of Employee" of MVC pattern referring to the
textbook.
2. SQLWorkpad exercise. Make SQLWorkpad application that shows the result of the
execution of Query in the specified the table of database. MySQL is used for database.
1) The first page is static page ("sqlwp1.html") where the following parameters can be
input.
Table 25 - Input Parameters for SQLWorkPad
Parameters Type length Description
USER_ID Textbox 20 User id for DB connection
PASSWORD Textbox 20 Password for DB connection
DBNAME Textbox 20 Database name for DB
connection
QUERY Textarea SQL Query to be executed.
[sqlwp1.html]
4) Make a program that receives the parameters from the browser and execute the
specified Query connecting the Database. Show all the result of the Query in the
next page.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
170/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
What is Struts Framework
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
171/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
Struts also provides quite rich Tag library for JSP to avoid using scriptlet.
7) If the following page appears, the necessary packages are set correctly into your
project.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
172/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
✩ Since Struts is not a software but a framework, it is required only to deploy (copy) the
libraries to the Servlet container. The necessary packages to use Struts exist in
"WEB-INF/lib" directory in the "struts-blank-xxx.war" file.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
173/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
Business
Struts Framework
Logic
Struts-config.xml
POJO
1) 2)
Action ActionForm EJB
Servlet Bean
3)
7) 4)
8) 6) 5)
JSP Action Class
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
174/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
175/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
Business
/StrutsPrj (Context)
Logic
Struts-config.xml
jsp/Hello.jsp POJO
action= 1) 2)
"/HelloPath"
Action ActionForm Bean EJB
Servlet (action/HelloForm.java)
3)
7) 4)
8) 6) 5)
JSP Action Class
(jsp/Greeting.jsp) (action/HelloAction.java
)
[sturts-config.xml]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<!-- ========= Form Bean Definitions --> Name used in this file to indicate
<form-beans> ActionForm Bean. The input
data is stored in this class.
<form-bean This name is also used in JSP
as bean name.
name="BeanNameHelloForm"
type="action.HelloForm"/> ActionForm Bean class name
</form-beans>
<!-- ========= Action Mapping Definitions -->
<action-mappings>
<action Action class name that is called
name="BeanNameHelloForm" from JSP with path name
"/HelloPath"
type="action.HelloAction"
scope="request">
The name of next page that is
<forward name="forwardHello" dispatched from Action class
path="/jsp/Greeting.jsp" />
</action> The real path of the next page
</action-mappings>
Once the JSP describes <Form action="/HelloPath">, the Struts can understand;
- "action.HelloForm" is the action bean class where the input parameter will be
stored.
- "action.HelloAction" is a class that will be called on the server to execute necessary
process.
- if "action.HelloAction" class wants to forward the next page to "forwardHello", Struts
understands that its real file path is "/jsp/Greeting.jsp".
- If the <bean:message> tag is described in JSP, Struts looks for
"MessageResources" class.
✩ "struts-config.xml" is not reloaded by Tomcat on modification. If you modify the file, you
need to reload the application. If you modify the xml file, at the same time adding some
change in java source file will cause the application to reload.
3) ActionForm
ActionForm is a kind of data object class where the input parameters data are defined with
getter/setter method, so that Struts automatically stores the data obtained from the browser.
[HelloForm.java]
package action;
import org.apache.struts.action.ActionForm;
In this form bean class, "name" instance variable and its get/set methods are defined. The
input parameter value of textbox from "Hello.jsp" will be set in the "name" variable by Struts.
✩ It is not any more necessary to use getParameter() of Request object to get input
parameter. Instead you need to create this ActionForm class with all the necessary input
data.
4) Action class
Action class is the main class in the framework. Some data access logic or other business
logic will be called from action class passing the Bean class that contains input data as a
parameter. In this case, since there is no special process to do, the next page is called and
forwarded.
[HelloAction.java]
package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
Your action class always needs to extend Action class and override the execute() method.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
178/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
ActionForm object is passed as one of the parameter of execute() method with input
parameter data inside. You can get the subclass by casting;
HelloForm myFormBean = (HelloForm)ActionForm;
String strName=myFormBean.getName();
5) View; Hello.jsp
As a view, usually JSP is used although it is not the only solution. Struts provided quite rich
tag library.
[Hello.jsp]
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
<html:html>
<Title>HelloWorld with Struts
<BODY>
<!-- Converted to Form tag -->
<html:form action="/HelloPath" >
<BR>
Please input your name<BR><html:text property="name" /><BR>
<html:submit>
<bean:message key="mysubmit" />
</html:submit>
</html:form>
</BODY>
</html:html>
To use Struts tags, it is necessary to declare taglib directory specifying its URI and prefix.
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
179/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
The above Struts html form tag is converted to HTML Form tag as follows.
<form name="HelloForm" method="post"
action="/StrutsPrj/HelloPath.do">
✩ The action path is created with Web context name and the extension ".do" which is
mapped to the Struts ActionServlet class.
The following code shows the <bean;message> tag. This tag is used to retrieve an
internationalized message for the specified locale, using the specified message key, and
write it to the output stream. The message file name is obtained from the message source.
The value will be extracted with the key name "mysubmit".
<bean:message key="mysubmit" />
The result of the conversion of Struts tag will be;
<input type="submit" value="click here">
You will prepare the message resources file with the name defined in the "struts-config.xml".
<!-- ================ Message Resources Definitions -->
<message-resources parameter="MessageResources" />
</struts-config>
The MessageResources file has the extension "properties". This file is located where
CLASSPATH is passed, such as "WEB-INF/classes" directory.
[MessageResources.properties]
greeting=Hello
welcome=Welcome
error=The error happens.
mysubmit=click here
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
180/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
✩ If the message-resources file has directory structure, parameter name is separated by ".".
For example, if the message file is located in
"WEB-INF/classes/java/MessageResources.properties", then its definition will be;
<message-resources parameter="java.MessageResources" />
✩ In Eclipse environment, properties file can be created under "/src" directory, so that each
time you save it, Eclipse automatically copies it under "/classes" directory.
6) View;Greeting.jsp
"Greeting.jsp" is a page that is shown as a result of request of the previous page. The
"name" input parameter in the first page is obtained from the java bean class which is set
automatically by Struts.
[Greeting.jsp]
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
<html:html>
<BODY>
<H1>
<bean:message key="greeting" />
<!-- Show the name sent from previous page -->
Ms. <bean:write name="BeanNameHelloForm" property="name" />
<br>Welcome to our HelloWorld with Struts!
</H1>
</BODY>
</html:html>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
181/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
How Struts works
This extracts the java bean named "BeanNameHelloForm" in the scope of Page, Request,
Session or Application object. The value of the property "name" will be shown in the page
executing getName() method of "BeanNameHelloForm" bean.
✩ The bean name should be the same as the bean name specified in the
"struts-config.xml".
7) web.xml
In the web.xml the following struts Servlet should be configured.
<!-- Standard Action Servlet Configuration -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-cl
ass>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
8) Directory structure
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
182/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
StrutsPrj
WEB-INF
struts-config.xml
web.xml
Classes
MessageResources.properties
action
HelloForm.class
src HelloAction.class
MessageResources.properties
action
HelloForm.java
HelloAction.java
lib
struts-core-1.3.8.jar
struts-taglib-1.3.8.jar
jsp
Hello.jsp
Greeting.jsp
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
183/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
✩ This textbook does not cover all the Struts Custom Tag and its attributes. Please refer to
the Struts document for detail specifications under "docs" directory of Struts install directory.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
184/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
[example]
Let's create a sample program using Struts HTML Tag Library. The first page is as follows;
[first page]
After submit the page, the values of input parameter will be shown;
[result]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
185/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
[jsp/HTMLTagTest.jsp]
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html:html>
<head><title>Struts HTML Tag Library example</title></head>
<body>
<H2>
Struts HTML Tag Library example
</H2>
<%-- (10)<html:reset>--%>
<html:reset value="reset"/>
</html:form>
</body>
</html:html>
[jsp/result.jsp]
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
187/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
<html:html>
<head><title>Struts HTML Tag Library Test Result</title></head>
<body>
<br> Comment ;
<bean:write name="MyTagBean" property="other"
scope="request" ignore="true" />
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
188/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
</body>
</html:html>
"MyTagBean" is the name of FormBean. All the input parameters using HTML Tag Library in
the first page are set to the properties of FormBean. Those values can be retrieved from the
bean in the next JSP page. <bean:write> tag is a bean tag that output the value of the
property in the specified bean.
[struts-config.xml]
<?xml version="1.0" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
</struts-config>
[TagFormBean.java]
package action;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
189/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
import java.util.LinkedList;
import java.util.List;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;
//(1)Declare Bean
public class TagFormBean extends ActionForm {
this.mypassword = mypassword;
}
public List getChoices(){
List list=new LinkedList();
list.add(new LabelValueBean("red","1"));
list.add(new LabelValueBean("green","2"));
list.add(new LabelValueBean("yellow","3"));
return(list);
}
}
All the input parameters are specified as instance values in the FormBean. Since the
multibox for hobby returns multiple values, the String array is declared.
<html:optionsCollection> can define the values and labels dynamically from the program. In
this sample, the values are created in the FormBean and provides the getChoices() method
to return collection as List type The "org.apache.struts.util.LabelValueBean" is a class that
has label and value property provided by Struts.
public List getChoices(){
List list=new LinkedList();
list.add(new LabelValueBean("red","1"));
list.add(new LabelValueBean("green","2"));
list.add(new LabelValueBean("yellow","3"));
return(list);
}
✩ The array used for collection should be initialized in the constructor. If the array is not
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
191/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
created, the exception "Collection not found" occurs when none of the option is selected.
// Constructor. Initialize the array for hobby
public TagFormBean() {
hobby = new String[0];
}
1) <bean:define> tag
Defines new bean with specified name.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
192/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
[example 1]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:define id="mySalary" name="employee" property="salary"
type="java.lang.Integer" />
[result 1]
If the salary property of employee bean contains "100,000" then ;
100000
[example 2]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:define id="myVar toScope="session" value="Hello">
[result1]
Hello
The new variable named "myVar" has value "Hello" and available within session
scope.
2) <bean:size> tag
Obtain the size of collection and creates a new bean, of type "java.lang.Integer", whose
value is the number of elements in that collection.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
193/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
[example 1]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:size id="mySize" name="list" scope="session"/>
Search the Bean named "list" from session scope and store the list.size to "mySize"
variable.
[example 2]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:size id="mySize" name="mybean" property="list" />
Get the bean named "mybean" from where the property named "list" is obtained. In the
variable "mySize" the list size is counted.
[example 3]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:size id="mySize"
collection="<%= request.getParameterValues("myCheckBox") %>" />
Get the parameter values named "myCheckBox" and its size is stored to "mySize" variable.
3) <bean:write> tag
Output the content of Bean within the scope.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
194/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
scope The scope of the Bean to be accessed. If not specified, the available String
scopes are searched in ascending sequence.
[example 1]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:write name="name" scope="session" />
Output the bean named "name" in the session scope.
[example 2]
<%@ taglib uri="http://struts.apache.org/tags-bean" %>
<bean:write name="user" property="name" scope="session" />
Output the value of property named "name" from the bean named "user" in the session
scope.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
195/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
1) <logic:iterate> tag
This tag repeats the nested tag content until the end of specified collection.
[example 1]
<%@ taglib uri="http://struts.apache.org/tags-logic"
prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
<logic:iterate> tag get the String array collection of "froots". Each element is stored in
"myFroots". <bean:write> tag output the value of the variable "myFroots".
[result]
* orange
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
196/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Custom Tag
* apple
* banana
[example 2]
<logic:iterate id="text" collection="<%=strsFroots %>" offset="1"
length="2">
<bean:write name="text" /><br>
</logic:iterate>
This is an example of using collection attribute. The offset is 1, and the number of iteration is
2.
[result]
apple
banana
2) Conditional logic
<logic:equal>, <logic:notEqual>, <logic:greaterEqual>, <logic:greaterThanEqual>,
<lessEqual>, <lessThan> tag compares the specified value with the value of Java bean,
cookie, HttpRequest, or Http header. If the expression is true, the body tag will be executed.
[example]
<logic:equal name="MyTagBean" property="color" value="1">
Red.
</logic:equal>
If the value of color property of bean named "MyTagBean" equals to "1" then, "Red" will be
output.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
197/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
[How to set]
1) In your form bean class override the validate() method.
2) Write the validation in the validate() method.
3) In case of error, set error content to ActionErrors class that is the return value of the
validate() method.
4) Add "validate" and "input" attribute in the "struts-config.xml"
5) Define the error message to be displayed in the message resources file.
[How it works]
1) In case No error;
AcctionErrors class always contains ActionMessage class. If no error happens, Struts
returns either null or a zero-length ActionErrors instance, and the controller servlet will
proceed to call the execute method of the appropriate Action class.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
198/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
ActionErrors=null
return ActionErrors
null
ActionErrors? Action execute(){
if ((getName()==null)||("".equals(getName()))){
errors.add("name",
new ActionMessage("errors.namerequired"));
return errors;
Check if the "name" input has value. If it is null or space, then it is considered as error. By
add() method of "ActionErrors" class, set "ActionMessage" object to "ActionErrors".
"ActionMessage" is created indicating what error message will be shown extracting from
"MessageResources" file. The "errors.namerequired" is a key in the "MessageResources"
file to get error message.
4) MessageResources file
errors.prefix=<FONT color="#FF0000">
errors.suffix=</FONT>
# -- validator --
errors.namerequired= Please input your name.
In the MessageResources file (with extension of "properties"), the constant messages are
defined with key. "errors.namerequired" key has "Please input your name" value, which is
reffered by "ActionMessage".
"errors.prefix" and "erros.suffix" are keys that are shown as prefix and suffix respectively in
case of error. For example, if the "ActionMessage" is set as follows;
errors.add("name",
new ActionMessage("errors.namerequired"));
then
<FONT color="#FF0000">
Please input your name.
</FONT>
will be described in HTML and the error message is shown in red.
4) struts-config.xml
<action path="/govaltest"
validate="true"
input="/jsp/ValidateTest.jsp"
type="action.ValidateAction"
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
200/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
name="MyTagBean"
scope="request">
<!-- (3)Where to dispatch -->
<forward name="result" path="/jsp/result.jsp"/>
</action>
In the "struts-config.xml", "validate" attribute is set to "true" to be valid the validation. The
"input" attribute indicates the page that is forwarded in case of error exists.
This tag extracts String, String array or ActionErrors object from scope. In this case, it looks
for the "name" property from the ActionErros and shows the error message that is stored in
ResourceMessages file.
Additionally, the following plug-in tag will be required to load Validator Resources.
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/org/apache/struts/validator/validator-rules.xml,
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
201/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
/WEB-INF/validation.xml"/>
</plug-in>
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.util.LabelValueBean;
import org.apache.struts.validator.ValidatorForm;
//Declare Bean
public class MyValidatorForm extends ValidatorForm{
private String name;
private String age;
// Access method
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
2) validation.xml
This error configuration file describes validator rule to be applied and the message to be
shown.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
202/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
<form-validation>
<formset>
<!-- Validator form -->
<form name="MyValidatorBean">
<field
property="name"
depends="required">
<arg key="name" resource="false"/>
</field>
<field
property="age"
depends="required,intRange">
<arg position="0" key="age" resource="false"/>
<arg position="1"
name="intRange"
key="${var:min}"
resource="false"/>
<arg position="2"
name="intRange"
key="${var:max}"
resource="false"/>
<var>
<var-name>min</var-name>
<var-value>10</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>80</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
<form name="MyValidatorBean">
The error configuration is specified for each bean form. The name of form should match the
action element's name attribute in "struts-config.xml".
property="name"
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
203/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
depends="required">
This specifies the property to be validated. "depends" attributes indicates the content of
validations. Struts has standard built in validations defined in "validator-rules.xml". The
built-in validations are associated with the default error message key which values are
defined in the message resources properties file. The following table shows some of the
rules used frequently.
Table 37 - Struts standard built in validations
rule remarks Default error message key
required mandatory field validation. errors.required
minlength validate input data isn't less than a specified errors.minlength
minimum length.
maxlength validate input data doesn't exceed a specified errors.maxlength
maximum length.
mask validate format according to a regular errors.invalid
expression.
integer validates that a field can be converted to an errors.integer
Integer.
intRange validates that an integer field is within a errors.range
specified range.
z With <arg> tag, some parameters can be specified to replace the message resources
file. For example the following <arg> tag specifies the parameter with "name" as
character.
<arg key="name" resource="false"/>
z If the message resource file has a key "errors.required" as follows;
errors.required={0} is required.
the paramer {0} will be replaced with "name", and "name is required" will be generated as
the error message. If resource="false" is omitted, then the system searches the key named
"name" in the message file.
For the validation of "age", "required" and "intRange" validations are applied to the field.
property="age"
depends="required,intRange">
The same as the case of "name", if "age" field does not have any input, then "age is
required" message will be shown according to the next <arg> tag..
<arg position="0" key="age" resource="false"/>
The following <arg> tag shows how to set the error message for intRange rule.
<arg position="1"
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
204/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
name="intRange"
key="${var:min}"
resource="false"/>
<var>
<var-name>min</var-name>
<var-value>10</var-value>
</var>
position="1" means the second parameter for "intRange" error that corresponds to the key
"errors.range" in message file. "${var:min}" means that a variable that is specified in <var>
tag with <var-name>, that is value 10, will be replaced with the second parameter. The error
message defined in the message resource file by default is;
errors.range={0} is not in the range {1} through {2}.
As a result of the definition for "intRange", if the value in the age field has range error, then
the following message will be shown;
age is not in the range 10 through 80.
3) Action file
There is nothing special to define in action file for validation. It is created as usual and the
business logic is called.
[action/ValidateAction.java]
package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
205/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Struts Validation
return mapping.findForward("result");
}
}
4) jsp file
The same as the validate() case, <html:errors> shows the error message to HTML in case of
field error.
name <html:text property="name" size="16"/><br>
<html:errors property="name" />
<br>
age <html:text property="age" size="2"/>
<br>
<html:errors property="age" />
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
206/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Exercise 6: Apache Struts
1. Create "StrutsPrj" project in Eclipse with Tomcat. Locate necessary files to create
"HelloWorld" described in the textbook. Execute it from the browser if the programs and
configuration files are set correctly.
2. Create "StrutsValidationPrj" project in Eclipse with Tomcat. Create the jsp named
"ValidatorTest.jsp" file which validates "required" validation for "name" and "age" field,
"Integer" and "intRange" validation for "age" field.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
207/298
S-EA-A-1.0
Framework; Apache Struts <Day6>
Exercise 6: Apache Struts
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
208/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
What is Spring Framework
Let's see some example of isolating the interface and implementation of the program.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
209/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
1) The first Hello program that we create when we start to learn Java Language will be like;
[MyFirstHello.java]
public class MyFirstHello {
public static void main(String[] args) {
System.out.println("Hello Pablo");
}
}
As you understand, in this example the main() method directly outputs the message "Hello
Pablo". In case the people name changes, or the way to output the message changes, the
program should be recompiled.
2) Let's separate the compoment so that the program will be more generalized one.
[HelloServiceWithoutInterface.java]
public class HelloServiceWithoutInterface {
String i_strPersonName;
public void printHello() {
System.out.println("Hello," + i_strPersonName);
}
public void setPersonName(String strName) {
i_strPersonName = strName;
}
}
In this class the name of person is still unknown until it is set from outside. The printHello()
method decides how the message is printout.
The main program that calls the above program will be;
[HelloWithoutInterface.java]
public class HelloWithoutInterface {
/**
* Hello program without using Interface
*/
public static void main(String[] args) {
HelloServiceWithoutInterface helloService =
new HelloServiceWithoutInterface();
helloService.setPersonName("Pablo");
helloService.printHello();
}
}
Now the person name other than "Pablo" can be set from main program. The way to output
the message is declared in the HelloServiceWithoutInterface class which is instantiated by
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
210/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
"new" keyword from main program. As a result this program is more flexible than the
previous "MyFirstHello" class due to no need of recompilation in case of the change of
person name. But What is the problem?
z The main program can not be compiled until the called program is created, since the
main program needs to know the exact class name (HelloWithoutInterface) and its
method names.
z When the main program needs to change to call another better program to output the
message, the modification of the class name should occur. All the class type with the
class name also should be modified.
HelloWithoutInterface HelloServiceWithoutInterface
setPersonName(){};
printHello(){};
myHello.setPersonName("Yuko");
myHello.printHello();
}
✩ The above case seems that only the instantiation of the class is affected, but also the
class type will be affected if it is used as parameter or return of a method. For example;
private NewHelloServiceWithoutInterface getService(){
return new NewHelloServiceWithoutInterface();
…
NewHelloServiceWithoutInterface service = getService();
service.printService();
}
3) Let's separate interface and implementation to be more independent of the person name
and of the way to output.
[HelloServiceInterface.java]
public interface HelloServiceInterface {
public void setPersonName(String strName);
public void printHello();
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
211/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
/**
* Hello program without Interface
*/
public static void main(String[] args) {
// Instantiate HelloImpl
HelloServiceInterface helloInterface =
new HelloServiceImpl();
helloInterface.setPersonName("Pablo");
helloInterface.printHello();
}
}
The HelloServiceImple class is instantiated with HelloServiceInterface type. As long as the
interface is defined, the method names are already known. Since all the reference to the
implemented class is pointed to interface name, in case of change of implemented class, no
modification is required except the following part ;
HelloServiceInterface helloInterface =
new HelloServiceImpl();
Here the implemented class name is specified explicitly in the program and its reference is
returned to the interface type.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
212/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
myHello.setPersonName("Pablo")
; Change
myHello.printHello();
NewHelloServiceImpl
setPersonName();
printHello();
4) Let's try DI container to see how the implemented class is defined in the configuration file.
✩ Set classpath to the following files;
- /dist/spring.jar
- /lib/Jakarta-commons/commons-logging.jar
[MySpringConfig.xml]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xs
d">
<bean id="serviceID" class="HelloServiceImpl">
<property name="personName" value="Pablo"/>
</bean>
</beans>
The <bean> tag specifies the classes that will be instantiated by DI Container.
The "HelloServiceImpl" class is defined with the name "serviceID". The property
"personName" of "HelloServiceImpl" will have the default value "Pablo". Place this file to
where file path is passed (for example, the project root directory if you use Eclipse).
[HelloWithSpring.java]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
213/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
HelloServiceInterface service =
(HelloServiceInterface) factory.getBean("serviceID");
The bean class that is defined in the configuration file with the name "serviceID" is loaded
that corresponds to "HelloServiceImpl" according to the definition. The default value "Pablo"
for the property "personName" defined in the file also is set at the same time.
[result]
Hello,Pablo
2007/04/27 10:21:49
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
information: Loading XML bean definitions from file
[C:\Data\Myammer\ashare\workspaceWin\SpringTestPrj\MySpringConfig
.xml]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
214/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
In this way, the implemented class name disappeared from the source code and only the
interface name remains, which means that in case of replacing the implemented class to
another, no any modification happens just changing the external configuration file.
DOES NOT
depend any
more HelloServiceImpl
setPersonName();
printHello();
Class HelloWithSpring{
As a result instantiation of the class with "new" keyword does not exist since the
implemented class is not created by caller program but by DI Container who passes the
reference of the class to the caller program. The following figure demonstrates the class
diagram to show the relationship between components.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
215/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring DI Container
HelloWithSpring <<interface>>
HelloServiceInterface
<<use>> +setPersonName()
+printHello();
<<use>>
HelloServiceImpl
Spring Framework <<create>>
-personName
+setPersonName();
+printHello();
Since the dependency of the components is injected by the Container, this mechanism is
called Dependency Injection.
The bean objects declared in the <bean> tag are loaded when getBean() method is called
with its id name. <ref> attribute is specified to refer to another object which is also loaded at
the time of calling getBean() method according to the definition in <bean> tag.
✩ When property value or reference is set by Spring, setter method for each property is
required since the container uses it.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
217/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Struts in Web Application
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
218/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Struts in Web Application
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
219/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Struts in Web Application
[struts-config.xml]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<!-- ========= Form Bean Definitions -->
<form-beans>
<form-bean
name="LogSimpleForm"
type="action.LoginForm"/>
</form-beans>
<!-- ========= Action Mapping Definitions -->
<action-mappings>
<action
name="LogSimpleForm"
type="org.springframework.web.struts.DelegatingActionProxy"
path="/LoginSimplePath"
scope="request">
<forward name="forwardLogin"
path="/jsp/ResultLoginSimple.jsp" />
</action>
</action-mappings>
[action-servlet.xml]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
>
<bean name="/LoginSimplePath" class="action.LoginSimpleAction">
<property name="personName" value="Pablo" />
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
220/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Struts in Web Application
</bean>
</beans>
In the "action-Servlet.xml", the bean name is defined as the same path name declared in
"struts-config.xml", so that DelegatingActionProxy can understand which class is user
Action class. In the <property> tag, the default value is set for the variable "personName" in
LoginSimpleAction class.
[/action/LoginSimpleAction.java]
package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
return mapping.findForward("forwardLogin");
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
221/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Struts in Web Application
[/action/LoginForm.java]
package action;
import org.apache.struts.action.ActionForm;
}
LoginForm is a Struts "Form Bean" where data obtained from JSP is stored. This class is
also used to transfer data to JSP to show the data.
[/jsp/SpringLoginSimple.jsp]
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
<html:html>
<Title>Spring + Struts Simple Test
<BODY>
<!-- Converted to Form tag -->
<html:form action="/LoginSimplePath" >
<BR>
Please input your id<BR><html:text property="id" /><BR>
<html:submit>
<bean:message key="mysubmit" />
</html:submit>
</html:form>
</BODY>
</html:html>
This is JSP for first page where your id is asked to input. <html:form> specifies
"LoginSimplePath" as its action path which is a key to combine Struts and Spring framework.
The value of textbox "id" is set to LoginForm bean.
[/jsp/ResultLoginSimple.jsp]
<%@ taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
<html:html>
<BODY>
<H1>
<bean:message key="hello" />
<!-- Show the name obtained from Action Class -->
<bean:write name="LogSimpleForm" property="name" />
<br>Welcome to our HelloWorld with Spring & Struts!
</H1>
</BODY>
</html:html>
This is JSP for the result page. The user name obtained from Action class is shown.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
223/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
id Name Salary
id = 10 10 Pablo 10000
Name = Pablo
Salary=10000
The following table shows some example of HQL comparing usual SQL;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
224/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
In Hibernate Java objects are mapped to tables of Relational database. The following
configuration is an example of Mapping in Hibernate. In the <class> tag, "business.UserDto"
class is mapped to "emp" table. In the <id> tag shows the configuration of key in the "emp"
table.
class name table name
<hibernate-mapping>
<class name="business.UserDto" table="emp" lazy="true">
<id name="empno" type="integer" unsaved-value="null" >
<column name="empno" sql-type="INTEGER" not-null="true" />
<generator class="assigned" />
</id>
<property name="ename" column="ename" />
</class>
</hibernate-mapping>
All the data access information is not any more described in the source code to load JDBC
driver, but is specified in the configuration file instead. Introducing Hibernate releases
developers from;
- Description about connection
- Description about SQL Statement
- Generating Java Bean to store the result set
The Spring Framework provides powerful support for O/R mapping including Hibernate in
terms of resource management, DAO implementation support and transaction management.
When Hibernate is integrated with DI container of Spring Framework, session or transaction
can be obtained by way of Framework automatically.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
225/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
Spring Framework provides dependent modules under "lib/" directory where necessary
modules to execute Hibernate are found.
The following files are required to execute basic Hibernate features with Spring
environment;
- hibernate3.jar (%SpringDir%/lib/hibernate/)
- cglib-nodep-2.1.jar (%SpringDir%/lib/cglib/)
- jta.jar (%SpringDir%/lib/j2ee/)
- dom4j-1.6.jar (%SpringDir%/lib/dom4j/
- commons-logging.jar (%SpringDir%/lib/jakarta-commons/)
- commons-collection.jar (%SpringDir%/lib/ jakarta-commons/)
✩ The required packages depend on what functions you use and in which environment.
The version of each modules differs according to the Hibernate package you use. Please
refer to the Hibernate manual to check required modules for your environment with
corresponding version.
<hibernate-mapping>
<class name="entity.EmpClass" table="EMP">
<id name="empno" column="EMPNO" type="int" > Column in EMP table
<generator class="assigned" />
</id> Property in EmpClass
The "id" element is the declaration of the identifier property, name="empno" declares the
name of the property in "EmpClass". Hibernate will use the getter and setter methods to
access the property. The column attribute tells Hibernate which column of the "EMP" table
we use for this primary key.
<generator> tag specifies how to generate unique identifiers for instances of the persistent
class.
Table 40 - Hibernate generator
generator description
native picks identity, sequence or hilo depending upon the capabilities of the underlying
database.
assigned lets the application to assign an identifier to the object before save() is called. default.
identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL.
sequence uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in
Interbase.
hilo uses a hi/lo (high and low) algorithm to efficiently generate identifiers of type long, short or
int, given a table and column as a source of hi values.
import java.io.Serializable;
import java.util.Date;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
228/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
public EmpClass() {}
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// exception handling
System.out.println(
"Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
229/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
}
}
[HibernateStore.java]
import org.hibernate.Session;
import entity.EmpClass;
The necessary information to save data to the database is set in the entity class including its
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
230/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
primary key.
Once the entity is prepared, "save()" method of "Session" is called to store data. Internally
the "save()" method is converted to SQL insert statement.
session.save(emp);
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
231/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
action service
LoginService dao
LoginForm
<<interface>> EmpDaoImpl
EmpDao
LoginAction
entity
EmpDto
When Hibernate is integrated into Spring, Hibernate configuration file is not required, but
instead the resource information is absorbed in Spring configuration file.
1) Spring configuration file
[action-servlet.xml]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
>
<!-- Bean Configuration for Spring + Struts sample program -->
<bean name="/LoginSimplePath" class="action.LoginSimpleAction">
<property name="personName" value="Pablo" />
</bean>
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean
">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>dao/emp.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
233/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
The following part shows data resource information for Hibernate. The information is defined
in the external file named "database.properties".
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<bean id="dbConf"
class="org.springframework.core.io.ClassPathResource">
<constructor-arg>
<value>database.properties</value>
</constructor-arg>
</bean>
<bean id="databaseConfPostProcessor"
class="org.springframework.beans.factory.config.PropertyPlacehold
erConfigurer">
<property name="location">
<ref bean="dbConf"/>
</property>
</bean>
The "sessionFactory" bean tag represents which data resource to use, and which is the
mapping file for data access. In this case, "myDataSource" is referred to get JDBC
connection. Mapping file name is "dao/emp.hbm.xml". You will notice that multiple mapping
files can be defined as <value> tag of <list>.
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
234/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>dao/emp.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect </prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
User bean "/LoginPath" is the name defined as "Action Path" in Spring. The corresponding
action class name is specified in <class> tag, same as configured in the previous chapter.
The "action.LoginAction" class refers to "business.service.LoginService" class by variable
"idLoginService". "business.service.LoginService" also contains "dao.EmpDaoImpl" class
by variable name "myUserDao". Since these two beans are dependent with other bean,
Spring can inject dependencies.
<!-- Bean configuration for Spring + Hibernate sample -->
<bean name="/LoginPath" class="action.LoginAction">
<property name="myLogService" ref="idLoginService" />
</bean>
<bean id="idLoginService" class="business.service.LoginService">
<property name="myEmpDao" ref="idEmpDao" />
</bean>
<bean id="idEmpDao" class="dao.EmpDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
The final "dao.EmpDaoImpl" class is a DAO class who needs to get access to Relational
Database according to the configuration. For that purpose "sessionFactory" bean should be
declared as its property.
<bean id="idUserDao" class="business.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import business.service.LoginService;
return mapping.findForward("forwardHello");
}
this.myLogService = myLogService;
}
}
"LoginAction" class contains the Service bean class "LoginService" which is declared in the
Spring configuration file, so that it is instantiated by DI container and the reference is set to
its variable name "myLogService".
private LoginService myLogService;
Now the Action class calls service logic where business logics are controlled.
String strName= myLogService.getUserName(strID);
import business.entity.EmpDto;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
237/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
Now the service class calls business logic where database is really accessed.
EmpDto user = myEmpDao.get(id);
✩ Let's think what are rolls of service logic class. Why is it better not to describe the
business logic directly inside the Action class?
4) DAO interface
"EmpDao" is an interface to data access to get data from database. The retrieved data is set
in entity class "EmpDto".
[business/service/EmpDao.java]
package business.service;
import business.entity.EmpDto;
import
org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import business.entity.EmpDto;
import business.service.EmpDao;
/**
* Implemented class of EmpDao to get record from emp table.
* Use Hibernate as Data Access.
*/
public class EmpDaoImpl extends HibernateDaoSupport implements EmpDao
{
public EmpDto get(Integer id) {
System.out.println("EmpDto id=" + id);
// Get access to emp table and returns retrieved data
return
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
238/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
"HibernateTemplate" is a Spring Helper class that simplifies Hibernate data access code.
Automatically converts HibernateExceptions into DataAccessExceptions, following the
org.springframework.dao exception hierarchy providing many methods that mirror the
methods exposed on the Hibernate Session interface.
In combination of "HibernateDaoSupport" and "HibernateTemplate", this allows for very
simple DAO implementations for typical requirements
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
239/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Spring + Hibernate
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
240/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Exercise 7: Spring + Hibernate
1. Create "SpringPrj" project in Eclipse with Tomcat. Locate necessary files to create a
program that shows the name of corresponding "id" described in the textbook using
Hibernate. Execute it from the browser to see if the programs and configuration files are
set correctly.
[First page]
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
241/298
S-EA-A-1.0
Framework; Spring and Hibernate<Day 7>
Exercise 7: Spring + Hibernate
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
242/298
S-EA-A-1.0
Framework Application Development<Day 8>
Simplified Application Development
This chapter provides an outlook of the alternative lightweight approaches for building J2EE
enterprise based web application by combining all the three mentioned frameworks e.g.
Struts, Hibernate and Spring.It also describes different open source projects and their use in
simplifying J2EE web application development. So, one can get an overview of these three
open source projects such as Spring, Hibernate and Struts and their use in J2EE
development.
You have two days workshop for this course. Our requirement definition is based on
“Student Payroll System”. So, we need to prepare development environment for this project.
In this application we are only concern with take the new user information and saving in the
database for authenticating the user in the future.
We are using MySQL database for this application. MySQL one of the open source, free and
widely used relational database for applications.
You all have already installed MySQL on your machine and have access to the database
server. Login to your MySQL Server and create a database "library".
1. Start mysql
# Open a Linux Terminal and Start mysql
>mysql –u root -p
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
243/298
S-EA-A-1.0
Framework Application Development<Day 8>
Designing and Creating the Database
mysql>show databases;
mysql>use accountdb;
Database changed
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
244/298
S-EA-A-1.0
Framework Application Development<Day 8>
Designing and Creating the Database
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
245/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
In this section you will learn how to download required software for our Login and
Registration Application. In this textbook, we are using one of the best technologies (Struts,
Hibernate and Spring). This textbook is very good if you want to learn the process of
integrating these technologies in your application and developed highly scalable and robust
web application.
Download Struts:
Download Hibernate:
Download Spring:
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
246/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
all the components and then compile and test your development directory structure.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
247/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
248/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
249/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
250/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
<struts-config>
<!-- ======================== Global Exception Definitions -->
<global-exceptions>
</global-exceptions>
<!-- ====================== Global Forward Definitions -->
<global-forwards>
<forward
name="welcome"
path="/Welcome.do"/>
</global-forwards>
<!-- ============================ Action Mapping Definitions -->
<action-mappings>
<action
path="/Welcome"
forward="/pages/Welcome.jsp"/>
</action-mappings>
<!-- =========================== Message Resources Definitions -->
<message-resources parameter="MessageResources" />
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
251/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- DataSource definition -->
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="dbConf"
class="org.springframework.core.io.ClassPathResource">
<constructor-arg>
<value>database.properties</value>
</constructor-arg>
</bean>
<bean id="databaseConfPostProcessor"
class="org.springframework.beans.factory.config.PropertyPlaceho
lderConfigurer">
<property name="location">
<ref bean="dbConf" />
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionM
anager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- sessionFactory definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="mappingResources">
<list>
<value>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
252/298
S-EA-A-1.0
Framework Application Development<Day 8>
Downloading the required software and integration into web application
</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
253/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
12) Create the database.properties file under the directory “ \WEB-INF\src “ as shown in the
following:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/accountdb
db.username=root
db.password=root
db.dialect=org.hibernate.dialect.MySQLInnoDBDialect
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
254/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
When the following screen is shown, choose Hibernate Configuration File under
Hibernate from the wizard. Then click Next.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
255/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
256/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
2) To configure Hibernate mapping file, right click at the project, and choose New ,then
Other.
When the following screen is shown, choose Hibernate Mapping File under Hibernate from
the wizard. Then click Next. The following screen will appear.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
257/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
258/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
259/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
In the Properties tab of Hibernate Mapping File, configure as shown in the following:
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
260/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
3) Copy the files xxx.hbm.xml under the project directory to the folder
“ \WEB-INF\ src\ com\ online\account\dao \hbm \xml “.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
261/298
S-EA-A-1.0
Framework Application Development<Day 8>
Creating hibernate mapping class by using Hibernate Synchronizer
4) In order to synchronize,
select all the xxx.hbm.xml files
click right click,
choose Hibernate Synchronizer
choose Synchronize and Overwrite
5) The hibernate synchronizer automatically create the entity files under the directory
“ com.online.account.business.entity” and “com.online.account.business.entity.base” as
shown in the following figure.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
262/298
S-EA-A-1.0
Framework Application Development<Day 8>
Login Specificaton
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
263/298
S-EA-A-1.0
Framework Application Development<Day 8>
System Structure for Login Function
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
264/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
[Staff.hbm.xml]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.online.account.business.entity">
<class
Class Name
name="Staff"
table="staff"
lazy="false" Table Name
>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
265/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
<meta attribute="sync-DAO">false</meta>
<id
Property in Entity Class
name="id"
type="integer" Data Type
column="staff_id"
> Column in Table
<generator class="identity"/>
</id>
<property
name="staffName"
column="staff_name"
type="string"
not-null="true"
length="25"
/>
<property
name="staffPassword"
column="staff_password"
type="string"
not-null="true"
length="45"
/>
</class>
</hibernate-mapping>
import com.online.account.business.entity.base.BaseStaff;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
266/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
}
[BaseStaff.java]
package com.online.account.business.entity.base;
import java.io.Serializable;
/**
* This is an object that contains data related to the staff table.
* Do not modify this class because it will be overwritten if the
configuration file
* related to this class is modified.
* @hibernate.class
* table="staff"
*/
public abstract class BaseStaff implements Serializable {
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
267/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
this.setId(id);
this.setStaffName(staffName);
this.setStaffPassword(staffPassword);
initialize();
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
268/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
/**
* Return the unique identifier of this class
* @hibernate.id
* generator-class="identity"
* column="staff_id"
*/
public java.lang.Integer getId () {
return id;
}
/**
* Set the unique identifier of this class
* @param id the new ID
*/
public void setId (java.lang.Integer id) {
this.id = id;
this.hashCode = Integer.MIN_VALUE;
}
/**
* Return the value associated with the column: staff_name
*/
public java.lang.String getStaffName () {
return staffName;
}
/**
* Set the value related to the column: staff_name
* @param staffName the staff_name value
*/
public void setStaffName (java.lang.String staffName) {
this.staffName = staffName;
}
/**
* Return the value associated with the column: staff_password
*/
public java.lang.String getStaffPassword () {
return staffPassword;
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
269/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
/**
* Set the value related to the column: staff_password
* @param staffPassword the staff_password value
*/
public void setStaffPassword (java.lang.String staffPassword) {
this.staffPassword = staffPassword;
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof
com.online.account.business.entity.Staff)) return false;
else {
com.online.account.business.entity.Staff staff =
(com.online.account.business.entity.Staff) obj;
if (null == this.getId() || null == staff.getId())
return false;
else return (this.getId().equals(staff.getId()));
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
if (null == this.getId()) return super.hashCode();
else {
String hashStr = this.getClass().getName() +
":" + this.getId().hashCode();
this.hashCode = hashStr.hashCode();
}
}
return this.hashCode;
}
public String toString () {
return super.toString();
}
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
270/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
[StaffDao.java]
package com.online.account.business.service;
import com.online.account.business.entity.Staff;
public interface StaffDao {
public Staff getStaffByNamePassword(String name,String password);
}
[UserDaoImpl.java]
package com.online.account.dao;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.online.account.business.entity.Staff;
import com.online.account.business.service.StaffDao;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
271/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
<bean id="idStaffDao"
class="com.online.account.dao.StaffDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
272/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
<bean id="dbConf"
class="org.springframework.core.io.ClassPathResource">
<constructor-arg>
<value>database.properties</value>
</constructor-arg>
</bean>
<bean id="databaseConfPostProcessor"
class="org.springframework.beans.factory.config.
PropertyPlaceholderConfigurer">
<property name="location">
<ref bean="dbConf" />
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.
HibernateTransactionManager">
<property name="sessionFactory"
ref="sessionFactory" />
</bean>
<!-- sessionFactory definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="mappingResources">
<list>
<value>com/online/account/dao/hbm/xml/Staff.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
273/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
</property>
</bean>
</beans>
// HttpSession
------------------------------------------------------------------
/** HttpSession */
/** user bean key name */
public static final String KEY_STAFFBEAN= "staffBean";
// HttpServletRequest
-----------------------------------------------------------
/** HttpServletRequest */
public static final String ATTR_MESSAGE = "message";
public static final String SESSION_SCREENNAME = "screen_name";
// ReserveForm
------------------------------------------------------------------
public static final String FORM_PROPERTY_IS_CHANGE = "isChange";
static final String KEY_MESSAGE_SCREENTRANSERR =
"message.error.screentransition";
static final String SUCCESS = "success";
//
----------------------------------------------------------------------
private WebConstants() {
// nothing to do.
}
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
274/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
8.7.7. Check!
Restart the Tomcat server to see if all configuration have no error.
8.7.9. Check!
Test your dao file if your Dao Implemented method is correctly executed by Hibernate.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
275/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
276/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
277/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn" >
<set-property property="contextConfigLocation"
value="/WEB-INF/action-servlet.xml,
/WEB-INF/action-servletAction.xml,
/WEB-INF/action-servletService.xml" />
</plug-in>
</struts-config>
</global-forwards>
<!-- =========================================== Action Mapping
Definitions -->
<action-mappings>
<action
path="/Welcome"
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
278/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
forward="/WEB-INF/jsp/login_000.jsp"/>
<action
path="/loginPattern"
type="org.springframework.web.struts.DelegatingActionProxy"
name="staffFormBean"
scope="session" input="/WEB-INF/jsp/login_000.jsp"
validate="true">
<forward name="success"
path="/WEB-INF/jsp/home_001.jsp"/>
<forward name="nosuccess"
path="/WEB-INF/jsp/login_000.jsp"/>
</action>
</action-mappings>
value="/WEB-INF/action-servlet.xml,/WEB-INF/action-servletAction.xml,/
WEB-INF/action-servletService.xml" />
</plug-in>
</struts-config>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
279/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
[action-servletAction.xml]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xs
d">
<bean name="/loginPattern"
class="com.online.account.presentation.action.LoginAction">
<property name="myLoginService"
ref="idLoginService" />
</bean>
</beans>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
280/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
[index.jsp]
<%@ include file="/WEB-INF/jsp/inc/common.jsp" %>
<logic:redirect forward="welcome" />
[login000.jsp]
<%@ include file="inc/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<H1>Account Management System</H1>
<html:form action="/loginPattern">
Enter Staff Name:<html:text property="name"/>***<html:errors
property="name"/><br>
Enter Password:<html:password
property="password"/>***<html:errors property="password"/><br>
<html:errors property="loginerror"/>
<html:submit property="btnLogin" value="Login"/>
</html:form>
</body>
</html>
[home001.jsp]
<%@ include file="inc/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
281/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
import org.apache.struts.validator.ValidatorForm;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
282/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
this.password = password;
}
public int getError() {
return error;
}
public void setError(int error) {
this.error = error;
}
}
[validation.xml]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules
Configuration 1.3.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">
<form-validation>
<formset>
<form name="staffFormBean">
<field property="name" depends="required">
<arg key="label.name" />
</field>
<var-value>^[0-9a-zA-Z]*$</var-value>
</var>
</field>
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
283/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
</form>
</formset>
</form-validation>
# -- my errors --
label.name=Name
label.password=Password
package com.online.account.presentation.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
284/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
import com.online.account.presentation.form.StaffForm;
/**
** <p>
* Execute the action. <br>
* <ol>
* Set the screen name obtained from the browser to session.<br>
* Transfer the control to each action. Save token Return next jsp
page
* obtained from each action.
* </ol>
* <p>
*
* @throws RuntimeException
* @see Action#execute
*/
public final ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse
response)
throws Exception {
if (isCheckScreenTransition(request)) {
if (!isValidScreenTransition(request)) {
throw new RuntimeException("screen
transition not allowed.");
}
}
// set screen name to the session
if (request.getParameter(WebConstants.SESSION_SCREENNAME) !=
null) {
request.getSession().setAttribute(WebConstants.SESSION_SCREENNA
ME,
request.getParameter(WebConstants.SESSION_SCREENNAME));
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
285/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
}
if (request.getMethod().toLowerCase().equals("get")) {
String strForward = doInit(form, request, mapping);
return mapping.findForward(strForward);
}
// if next button, doNext
if (null != request.getParameter("next")) {
String strForward = doNext(form, request, mapping);
return mapping.findForward(strForward);
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
286/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
}
/**
* when next button is clicked, actual page is counted down
* @return
*/
private String doPrev(ActionForm form,HttpServletRequest
request,ActionMapping mapping) {
//BookSearchForm userForm = getUserBean(request);
StaffForm staffForm = getStaffBean(request);
staffForm.setActualPage(staffForm.getActualPage() -1);
setStaffBean(request, staffForm);
return WebConstants.SUCCESS;
}
/**
* Do initial process. If needs to process something
especial,override in
* the child module
* <p>
* default is true.
* <p>
*
* @return the next jsp path
*/
protected String doInit(ActionForm form, HttpServletRequest
request,
ActionMapping mapping) {
return "success";
}
/**
* Check if the screen requires login.
* <p>
* default is true.
* <p>
*
* @return true,if required. false if not required
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
287/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
*/
protected boolean isRequiredLogin(HttpServletRequest request) {
return true;
}
/**
* Get if it is necessary to check screen transition.
* <p>
* default is false.
* <p>
*
* @param request
* HTTP Servlet Request
* @return true, if check is necessary.
*/
protected boolean isCheckScreenTransition(HttpServletRequest
request) {
return false;
}
/**
* Check if screen transition is correct.
* <p>
* Check by {@link Action#isTokenValid(HttpServletRequest)
isTokenValid()}
* <p>
*
* @param request
* HTTP Servlet Request
* @return true, if the transition is correct
*/
protected boolean isValidScreenTransition(HttpServletRequest
request) {
return isTokenValid(request);
}
/**
* Execute request process of Action.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
288/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
* <p>
*
* @param form
* ActionForm
* @param request
* HTTP Servlet Request
* @param mapping
* @return destination of forward
* @throws Exception
*/
protected abstract String doExecute(ActionForm form,
HttpServletRequest request,HttpServletResponse
response, ActionMapping mapping) throws Exception;
/**
* Get message from MessageResources.properties
* <p>
* @param request
* HTTP Servlet Request
* @param key
* Message Resource key
* @return Message
*/
protected String getMessage(HttpServletRequest request, String
key) {
return getResources(request).getMessage(key);
}
protected StaffForm getStaffBean(HttpServletRequest req) {
HttpSession session = req.getSession();
return (StaffForm)
session.getAttribute(WebConstants.KEY_STAFFBEAN);
}
protected void setStaffBean(HttpServletRequest req, StaffForm STAFFBEAN)
{ HttpSession session = req.getSession();
session.setAttribute(WebConstants.KEY_STAFFBEAN, STAFFBEAN);
}
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
289/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import com.online.account.business.service.LoginService;
import com.online.account.presentation.form.StaffForm;
@Override
protected String doExecute(ActionForm form, HttpServletRequest
request,HttpServletResponse response,
ActionMapping mapping) throws Exception {
StaffForm myStaffForm=(StaffForm)form;
myLoginService.checkStaff(myStaffForm);
ActionErrors errors = new ActionErrors();
if(myStaffForm.getError()==1){
errors.add("loginerror", new
ActionMessage("errors.login"));
saveErrors(request, errors);
return "nosuccess";
}
setStaffBean(request,myStaffForm);
return "success";
}
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
290/298
S-EA-A-1.0
Framework Application Development<Day 8>
Developing Login Function
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
291/298
S-EA-A-1.0
Framework Application Development<Day 8>
Context Path Creation at Tomcat Server
account.xml
http://localhost:8080/account
8.9. Check!
Execute the Login function. Input user name and see if you can go to the next screen when
the name and password are correct.
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
292/298
S-EA-A-1.0
Tables and Figures
Figures
Figures
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
293/298
S-EA-A-1.0
Tables and Figures
Figures
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
294/298
S-EA-A-1.0
Tables and Figures
Tables
Tables
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
295/298
S-EA-A-1.0
Tables and Figures
Tables
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
296/298
S-EA-A-1.0
Indexes
Keywords
Indexes
Keywords
Bean Tag Library, 191 HTTP, 51
CGI, 53 Implicit object, 111
Connection Pooling, 136 Invoker Servlet, 60
Context initialization, 93 JavaScrip, 56
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
297/298
S-EA-A-1.0
Indexes
Keywords
S-EA-A-1.0
Software Technologies – ICTTI, Union of Myanmar
298/298