100% found this document useful (11 votes)
50 views85 pages

The Java EE 5 Tutorial 2nd Ed Edition Eric Jendrock All Chapter Instant Download

Tutorial

Uploaded by

mhondbehfar9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (11 votes)
50 views85 pages

The Java EE 5 Tutorial 2nd Ed Edition Eric Jendrock All Chapter Instant Download

Tutorial

Uploaded by

mhondbehfar9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Download the full version of the ebook at ebookfinal.

com

The Java EE 5 Tutorial 2nd ed Edition Eric


Jendrock

https://ebookfinal.com/download/the-java-ee-5-tutorial-2nd-
ed-edition-eric-jendrock/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookfinal.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Java EE 5 Development using GlassFish Application Server


1st Ed. Edition David R. Heffelfinger

https://ebookfinal.com/download/java-ee-5-development-using-glassfish-
application-server-1st-ed-edition-david-r-heffelfinger/

ebookfinal.com

Java EE Development with Eclipse 2nd Edition Ram Kulkarni

https://ebookfinal.com/download/java-ee-development-with-eclipse-2nd-
edition-ram-kulkarni/

ebookfinal.com

Java EE 6 Pocket Guide 1st Edition Arun Gupta

https://ebookfinal.com/download/java-ee-6-pocket-guide-1st-edition-
arun-gupta/

ebookfinal.com

Beginning EJB 3 Java EE 7 edition Jonathan Wetherbee

https://ebookfinal.com/download/beginning-ejb-3-java-ee-7-edition-
jonathan-wetherbee/

ebookfinal.com
Java EE 7 Development with NetBeans 8 3rd Edition David R.
Heffelfinger

https://ebookfinal.com/download/java-ee-7-development-with-
netbeans-8-3rd-edition-david-r-heffelfinger/

ebookfinal.com

Java EE 7 Recipes A Problem Solution Approach 1st Edition


Josh Juneau (Auth.)

https://ebookfinal.com/download/java-ee-7-recipes-a-problem-solution-
approach-1st-edition-josh-juneau-auth/

ebookfinal.com

Java 1 5 Tiger A Developer s Notebook 1st ed Edition David


Flanagan

https://ebookfinal.com/download/java-1-5-tiger-a-developer-s-
notebook-1st-ed-edition-david-flanagan/

ebookfinal.com

Java in a nutshell 2nd ed Edition David Flanagan

https://ebookfinal.com/download/java-in-a-nutshell-2nd-ed-edition-
david-flanagan/

ebookfinal.com

Java Concepts Compatible with Java 5 6 and 7 6th Edition


Cay S. Horstmann

https://ebookfinal.com/download/java-concepts-compatible-with-
java-5-6-and-7-6th-edition-cay-s-horstmann/

ebookfinal.com
The Java™ EE 5
Tutorial

For Sun Java System Application Server Platform Edition 9

Jennifer Ball
Debbie Bode Carson
Ian Evans
Kim Haase
Eric Jendrock

May 10, 2006


Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A.
All rights reserved.U.S. Government Rights - Commercial software. Government users are subject to the
Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supple-
ments.

This distribution may include materials developed by third parties.


Sun, Sun Microsystems, the Sun logo, Java, JavaBeans, JavaServer, JavaServer Pages, Enterprise Java-
Beans, Java Naming and Directory Interface, JavaMail, JDBC, EJB, JSP, J2EE, J2SE, “Write Once, Run
Anywhere”, and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems,
Inc. in the U.S. and other countries.
Unless otherwise licensed, software code in all technical materials herein (including articles, FAQs, sam-
ples) is provided under this License.
Products covered by and information contained in this service manual are controlled by U.S. Export Con-
trol laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical
biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly pro-
hibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export
exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is
strictly prohibited.
DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS,
REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MER-
CHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE
LEGALLY INVALID.

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, États-
Unis. Tous droits réservés.
Droits du gouvernement américain, utlisateurs gouvernmentaux - logiciel commercial. Les utilisateurs
gouvernmentaux sont soumis au contrat de licence standard de Sun Microsystems, Inc., ainsi qu aux dis-
positions en vigueur de la FAR [ (Federal Acquisition Regulations) et des suppléments à celles-ci.
Cette distribution peut comprendre des composants développés pardes tierces parties.
Sun, Sun Microsystems, le logo Sun, Java, JavaBeans, JavaServer, JavaServer Pages, Enterprise Java-
Beans, Java Naming and Directory Interface, JavaMail, JDBC, EJB, JSP, J2EE, J2SE, “Write Once, Run
Anywhere”, et le logo Java Coffee Cup sont des marques de fabrique ou des marques déposées de Sun
Microsystems, Inc. aux États-Unis et dans d’autres pays.
A moins qu’autrement autorisé, le code de logiciel en tous les matériaux techniques dans le présent (arti-
cles y compris, FAQs, échantillons) est fourni sous ce permis.
Les produits qui font l’objet de ce manuel d’entretien et les informations qu’il contient sont régis par la
législation américaine en matière de contrôle des exportations et peuvent être soumis au droit d’autres
pays dans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pour
des armes nucléaires, des missiles, des armes biologiques et chimiques ou du nucléaire maritime, directe-
ment ou indirectement, sont strictement interdites. Les exportations ou réexportations vers des pays sous
embargo des États-Unis, ou vers des entités figurant sur les listes d’exclusion d’exportation américaines,
y compris, mais de manière non exclusive, la liste de personnes qui font objet d’un ordre de ne pas partic-
iper, d’une façon directe ou indirecte, aux exportations des produits ou des services qui sont régi par la
législation américaine en matière de contrôle des exportations ("U .S. Commerce Department’s Table of
Denial Orders "et la liste de ressortissants spécifiquement désignés ("U.S. Treasury Department of Spe-
cially Designated Nationals and Blocked Persons "),, sont rigoureusement interdites.

LA DOCUMENTATION EST FOURNIE "EN L’ÉTAT" ET TOUTES AUTRES CONDITIONS, DEC-


LARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES,
DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE
GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L’APTITUDE A UNE
UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.
Contents
About This Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Who Should Use This Tutorial xxvii
Prerequisites xxvii
How to Read This Tutorial xxviii
About the Examples xxx
Further Information xxxiv
How to Print This Tutorial xxxiv
Typographical Conventions xxxiv
Feedback xxxv

Chapter 1: Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Java EE Application Model 2
Distributed Multitiered Applications 3
Security 4
Java EE Components 5
Java EE Clients 5
Web Components 7
Business Components 8
Enterprise Information System Tier 9
Java EE Containers 9
Container Services 10
Container Types 11
Web Services Support 12
XML 12
SOAP Transport Protocol 13
WSDL Standard Format 13
UDDI and ebXML Standard Formats 14
Java EE Application Assembly and Deployment 14
Packaging Applications 14
iii
iv CONTENTS

Development Roles 16
Java EE Product Provider 16
Tool Provider 17
Application Component Provider 17
Application Assembler 18
Application Deployer and Administrator 18
Java EE 5 APIs 19
Enterprise JavaBeans Technology 20
Java Servlet Technology 20
JavaServer Pages Technology 20
JavaServer Pages Standard Tag Library 20
JavaServer Faces 21
Java Message Service API 21
Java Transaction API 22
JavaMail API 22
JavaBeans Activation Framework 22
Java API for XML Processing 22
Java API for XML Web Services (JAX-WS) 23
Java Architecture for XML Binding (JAXB) 23
SOAP with Attachments API for Java 23
Java API for XML Registries 24
J2EE Connector Architecture 24
Java Database Connectivity API 24
Java Persistence API 25
Java Naming and Directory Interface 25
Java Authentication and Authorization Service 26
Simplified Systems Integration 26
Sun Java System Application Server Platform Edition 9 27
Tools 27
Starting and Stopping the Application Server 28
Starting the Admin Console 29
Starting and Stopping the Java DB Database Server 30
Debugging Java EE Applications 30

Part One: The Web Tier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33

Chapter 2: Getting Started with Web Applications. . . . . . . . . .35


Web Application Life Cycle 38
Web Modules 40
Packaging Web Modules 42
Deploying a WAR File 43
CONTENTS v

Testing Deployed Web Modules 44


Listing Deployed Web Modules 44
Updating Web Modules 45
Undeploying Web Modules 47
Configuring Web Applications 48
Mapping URLs to Web Components 48
Declaring Welcome Files 49
Setting Initialization Parameters 50
Mapping Errors to Error Screens 50
Declaring Resource References 51
Duke’s Bookstore Examples 54
Accessing Databases from Web Applications 54
Populating the Example Database 55
Creating a Data Source in the Application Server 55
Further Information 56

Chapter 3: Java Servlet Technology . . . . . . . . . . . . . . . . . . . . . 57


What Is a Servlet? 57
The Example Servlets 58
Troubleshooting 60
Servlet Life Cycle 61
Handling Servlet Life-Cycle Events 61
Handling Errors 64
Sharing Information 64
Using Scope Objects 64
Controlling Concurrent Access to Shared Resources 65
Accessing Databases 67
Initializing a Servlet 68
Writing Service Methods 69
Getting Information from Requests 70
Constructing Responses 72
Filtering Requests and Responses 75
Programming Filters 75
Programming Customized Requests and Responses 77
Specifying Filter Mappings 80
Invoking Other Web Resources 82
Including Other Resources in the Response 82
Transferring Control to Another Web Component 84
Accessing the Web Context 85
Maintaining Client State 86
vi CONTENTS

Accessing a Session 86
Associating Objects with a Session 86
Session Management 87
Session Tracking 88
Finalizing a Servlet 89
Tracking Service Requests 89
Notifying Methods to Shut Down 90
Creating Polite Long-Running Methods 91
Further Information 92

Chapter 4: JavaServer Pages Technology . . . . . . . . . . . . . . . .93


What Is a JSP Page? 93
Example 94
The Example JSP Pages 97
The Life Cycle of a JSP Page 102
Translation and Compilation 102
Execution 103
Creating Static Content 105
Response and Page Encoding 105
Creating Dynamic Content 106
Using Objects within JSP Pages 106
Unified Expression Language 107
Immediate and Deferred Evaluation Syntax 110
Value and Method Expressions 111
Defining a Tag Attribute Type 118
Deactivating Expression Evaluation 119
Literal Expressions 121
Resolving Expressions 122
Implicit Objects 125
Operators 126
Reserved Words 127
Examples 127
Functions 129
JavaBeans Components 130
JavaBeans Component Design Conventions 131
Creating and Using a JavaBeans Component 132
Setting JavaBeans Component Properties 133
Retrieving JavaBeans Component Properties 136
Using Custom Tags 136
Declaring Tag Libraries 137
CONTENTS vii

Including the Tag Library Implementation 139


Reusing Content in JSP Pages 139
Transferring Control to Another Web Component 140
jsp:param Element 141
Including an Applet 141
Setting Properties for Groups of JSP Pages 144
Further Information 147

Chapter 5: JavaServer Pages Documents . . . . . . . . . . . . . . . 149


The Example JSP Document 150
Creating a JSP Document 152
Declaring Tag Libraries 154
Including Directives in a JSP Document 156
Creating Static and Dynamic Content 158
Using the jsp:root Element 161
Using the jsp:output Element 162
Identifying the JSP Document to the Container 166

Chapter 6: JavaServer Pages Standard Tag Library . . . . . . . 167


The Example JSP Pages 168
Using JSTL 169
Tag Collaboration 170
Core Tag Library 172
Variable Support Tags 172
Flow Control Tags 174
URL Tags 177
Miscellaneous Tags 178
XML Tag Library 180
Core Tags 181
Flow Control Tags 182
Transformation Tags 183
Internationalization Tag Library 184
Setting the Locale 185
Messaging Tags 185
Formatting Tags 186
SQL Tag Library 187
query Tag Result Interface 189
Functions 191
Further Information 192
viii CONTENTS

Chapter 7: Custom Tags in JSP Pages . . . . . . . . . . . . . . . . . . .195


What Is a Custom Tag? 196
The Example JSP Pages 196
Types of Tags 199
Tags with Attributes 199
Tags with Bodies 202
Tags That Define Variables 203
Communication between Tags 203
Encapsulating Reusable Content Using Tag Files 204
Tag File Location 206
Tag File Directives 206
Evaluating Fragments Passed to Tag Files 215
Examples 215
Tag Library Descriptors 220
Top-Level Tag Library Descriptor Elements 221
Declaring Tag Files 222
Declaring Tag Handlers 225
Declaring Tag Attributes for Tag Handlers 227
Declaring Tag Variables for Tag Handlers 229
Programming Simple Tag Handlers 231
Including Tag Handlers in Web Applications 231
How Is a Simple Tag Handler Invoked? 232
Tag Handlers for Basic Tags 232
Tag Handlers for Tags with Attributes 232
Tag Handlers for Tags with Bodies 236
Tag Handlers for Tags That Define Variables 237
Cooperating Tags 240
Examples 242

Chapter 8: Scripting in JSP Pages . . . . . . . . . . . . . . . . . . . . . .251


The Example JSP Pages 252
Using Scripting 253
Disabling Scripting 253
Declarations 254
Initializing and Finalizing a JSP Page 254
Scriptlets 255
Expressions 256
Programming Tags That Accept Scripting Elements 257
TLD Elements 257
Tag Handlers 257
CONTENTS ix

Tags with Bodies 260


Cooperating Tags 261
Tags That Define Variables 263

Chapter 9: JavaServer Faces Technology . . . . . . . . . . . . . . . 265


JavaServer Faces Technology Benefits 267
What is a JavaServer Faces Application? 268
A Simple JavaServer Faces Application 268
Steps in the Development Process 269
Mapping the FacesServlet Instance 270
Creating the Pages 271
Defining Page Navigation 278
Configuring Error Messages 279
Developing the Beans 279
Adding Managed Bean Declarations 280
User Interface Component Model 281
User Interface Component Classes 282
Component Rendering Model 284
Conversion Model 289
Event and Listener Model 290
Validation Model 291
Navigation Model 292
Backing Beans 295
The Life Cycle of a JavaServer Faces Page 300
Further Information 306

Chapter 10: Using JavaServer Faces Technology in JSP Pages . .


307
The Example JavaServer Faces Application 308
Setting Up a Page 310
Using the Core Tags 313
Using the HTML Component Tags 316
UI Component Tag Attributes 317
The UIForm Component 319
The UIColumn Component 320
The UICommand Component 321
The UIData Component 323
The UIGraphic Component 326
The UIInput and UIOutput Components 327
x CONTENTS

The UIPanel Component 332


The UISelectBoolean Component 335
The UISelectMany Component 335
The UIMessage and UIMessages Components 337
The UISelectOne Component 338
The UISelectItem, UISelectItems, and UISelectItemGroup Components
339
Using Localized Data 343
Loading a Resource Bundle 343
Referencing Localized Static Data 344
Referencing Error Messages 345
Using the Standard Converters 347
Converting a Component’s Value 348
Using DateTimeConverter 349
Using NumberConverter 351
Registering Listeners on Components 353
Registering a Value-Change Listener on a Component 354
Registering an Action Listener on a Component 355
Using the Standard Validators 356
Requiring a Value 358
Using the LongRangeValidator 359
Binding Component Values and Instances to External Data Sources
359
Binding a Component Value to a Property 361
Binding a Component Value to an Implicit Object 363
Binding a Component Instance to a Bean Property 364
Binding Converters, Listeners, and Validators to Backing Bean Prop-
erties 365
Referencing a Backing Bean Method 367
Referencing a Method That Performs Navigation 368
Referencing a Method That Handles an Action Event 369
Referencing a Method That Performs Validation 370
Referencing a Method That Handles a Value-change Event 370
Using Custom Objects 371
Using a Custom Converter 372
Using a Custom Validator 373
Using a Custom Component 374

Chapter 11: Developing with JavaServer Faces Technology .377


Writing Bean Properties 378
CONTENTS xi

Writing Properties Bound to Component Values 379


Writing Properties Bound to Component Instances 387
Writing Properties Bound to Converters, Listeners, or Validators 389
Performing Localization 390
Creating a Resource Bundle 390
Localizing Dynamic Data 391
Localizing Messages 391
Creating a Custom Converter 393
Implementing an Event Listener 396
Implementing Value-Change Listeners 397
Implementing Action Listeners 398
Creating a Custom Validator 399
Implementing the Validator Interface 400
Creating a Custom Tag 404
Writing Backing Bean Methods 406
Writing a Method to Handle Navigation 407
Writing a Method to Handle an Action Event 409
Writing a Method to Perform Validation 409
Writing a Method to Handle a Value-Change Event 410

Chapter 12: Creating Custom UI Components . . . . . . . . . . . . 413


Determining Whether You Need a Custom Component or Renderer
414
When to Use a Custom Component 414
When to Use a Custom Renderer 415
Component, Renderer, and Tag Combinations 416
Understanding the Image Map Example 417
Why Use JavaServer Faces Technology to Implement an Image Map?
418
Understanding the Rendered HTML 418
Understanding the JSP Page 419
Configuring Model Data 421
Summary of the Application Classes 423
Steps for Creating a Custom Component 424
Creating Custom Component Classes 425
Specifying the Component Family 428
Performing Encoding 428
Performing Decoding 430
Enabling Component Properties to Accept Expressions 431
Saving and Restoring State 433
xii CONTENTS

Delegating Rendering to a Renderer 434


Creating the Renderer Class 435
Identifying the Renderer Type 436
Handling Events for Custom Components 437
Creating the Component Tag Handler 438
Retrieving the Component Type 439
Setting Component Property Values 439
Providing the Renderer Type 442
Releasing Resources 443
Defining the Custom Component Tag in a Tag Library Descriptor 443

Chapter 13: Configuring JavaServer Faces Applications . . . .447


Application Configuration Resource File 448
Configuring Beans 449
Using the managed-bean Element 450
Initializing Properties using the managed-property Element 451
Initializing Maps and Lists 458
Registering Custom Error Messages 459
Registering Custom Localized Static Text 460
Registering a Custom Validator 461
Registering a Custom Converter 462
Configuring Navigation Rules 463
Registering a Custom Renderer with a Render Kit 466
Registering a Custom Component 469
Basic Requirements of a JavaServer Faces Application 470
Configuring an Application with a Deployment Descriptor 471
Including the Required JAR Files 478
Including the Classes, Pages, and Other Resources 478

Chapter 14: Internationalizing and Localizing Web Applications .


481
Java Platform Localization Classes 481
Providing Localized Messages and Labels 482
Establishing the Locale 483
Setting the Resource Bundle 484
Retrieving Localized Messages 485
Date and Number Formatting 486
Character Sets and Encodings 487
Character Sets 487
CONTENTS xiii

Character Encoding 488


Further Information 491

Part Two: Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493

Chapter 15: Building Web Services with JAX-WS . . . . . . . . . . . 495


Setting the Port 496
Creating a Simple Web Service and Client with JAX-WS 496
Requirements of a JAX-WS Endpoint 498
Coding the Service Endpoint Implementation Class 498
Building and Packaging the Service 499
Deploying the Service 499
A Simple JAX-WS Client 501
Types Supported by JAX-WS 503
Web Services Interoperability and JAX-WS 503
Further Information 503

Chapter 16: Binding between XML Schema and Java Classes . .


505
JAXB Architecture 506
Architectural Overview 506
The JAXB Binding Process 507
More About Unmarshalling 508
More About Marshalling 508
More About Validation 508
Representing XML Content 509
Java Representation of XML Schema 509
Binding XML Schemas 509
Simple Type Definitions 509
Default Data Type Bindings 510
Customizing JAXB Bindings 512
Schema-to-Java 512
Java-to-Schema 513
Examples 518
General Usage Instructions 519
Description 520
Using the Examples 523
Configuring and Running the Samples 523
JAXB Compiler Options 523
JAXB Schema Generator Options 525
xiv CONTENTS

About the Schema-to-Java Bindings 526


Schema-Derived JAXB Classes 529
Basic Examples 537
Modify Marshal Example 537
Unmarshal Validate Example 539
Customizing JAXB Bindings 540
Why Customize? 541
Customization Overview 542
Customize Inline Example 555
Datatype Converter Example 560
External Customize Example 561
Java-toSchema Examples 565
j2s-create-marshal Example 565
j2s-xmlAccessorOrder Example 565
j2s-xmlAdapter-field Example 568
j2s-xmlAttribute-field Example 571
j2s-xmlRootElement Example 572
j2s-xmlSchemaType-class Example 572
j2s-xmlType Example 573

Chapter 17: Streaming API for XML . . . . . . . . . . . . . . . . . . . . . .575


Why StAX? 575
Streaming Versus DOM 576
Pull Parsing Versus Push Parsing 577
StAX Use Cases 577
Comparing StAX to Other JAXP APIs 578
StAX API 579
Cursor API 579
Iterator API 580
Choosing Between Cursor and Iterator APIs 585
Using StAX 587
StAX Factory Classes 587
Resources, Namespaces, and Errors 589
Reading XML Streams 590
Writing XML Streams 593
Sun’s Streaming Parser Implementation 595
Reporting CDATA Events 595
SJSXP Factories Implementation 596
Sample Code 597
Sample Code Organization 597
CONTENTS xv

Configuring Your Environment for Running the Samples 598


Running the Samples 599
Sample XML Document 600
cursor Sample – CursorParse.java 600
cursor2event Sample – CursorApproachEventObject.java 603
event Sample – EventParse.java 604
filter Sample – MyStreamFilter.java 606
readnwrite Sample – EventProducerConsumer.java 609
writer Sample – CursorWriter.java 611
Further Information 613

Chapter 18: SOAP with Attachments API for Java . . . . . . . . . . 615


Overview of SAAJ 616
Messages 616
Connections 620
Tutorial 621
Creating and Sending a Simple Message 622
Adding Content to the Header 631
Adding Content to the SOAPPart Object 632
Adding a Document to the SOAP Body 634
Manipulating Message Content Using SAAJ or DOM APIs 634
Adding Attachments 635
Adding Attributes 637
Using SOAP Faults 643
Code Examples 649
Request.java 650
MyUddiPing.java 651
HeaderExample.java 658
DOMExample.java and DOMSrcExample.java 660
Attachments.java 664
SOAPFaultTest.java 666
Further Information 668

Chapter 19: Java API for XML Registries . . . . . . . . . . . . . . . . . . 671


Overview of JAXR 671
What Is a Registry? 671
What Is JAXR? 672
JAXR Architecture 673
Implementing a JAXR Client 674
xvi CONTENTS

Establishing a Connection 675


Querying a Registry 681
Managing Registry Data 686
Using Taxonomies in JAXR Clients 694
Running the Client Examples 699
Before You Compile the Examples 700
Compiling the Examples 701
Running the Examples 702
Using JAXR Clients in Java EE Applications 707
Coding the Application Client: MyAppClient.java 707
Coding the PubQuery Session Bean 708
Editing the Properties File 708
Starting the Application Server 708
Creating JAXR Resources 709
Compiling the Source Files and Packaging the Application 710
Deploying the Application 710
Running the Application Client 710
Further Information 711

Part Three: Enterprise Beans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .713

Chapter 20: Enterprise Beans . . . . . . . . . . . . . . . . . . . . . . . . . . .715


What Is an Enterprise Bean? 715
Benefits of Enterprise Beans 715
When to Use Enterprise Beans 716
Types of Enterprise Beans 717
What Is a Session Bean? 717
State Management Modes 717
When to Use Session Beans 718
What Is a Message-Driven Bean? 719
What Makes Message-Driven Beans Different from Session and Entity
Beans? 719
When to Use Message-Driven Beans 721
Defining Client Access with Interfaces 721
Remote Clients 722
Local Clients 722
Deciding on Remote or Local Access 723
Web Service Clients 724
Method Parameters and Access 724
The Contents of an Enterprise Bean 725
Naming Conventions for Enterprise Beans 726
CONTENTS xvii

The Life Cycles of Enterprise Beans 727


The Life Cycle of a Stateful Session Bean 727
The Life Cycle of a Stateless Session Bean 728
The Life Cycle of a Message-Driven Bean 729
Further Information 729

Chapter 21: Getting Started with Enterprise Beans . . . . . . . . . 731


Creating the Enterprise Bean 732
Coding the Enterprise Bean 732
Compiling and Packaging converter 733
Creating the Application Client 734
Coding the Application Client 735
Compiling the Application Client 736
Creating the Web Client 737
Coding the Web Client 737
Compiling the Web Client 738
Deploying the Java EE Application 739
Running the Application Client 739
Running the Web Client 739
Modifying the Java EE Application 740
Modifying a Class File 740

Chapter 22: Session Bean Examples . . . . . . . . . . . . . . . . . . . . . 743


The cart Example 743
Session Bean Class 745
The Remove Method 748
Helper Classes 749
Building and Packaging the CartBean Example 749
Undeploying cart 750
A Web Service Example: HelloServiceBean 751
The Web Service Endpoint Implementation Class 751
Stateless Session Bean Implementation Class 752
Building and Packaging helloservice 753
Deploying helloservice 753
Using the Timer Service 754
The Timeout Method 754
Creating Timers 754
Canceling and Saving Timers 755
Getting Timer Information 756
xviii CONTENTS

Transactions and Timers 756


The timersession Example 756
Building and Packaging timersession 757
Deploying timersession 758
Handling Exceptions 759

Chapter 23: A Message-Driven Bean Example . . . . . . . . . . . .761


Example Application Overview 761
The Application Client 762
The Message-Driven Bean Class 763
The onMessage Method 764
Packaging, Deploying, and Running SimpleMessage 765
Creating the Administered Objects 765
Creating and Packaging the Application 766
Deploying the Application 766
Running the Client 767
Removing the Administered Objects 767
Creating Deployment Descriptors for Message-Driven Beans 768

Part Four: Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .769

Chapter 24: Introduction to the Java Persistence API . . . . . . .771


Entities 771
Requirements for Entity Classes 772
Persistent Fields and Properties in Entity Classes 772
Primary Keys in Entities 774
Multiplicity in Entity Relationships 776
Direction in Entity Relationships 777
Managing Entities 779
The Persistence Context 779
The EntityManager 779
Persistence Units 785

Chapter 25: Persistence in the Web Tier . . . . . . . . . . . . . . . . . .787


Accessing Databases from Web Applications 787
Populating the Example Database 789
Creating a Data Source in the Application Server 789
Defining the Persistence Unit 790
Creating an Entity Class 790
CONTENTS xix

Obtaining Access to an Entity Manager 792


Accessing Data From the Database 794
Updating Data in the Database 795

Chapter 26: Persistence in the EJB Tier . . . . . . . . . . . . . . . . . . . 797


Overview of the order Application 797
Entity Relationships in order 798
Primary Keys in order 800
Entity Mapped to More Than One Database Table 804
Cascade Operations in order 805
BLOB and CLOB Database Types in order 805
Temporal Types in order 806
Managing order’s Entities 807
Building and Running order 810
Creating the Database Tables 810
Building and Packaging the Application 810
Deploying the Application 810
Running the Application 811
Undeploying order 812
The roster Application 812
Relationships in the roster Application 813
Automatic Table Generation in roster 814
Building and Running roster 814
Building and Packaging the roster Application 815
Deploying the Application 815
Running the Application 815
Undeploying order 816

Chapter 27: The Java Persistence Query Language . . . . . . . . 817


Terminology 817
Simplified Syntax 818
Select Statements 818
Update and Delete Statements 819
Example Queries 819
Simple Queries 820
Queries That Navigate to Related Entities 821
Queries with Other Conditional Expressions 823
Bulk Updates and Deletes 825
Full Syntax 826
xx CONTENTS

BNF Symbols 826


BNF Grammar of the Java Persistence Query Language 827
FROM Clause 832
Path Expressions 836
WHERE Clause 837
SELECT Clause 848
ORDER BY Clause 851
The GROUP BY Clause 851

Part Five: Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .853

Chapter 28: Introduction to Security in Java EE . . . . . . . . . . . .855


Overview 856
A Simple Example 857
Security Functions 860
Characteristics of Application Security 861
Security Implementation Mechanisms 862
Java SE Security Implementation Mechanisms 862
Java EE Security Implementation Mechanisms 863
Securing Containers 866
Using Deployment Descriptors for Declarative Security 867
Using Annotations 868
Using Programmatic Security 869
Securing the Application Server 869
Working with Realms, Users, Groups, and Roles 871
What is a Realm, User, Group, and Role? 871
Managing Users and Groups on the Application Server 875
Setting Up Security Roles 876
Mapping Roles to Users and Groups 878
Establishing a Secure Connection Using SSL 879
Installing and Configuring SSL Support 880
Specifying a Secure Connection in Your Application Deployment De-
scriptor 880
Verifying SSL Support 881
Working with Digital Certificates 883
Enabling Mutual Authentication over SSL 888
Further Information 891

Chapter 29: Securing Java EE Applications . . . . . . . . . . . . . . .893


Securing Enterprise Beans 894
CONTENTS xxi

Accessing an Enterprise Bean Caller’s Security Context 896


Declaring Security Role Names Referenced from Enterprise Bean Code
898
Defining a Security View of Enterprise Beans 901
Using Enterprise Bean Security Annotations 913
Using Enterprise Bean Security Deployment Descriptor Elements 914
Configuring IOR Security 915
Deploying Secure Enterprise Beans 918
Enterprise Bean Example Applications 919
Example: Securing an Enterprise Bean 919
Discussion: Securing the Duke’s Bank Example 925
Securing Application Clients 926
Using Login Modules 926
Using Programmatic Login 927
Securing EIS Applications 928
Container-Managed Sign-On 928
Component-Managed Sign-On 929
Configuring Resource Adapter Security 929
Mapping an Application Principal to EIS Principals 931
Further Information 932

Chapter 30: Securing Web Applications. . . . . . . . . . . . . . . . . . 933


Overview 934
Working with Security Roles 936
Declaring Security Roles 937
Mapping Security Roles to Application Server Groups 940
Checking Caller Identity Programmatically 941
Declaring and Linking Role References 943
Defining Security Requirements for Web Applications 945
Declaring Security Requirements Using Annotations 946
Declaring Security Requirements in a Deployment Descriptor 948
Specifying a Secure Connection 955
Specifying an Authentication Mechanism 957
Examples: Securing Web Applications 963
Example: Basic Authentication with JAX-WS 964
Further Information 970

Chapter 31: Securing Web Services . . . . . . . . . . . . . . . . . . . . . 971


Securing Web Service Endpoints 972
xxii CONTENTS

Overview of Message Security 972


Advantages of Message Security 973
Message Security Mechanisms 975
Web Services Security Initiatives and Organizations 976
W3C Specifications 976
OASIS Specifications 977
JCP Specifications 978
WS-I Specifications 979
Using Message Security with Java EE 981
Using the Application Server Message Security Implementation 982
Using the Java WSDP XWSS Security Implementation 987
Further Information 991

Chapter 32: The Java Message Service API . . . . . . . . . . . . . . .993


Overview 993
What Is Messaging? 994
What Is the JMS API? 994
When Can You Use the JMS API? 995
How Does the JMS API Work with the Java EE Platform? 996
Basic JMS API Concepts 997
JMS API Architecture 998
Messaging Domains 999
Message Consumption 1001
The JMS API Programming Model 1001
Administered Objects 1002
Connections 1004
Sessions 1005
Message Producers 1006
Message Consumers 1007
Messages 1009
Queue Browsers 1012
Exception Handling 1013
Writing Simple JMS Client Applications 1013
A Simple Example of Synchronous Message Receives 1014
A Simple Example of Asynchronous Message Consumption 1021
A Simple Example of Browsing Messages in a Queue 1025
Running JMS Client Programs on Multiple Systems 1028
Creating Robust JMS Applications 1033
Using Basic Reliability Mechanisms 1034
Using Advanced Reliability Mechanisms 1041
CONTENTS xxiii

Using the JMS API in a Java EE Application 1052


Using @Resource Annotations in Java EE Components 1053
Using Session Beans to Produce and to Synchronously Receive Messages
1053
Using Message-Driven Beans 1054
Managing Distributed Transactions 1057
Using the JMS API with Application Clients and Web Components1059
Further Information 1060

Chapter 33: Java EE Examples Using the JMS API . . . . . . . . . 1061


A Java EE Application That Uses the JMS API with a Session Bean
1062
Writing the Application Components 1062
Creating and Packaging the Application 1065
Deploying the Application 1066
Running the Application Client 1067
A Java EE Application That Uses the JMS API with an Entity 1067
Overview of the Human Resources Application 1068
Writing the Application Components 1070
Creating and Packaging the Application 1072
Deploying the Application 1073
Running the Application Client 1074
An Application Example That Consumes Messages from a Remote
Java EE Server 1075
Overview of the Modules 1076
Writing the Components 1077
Creating and Packaging the Modules 1077
Deploying the EJB Module and Copying the Client 1079
Running the Application Client 1079
An Application Example That Deploys a Message-Driven Bean on Two
Java EE Servers 1080
Overview of the Modules 1081
Writing the Module Components 1082
Creating and Packaging the Modules 1084
Deploying the Modules 1084
Running the Application Client 1085

Chapter 34: Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1089


What Is a Transaction? 1089
xxiv CONTENTS

Container-Managed Transactions 1090


Transaction Attributes 1091
Rolling Back a Container-Managed Transaction 1095
Synchronizing a Session Bean’s Instance Variables 1096
Methods Not Allowed in Container-Managed Transactions 1096
Bean-Managed Transactions 1097
JTA Transactions 1097
Returning without Committing 1098
Methods Not Allowed in Bean-Managed Transactions 1098
Transaction Timeouts 1098
Updating Multiple Databases 1099
Transactions in Web Components 1101

Chapter 35: Resource Connections . . . . . . . . . . . . . . . . . . . . .1103


Resources and JNDI Naming 1103
DataSource Objects and Connection Pools 1105
Resource Injection 1106
Field-Based Injection 1107
Method-Based Injection 1108
Class-Based Injection 1109
Further Information 1110

Chapter 36: Connector Architecture . . . . . . . . . . . . . . . . . . . .1111


About Resource Adapters 1111
Resource Adapter Contracts 1113
Management Contracts 1113
Outbound Contracts 1115
Inbound Contracts 1116
Common Client Interface 1116
Further Information 1118

Part Six: Case Studies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1119

Chapter 37: The Coffee Break Application . . . . . . . . . . . . . . .1121


Common Code 1122
JAX-WS Coffee Supplier Service 1122
Service Implementation 1123
SAAJ Coffee Supplier Service 1124
SAAJ Client 1125
CONTENTS xxv

SAAJ Service 1133


Coffee Break Server 1139
JSP Pages 1140
JavaBeans Components 1143
RetailPriceListServlet 1145
Resource Configuration 1145
Building, Packaging, Deploying, and Running the Application 1146
Setting the Port 1146
Building the Common Classes 1147
Building, Packaging, and Deploying the JAX-WS Service 1147
Building, Packaging, and Deploying the SAAJ Service 1148
Building, Packaging, and Deploying the Coffee Break Server 1148
Running the Coffee Break Client 1148
Removing the Coffee Break Application 1150

Chapter 38: The Duke’s Bank Application . . . . . . . . . . . . . . . 1151


Enterprise Beans 1152
Session Beans 1153
Java Persistence Entities 1155
Helper Classes 1156
Database Tables 1156
Protecting the Enterprise Beans 1157
Application Client 1158
The Classes and Their Relationships 1160
BankAdmin Class 1160
Web Client 1161
Design Strategies 1163
Client Components 1164
Request Processing 1167
Protecting the Web Client Resources 1170
Building, Packaging, Deploying, and Running the Application 1171
Setting Up the Servers 1172
Building the Duke’s Bank Application 1173
Running the Clients 1173
Running the Application Client 1173
Running the Web Client 1174

Appendix A: Java Encoding Schemes. . . . . . . . . . . . . . . . . . . 1177


Further Information 1178
xxvi CONTENTS

About the Authors . . . . . . . . . . . . . . . . . . . . . . . . .1179


Current Writers 1179

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1181
About This Tutorial

THE Java™ EE 5 Tutorial is a guide to developing enterprise applications for


the Java Platform, Enterprise Edition 5 (Java EE 5). Here we cover all the things
you need to know to make the best use of this tutorial.

Who Should Use This Tutorial


This tutorial is intended for programmers who are interested in developing and
deploying Java EE 5 applications on the Sun Java System Application Server
Platform Edition 9.

Prerequisites
Before proceeding with this tutorial you should have a good knowledge of the
Java programming language. A good way to get to that point is to work through
all the basic and some of the specialized trails in The Java™ Tutorial, Mary
Campione et al., (Addison-Wesley, 2000). In particular, you should be familiar
with relational database and security features described in the trails listed in
Table 1.

Table 1 Prerequisite Trails in The Java™ Tutorial

Trail URL

JDBC http://java.sun.com/docs/books/tutorial/jdbc

Security http://java.sun.com/docs/books/tutorial/security1.2

xxvii
xxviii

How to Read This Tutorial


The Java EE 5 platform is quite large, and this tutorial reflects this. However,
you don’t have to digest everything in it at once. The tutorial has been divided
into parts to help you navigate the content more easily.
This tutorial opens with an introductory chapter, which you should read before
proceeding to any specific technology area. Chapter 1 covers the Java EE 5 plat-
form architecture and APIs along with the Sun Java System Application Server
Platform Edition 9.
When you have digested the basics, you can delve into one or more of the five
main technology areas listed next. Because there are dependencies between
some of the chapters, Figure 1 contains a roadmap for navigating through the
tutorial.
• The web-tier technology chapters cover the components used in develop-
ing the presentation layer of a Java EE 5 or stand-alone web application:
• Java Servlet
• JavaServer Pages (JSP)
• JavaServer Pages Standard Tag Library (JSTL)
• JavaServer Faces
• Web application internationalization and localization
• The web services technology chapters cover the APIs used in developing
standard web services:
• The Java API for XML-based Web Services (JAX-WS)
• The Java API for XML Binding (JAXB)
• The Streaming API for XML (StAX)
• The SOAP with Attachments API for Java (SAAJ)
• The Java API for XML Registries (JAXR)
• The Enterprise JavaBeans (EJB) technology chapters cover the compo-
nents used in developing the business logic of a Java EE 5 application:
• Session beans
• Message-driven beans
• The Persistence technology chapters cover the Java Persistence API, which
is used for accessing databases from Java EE applications:
• Introduction to the Java Persistence API
xxix

• Persistence in the Web Tier


• Persistence in the EJB Tier
• The Java Persistence Query Language
• The platform services chapters cover the system services used by all the
Java EE 5 component technologies:
• Transactions
• Resource connections
• Security
• Java Message Service
• The Connector architecture

Figure 1 Roadmap to This Tutorial

After you have become familiar with some of the technology areas, you are
ready to tackle the case studies, which tie together several of the technologies
discussed in the tutorial. The Coffee Break Application (Chapter 37) describes
an application that uses the web application and web services APIs. The Duke’s
xxx

Bank Application (Chapter 38) describes an application that employs web appli-
cation technologies, enterprise beans, and the Java Persistence API.
Finally, the appendix contains auxiliary information helpful to the Java EE 5
application developer:
• Java encoding schemes (Appendix A)

About the Examples


This section tells you everything you need to know to install, build, and run the
examples.

Required Software
The following software is required to run the examples.

Tutorial Bundle
The tutorial example source is contained in the tutorial bundle. If you are view-
ing this online, you need to click on the “Download” link at the top of any page.
After you have installed the tutorial bundle, the example source code is in the
<INSTALL>/javaee5tutorial/examples/ directory, with subdirectories for
each of the technologies discussed in the tutorial.

Application Server
The Sun Java System Application Server Platform Edition 9 is targeted as the
build and runtime environment for the tutorial examples. To build, deploy, and
run the examples, you need a copy of the Application Server and Java 2 Plat-
form, Standard Edition 5.0 (J2SE 5.0). If you already have a copy of the J2SE
SDK, you can download the Application Server from:

http://java.sun.com/javaee/downloads/index.html

You can also download the Java EE 5 SDK—which contains the Application
Server and the J2SE SDK—from the same site.
xxxi

Application Server Installation Tips


In the Admin configuration pane of the Application Server installer,
• Select the Don’t Prompt for Admin User Name radio button. This will save
the user name and password so that you won’t need to provide them when
performing administrative operations with asadmin. You will still have to
provide the user name and password to log in to the Admin Console.
• Note the HTTP port at which the server is installed. This tutorial assumes
that you are accepting the default port of 8080. If 8080 is in use during
installation and the installer chooses another port or if you decide to
change it yourself, you will need to update the common build properties
file (described in the next section) and the configuration files for some of
the tutorial examples to reflect the correct port.
In the Installation Options pane, check the Add Bin Directory to PATH checkbox
so that Application Server scripts (asadmin, asant, wsimport, wsgen, xjc, and
schemagen) override other installations.

Apache Ant
Ant is a Java technology-based build tool developed by the Apache Software
Foundation (http://ant.apache.org), and is used to build, package, and
deploy the tutorial examples. Ant is included with the Application Server. To use
the ant command-line tool add <JAVAEE_HOME>/lib/ant/bin to your PATH
environment variable.

Registry Server
You need a registry server to run the examples discussed in Chapter 19. Instruc-
tions for obtaining and setting up a registry server are provided in Chapter 19.

Building the Examples


The tutorial examples are distributed with a configuration file for ant or asant, a
portable build tool contained in the Application Server. This tool is an extension
of the Ant tool developed by the Apache Software Foundation
(http://ant.apache.org). The asant utility contains additional tasks that
invoke the Application Server administration utility asadmin. Directions for
building the examples are provided in each chapter. Either ant or asant may be
used to build, package, and deploy the examples.
xxxii

Build properties common to all the examples are specified in the


<INSTALL>/javaeetutorial5/examples/bp-project/build.properties
file. This file must be created before you run the examples. We’ve included a
sample file <INSTALL>/javaeetutorial5/examples/bp-
project/build.properties.sample that you should rename to
<INSTALL>/javaeetutorial5/examples/bp-project/build.properties and
edit to reflect your environment. The tutorial examples use the Java BluePrints
(http://java.sun.com/reference/blueprints/) build system and applica-
tion layout structure.
To run the ant scripts, you must set common build properties in the file
<INSTALL>/javaeetutorial5/examples/bp-project/build.properties as
follows:
• Set the javaee.home property to the location of your Application Server
installation. The build process uses the javaee.home property to include
the libraries in <JAVAEE_HOME>/lib/ in the classpath. All examples that
run on the Application Server include the Java EE library archive—
<JAVAEE_HOME>/lib/javaee.jar—in the build classpath. Some exam-
ples use additional libraries in <JAVAEE_HOME>/lib/; the required libraries
are enumerated in the individual technology chapters. <JAVAEE_HOME>
refers to the directory where you have installed the Application Server.

Note: On Windows, you must escape any backslashes in the javaee.home property
with another backslash or use forward slashes as a path separator. So, if your Appli-
cation Server installation is C:\Sun\AppServer, you must set javaee.home as fol-
lows:

javaee.home = C:\\Sun\\AppServer

or

javaee.home=C:/Sun/AppServer

• Set the javaee.tutorial.home property to the location of your tutorial.


This property is used for asant deployment and undeployment.
For example, on UNIX:
javaee.tutorial.home=/home/username/javaeetutorial5
On Windows:
javaee.tutorial.home=C:/javaeetutorial5
xxxiii

Do not install the tutorial to a location with spaces in the path.


• If you did not use the default value (admin) for the admin user, set the
admin.user property to the value you specified when you installed the
Application Server.
• If you did not use port 8080, set the domain.resources.port property to
the value specified when you installed the Application Server.
• Set the admin user’s password in
<INSTALL>/javaeetutorial5/examples/common/admin-pass-
word.txt to the value you specified when you installed the Application
Server. The format of this file is AS_ADMIN_PASSWORD=password. For
example:
AS_ADMIN_PASSWORD=mypassword

Tutorial Example Directory Structure


To facilitate iterative development and keep application source separate from
compiled files the tutorial examples use the Java BluePrints application directory
structure.
Each application module has the following structure:
• build.xml: Ant build file
• src/java: Java source files for the module
• src/conf: configuration files for the module, with the exception of web
applications
• web: JSP and HTML pages, style sheets, tag files, and images
• web/WEB-INF: configuration files for web applications
• nbproject: NetBeans project files
Examples that have multiple application modules packaged into an enterprise
application archive (or EAR) have submodule directories that use the following
naming conventions:
• <EXAMPLE_NAME>-app-client: Application clients
• <EXAMPLE_NAME>-ejb: Enterprise bean JARs
• <EXAMPLE_NAME>-war: web applications
The Ant build files (build.xml) distributed with the examples contain targets to
create a build subdirectory and to copy and compile files into that directory; a
xxxiv

dist subdirectory, which holds the packaged module file; and a client-jar
directory, which holds the retrieved application client JAR.

Further Information
This tutorial includes the basic information that you need to deploy applications
on and administer the Application Server.
See the Sun Java™ System Application Server Platform Edition 9 Developer’s
Guide at http://docs.sun.com/app/docs/doc/819-3659 for information
about developer features of the Application Server.
See the Sun Java™ System Application Server Platform Edition 9 Administra-
tion Guide at http://docs.sun.com/app/docs/doc/819-3658 for information
about administering the Application Server.
For information about the Java DB database included with the Application
Server see the Apache web site at http://db.apache.org/derby.

How to Print This Tutorial


To print this tutorial, follow these steps:
1. Ensure that Adobe Acrobat Reader is installed on your system.
2. Open the PDF version of this book.
3. Click the printer icon in Adobe Acrobat Reader.

Typographical Conventions
Table 2 lists the typographical conventions used in this tutorial.

Table 2 Typographical Conventions

Font Style Uses

italic Emphasis, titles, first occurrence of terms


xxxv

Table 2 Typographical Conventions

Font Style Uses

URLs, code examples, file names, path names, tool names,


monospace application names, programming language keywords, tag,
interface, class, method, and field names, properties

italic monospace Variables in code, file paths, and URLs

<italic monospace> User-selected file path components

Menu selections indicated with the right-arrow character →, for example,


First→Second, should be interpreted as: select the First menu, then choose Sec-
ond from the First submenu.

Feedback
To send comments, broken link reports, errors, suggestions, and questions about
this tutorial to the tutorial team, please use the feedback form at
http://java.sun.com/javaee/5/docs/tutorial/information/sendus-
mail.html.
xxxvi
1
Overview

Developers today increasingly recognize the need for distributed, transac-


tional, and portable applications that leverage the speed, security, and reliability
of server-side technology. In the world of information technology, enterprise
applications must be designed, built, and produced for less money, with greater
speed, and with fewer resources.
With the Java™ Platform, Enterprise Edition (Java EE), development of Java
enterprise applications has never been easier or faster. The aim of the Java EE 5
platform is to provide developers a powerful set of APIs while reducing develop-
ment time, reducing application complexity, and improving application perfor-
mance.
The Java EE 5 platform introduces a simplified programming model. With Java
EE 5 technology, XML deployment descriptors are now optional. Instead, a
developer can simply enter the information as an annotation directly into a Java
source file, and the Java EE server will configure the component at deployment
and run-time. These annotations are generally used to embed in a program data
that would otherwise be furnished in a deployment descriptor. With annotations,
the specification information is put directly in your code next to the program ele-
ment that it affects.
In the Java EE platform, dependency injection can be applied to all resources
that a component needs, effectively hiding the creation and lookup of resources
from application code. Dependency injection can be used in EJB containers, web
containers, and application clients. Dependency injection allows the Java EE
container to automatically insert references to other required components or
resources using annotations.
1
2 OVERVIEW

The Java™ Persistence API is new to the Java EE 5 platform. The Java Persis-
tence API provides an object/relational mapping for managing relational data in
enterprise beans, web components, and application clients. It can also be used in
Java SE applications, outside of the Java EE environment.
This tutorial uses examples to describe the features and functionalities available
in the Java EE 5 platform for developing enterprise applications. Whether you
are a new or experienced Enterprise developer, you should find the examples and
accompanying text a valuable and accessible knowledge base for creating your
own solutions.
If you are new to Java EE enterprise application development, this chapter is a
good place to start. Here you will review development basics, learn about the
Java EE architecture and APIs, become acquainted with important terms and
concepts, and find out how to approach Java EE application programming,
assembly, and deployment.

Java EE Application Model


The Java EE application model begins with the Java programming language and
the Java virtual machine. The proven portability, security, and developer produc-
tivity they provide forms the basis of the application model. Java EE is designed
to support applications that implement enterprise services for customers,
employees, suppliers, partners, and others who make demands on or contribu-
tions to the enterprise. Such applications are inherently complex, potentially
accessing data from a variety of sources and distributing applications to a variety
of clients.
To better control and manage these applications, the business functions to sup-
port these various users are conducted in the middle tier. The middle tier repre-
sents an environment that is closely controlled by an enterprise’s information
technology department. The middle tier is typically run on dedicated server
hardware and has access to the full services of the enterprise.
The Java EE application model defines an architecture for implementing services
as multi-tier applications that deliver the scalability, accessibility, and manage-
ability needed by enterprise-level applications. This model partitions the work
needed to implement a multi-tier service into two parts: the business and presen-
tation logic to be implemented by the developer, and the standard system ser-
vices provided by the Java EE platform. The developer can rely on the platform
to provide solutions for the hard systems-level problems of developing a multi-
tier service.
DISTRIBUTED MULTITIERED APPLICATIONS 3

Distributed Multitiered Applications


The Java EE platform uses a distributed multitiered application model for enter-
prise applications. Application logic is divided into components according to
function, and the various application components that make up a Java EE appli-
cation are installed on different machines depending on the tier in the multitiered
Java EE environment to which the application component belongs. Figure 1–1
shows two multitiered Java EE applications divided into the tiers described in the
following list. The Java EE application parts shown in Figure 1–1 are presented
in Java EE Components (page 5).
• Client-tier components run on the client machine.
• Web-tier components run on the Java EE server.
• Business-tier components run on the Java EE server.
• Enterprise information system (EIS)-tier software runs on the EIS server.
Although a Java EE application can consist of the three or four tiers shown in
Figure 1–1, Java EE multitiered applications are generally considered to be
three-tiered applications because they are distributed over three locations: client
machines, the Java EE server machine, and the database or legacy machines at
the back end. Three-tiered applications that run in this way extend the standard
two-tiered client and server model by placing a multithreaded application server
between the client application and back-end storage.
4 OVERVIEW

Figure 1–1 Multitiered Applications

Security
While other enterprise application models require platform-specific security
measures in each application, the Java EE security environment enables security
constraints to be defined at deployment time. The Java EE platform makes appli-
cations portable to a wide variety of security implementations by shielding appli-
cation developers from the complexity of implementing security features.
The Java EE platform provides standard declarative access control rules that are
defined by the developer and interpreted when the application is deployed on the
server. Java EE also provides standard login mechanisms so application develop-
ers do not have to implement these mechanisms in their applications. The same
application works in a variety of different security environments without chang-
ing the source code.
JAVA EE COMPONENTS 5

Java EE Components
Java EE applications are made up of components. A Java EE component is a
self-contained functional software unit that is assembled into a Java EE applica-
tion with its related classes and files and that communicates with other compo-
nents. The Java EE specification defines the following Java EE components:
• Application clients and applets are components that run on the client.
• Java Servlet, JavaServer Faces, and JavaServer Pages™ (JSP™) technol-
ogy components are web components that run on the server.
• Enterprise JavaBeans™ (EJB™) components (enterprise beans) are busi-
ness components that run on the server.
Java EE components are written in the Java programming language and are com-
piled in the same way as any program in the language. The difference between
Java EE components and “standard” Java classes is that Java EE components are
assembled into a Java EE application, are verified to be well formed and in com-
pliance with the Java EE specification, and are deployed to production, where
they are run and managed by the Java EE server.

Java EE Clients
A Java EE client can be a web client or an application client.

Web Clients
A web client consists of two parts: (1) dynamic web pages containing various
types of markup language (HTML, XML, and so on), which are generated by
web components running in the web tier, and (2) a web browser, which renders
the pages received from the server.
A web client is sometimes called a thin client. Thin clients usually do not query
databases, execute complex business rules, or connect to legacy applications.
When you use a thin client, such heavyweight operations are off-loaded to enter-
prise beans executing on the Java EE server, where they can leverage the secu-
rity, speed, services, and reliability of Java EE server-side technologies.
6 OVERVIEW

Applets
A web page received from the web tier can include an embedded applet. An
applet is a small client application written in the Java programming language
that executes in the Java virtual machine installed in the web browser. However,
client systems will likely need the Java Plug-in and possibly a security policy file
in order for the applet to successfully execute in the web browser.
Web components are the preferred API for creating a web client program
because no plug-ins or security policy files are needed on the client systems.
Also, web components enable cleaner and more modular application design
because they provide a way to separate applications programming from web
page design. Personnel involved in web page design thus do not need to under-
stand Java programming language syntax to do their jobs.

Application Clients
An application client runs on a client machine and provides a way for users to
handle tasks that require a richer user interface than can be provided by a markup
language. It typically has a graphical user interface (GUI) created from the
Swing or the Abstract Window Toolkit (AWT) API, but a command-line inter-
face is certainly possible.
Application clients directly access enterprise beans running in the business tier.
However, if application requirements warrant it, an application client can open
an HTTP connection to establish communication with a servlet running in the
web tier. Application clients written in languages other than Java can interact
with Java EE 5 servers, enabling the Java EE 5 platform to interoperate with leg-
acy systems, clients, and non-Java languages.

The JavaBeans™ Component Architecture


The server and client tiers might also include components based on the Java-
Beans component architecture (JavaBeans components) to manage the data flow
between an application client or applet and components running on the Java EE
server, or between server components and a database. JavaBeans components are
not considered Java EE components by the Java EE specification.
JavaBeans components have properties and have get and set methods for
accessing the properties. JavaBeans components used in this way are typically
simple in design and implementation but should conform to the naming and
design conventions outlined in the JavaBeans component architecture.
WEB COMPONENTS 7

Java EE Server Communications


Figure 1–2 shows the various elements that can make up the client tier. The cli-
ent communicates with the business tier running on the Java EE server either
directly or, as in the case of a client running in a browser, by going through JSP
pages or servlets running in the web tier.
Your Java EE application uses a thin browser-based client or thick application
client. In deciding which one to use, you should be aware of the trade-offs
between keeping functionality on the client and close to the user (thick client)
and off-loading as much functionality as possible to the server (thin client). The
more functionality you off-load to the server, the easier it is to distribute, deploy,
and manage the application; however, keeping more functionality on the client
can make for a better perceived user experience.

Figure 1–2 Server Communication

Web Components
Java EE web components are either servlets or pages created using JSP technol-
ogy (JSP pages) and/or JavaServer Faces technology. Servlets are Java program-
ming language classes that dynamically process requests and construct
responses. JSP pages are text-based documents that execute as servlets but allow
8 OVERVIEW

a more natural approach to creating static content. JavaServer Faces technology


builds on servlets and JSP technology and provides a user interface component
framework for web applications.
Static HTML pages and applets are bundled with web components during appli-
cation assembly but are not considered web components by the Java EE specifi-
cation. Server-side utility classes can also be bundled with web components and,
like HTML pages, are not considered web components.
As shown in Figure 1–3, the web tier, like the client tier, might include a Java-
Beans component to manage the user input and send that input to enterprise
beans running in the business tier for processing.

Business Components
Business code, which is logic that solves or meets the needs of a particular busi-
ness domain such as banking, retail, or finance, is handled by enterprise beans
running in the business tier. Figure 1–4 shows how an enterprise bean receives
data from client programs, processes it (if necessary), and sends it to the enter-
prise information system tier for storage. An enterprise bean also retrieves data
from storage, processes it (if necessary), and sends it back to the client program.

Figure 1–3 Web Tier and Java EE Applications


ENTERPRISE INFORMATION SYSTEM TIER 9

Figure 1–4 Business and EIS Tiers

Enterprise Information System Tier


The enterprise information system tier handles EIS software and includes enter-
prise infrastructure systems such as enterprise resource planning (ERP), main-
frame transaction processing, database systems, and other legacy information
systems. For example, Java EE application components might need access to
enterprise information systems for database connectivity.

Java EE Containers
Normally, thin-client multitiered applications are hard to write because they
involve many lines of intricate code to handle transaction and state management,
multithreading, resource pooling, and other complex low-level details. The com-
ponent-based and platform-independent Java EE architecture makes Java EE
applications easy to write because business logic is organized into reusable com-
ponents. In addition, the Java EE server provides underlying services in the form
of a container for every component type. Because you do not have to develop
10 OVERVIEW

these services yourself, you are free to concentrate on solving the business prob-
lem at hand.

Container Services
Containers are the interface between a component and the low-level platform-
specific functionality that supports the component. Before a web, enterprise
bean, or application client component can be executed, it must be assembled into
a Java EE module and deployed into its container.
The assembly process involves specifying container settings for each component
in the Java EE application and for the Java EE application itself. Container set-
tings customize the underlying support provided by the Java EE server, including
services such as security, transaction management, Java Naming and Directory
Interface™ (JNDI) lookups, and remote connectivity. Here are some of the high-
lights:
• The Java EE security model lets you configure a web component or enter-
prise bean so that system resources are accessed only by authorized users.
• The Java EE transaction model lets you specify relationships among meth-
ods that make up a single transaction so that all methods in one transaction
are treated as a single unit.
• JNDI lookup services provide a unified interface to multiple naming and
directory services in the enterprise so that application components can
access these services.
• The Java EE remote connectivity model manages low-level communica-
tions between clients and enterprise beans. After an enterprise bean is cre-
ated, a client invokes methods on it as if it were in the same virtual
machine.
Because the Java EE architecture provides configurable services, application
components within the same Java EE application can behave differently based
on where they are deployed. For example, an enterprise bean can have security
settings that allow it a certain level of access to database data in one production
environment and another level of database access in another production environ-
ment.
The container also manages nonconfigurable services such as enterprise bean
and servlet life cycles, database connection resource pooling, data persistence,
and access to the Java EE platform APIs (see section Java EE 5 APIs, page 19).
CONTAINER TYPES 11

Container Types
The deployment process installs Java EE application components in the Java EE
containers illustrated in Figure 1–5.

Figure 1–5 Java EE Server and Containers

Java EE server
The runtime portion of a Java EE product. A Java EE server provides EJB
and web containers.
Enterprise JavaBeans (EJB) container
Manages the execution of enterprise beans for Java EE applications. Enter-
prise beans and their container run on the Java EE server.
Web container
Manages the execution of JSP page and servlet components for Java EE
applications. Web components and their container run on the Java EE server.
Application client container
Manages the execution of application client components. Application clients
and their container run on the client.
Applet container
Manages the execution of applets. Consists of a web browser and Java Plug-
in running on the client together.
12 OVERVIEW

Web Services Support


Web services are web-based enterprise applications that use open, XML-based
standards and transport protocols to exchange data with calling clients. The Java
EE platform provides the XML APIs and tools you need to quickly design,
develop, test, and deploy web services and clients that fully interoperate with
other web services and clients running on Java-based or non-Java-based plat-
forms.
To write web services and clients with the Java EE XML APIs, all you do is pass
parameter data to the method calls and process the data returned; or for docu-
ment-oriented web services, you send documents containing the service data
back and forth. No low-level programming is needed because the XML API
implementations do the work of translating the application data to and from an
XML-based data stream that is sent over the standardized XML-based transport
protocols. These XML-based standards and protocols are introduced in the fol-
lowing sections.
The translation of data to a standardized XML-based data stream is what makes
web services and clients written with the Java EE XML APIs fully interoperable.
This does not necessarily mean that the data being transported includes XML
tags because the transported data can itself be plain text, XML data, or any kind
of binary data such as audio, video, maps, program files, computer-aided design
(CAD) documents and the like. The next section introduces XML and explains
how parties doing business can use XML tags and schemas to exchange data in a
meaningful way.

XML
XML is a cross-platform, extensible, text-based standard for representing data.
When XML data is exchanged between parties, the parties are free to create their
own tags to describe the data, set up schemas to specify which tags can be used
in a particular kind of XML document, and use XML stylesheets to manage the
display and handling of the data.
For example, a web service can use XML and a schema to produce price lists,
and companies that receive the price lists and schema can have their own
SOAP TRANSPORT PROTOCOL 13

stylesheets to handle the data in a way that best suits their needs. Here are exam-
ples:
• One company might put XML pricing information through a program to
translate the XML to HTML so that it can post the price lists to its intranet.
• A partner company might put the XML pricing information through a tool
to create a marketing presentation.
• Another company might read the XML pricing information into an appli-
cation for processing.

SOAP Transport Protocol


Client requests and web service responses are transmitted as Simple Object
Access Protocol (SOAP) messages over HTTP to enable a completely interoper-
able exchange between clients and web services, all running on different plat-
forms and at various locations on the Internet. HTTP is a familiar request-and
response standard for sending messages over the Internet, and SOAP is an XML-
based protocol that follows the HTTP request-and-response model.
The SOAP portion of a transported message handles the following:
• Defines an XML-based envelope to describe what is in the message and
how to process the message
• Includes XML-based encoding rules to express instances of application-
defined data types within the message
• Defines an XML-based convention for representing the request to the
remote service and the resulting response

WSDL Standard Format


The Web Services Description Language (WSDL) is a standardized XML format
for describing network services. The description includes the name of the ser-
vice, the location of the service, and ways to communicate with the service.
WSDL service descriptions can be stored in UDDI registries or published on the
web (or both). The Sun Java System Application Server Platform Edition 8 pro-
vides a tool for generating the WSDL specification of a web service that uses
remote procedure calls to communicate with clients.
14 OVERVIEW

UDDI and ebXML Standard Formats


Other XML-based standards, such as Universal Description, Discovery and Inte-
gration (UDDI) and ebXML, make it possible for businesses to publish informa-
tion on the Internet about their products and web services, where the information
can be readily and globally accessed by clients who want to do business.

Java EE Application Assembly and


Deployment
A Java EE application is packaged into one or more standard units for deploy-
ment to any Java EE platform-compliant system. Each unit contains:
• A functional component or components (enterprise bean, JSP page, serv-
let, applet, etc.)
• An optional deployment descriptor that describes its content
Once a Java EE unit has been produced, it is ready to be deployed. Deployment
typically involves using a platform’s deployment tool to specify location-specific
information, such as a list of local users that can access it and the name of the
local database. Once deployed on a local platform, the application is ready to
run.

Packaging Applications
A Java EE application is delivered in an Enterprise Archive (EAR) file, a stan-
dard Java Archive (JAR) file with an .ear extension. Using EAR files and mod-
ules makes it possible to assemble a number of different Java EE applications
using some of the same components. No extra coding is needed; it is only a mat-
ter of assembling (or packaging) various Java EE modules into Java EE EAR
files.
An EAR file (see Figure 1–6) contains Java EE modules and deployment
descriptors. A deployment descriptor is an XML document with an .xml exten-
sion that describes the deployment settings of an application, a module, or a
component. Because deployment descriptor information is declarative, it can be
changed without the need to modify the source code. At runtime, the Java EE
server reads the deployment descriptor and acts upon the application, module, or
component accordingly.
Exploring the Variety of Random
Documents with Different Content
remains social property. But another part is as means of living
consumed by the members of the association. It must therefore be
distributed among them. The nature of this distribution will change
according to the special nature of the organisation of production and
the corresponding grade of historical development of the producers.’
And then he goes on to assume that the share of each producer in
the means of living may be determined by his labour time. Labour
time will at once serve as measure of the share of each producer in
the common labour, and therefore also of his share in the portion of
the common product which is devoted to consumption.[5]
Another important indication by one who has full right to speak for
Marx is contained in Fr. Engels’ views regarding the State. After the
proletariat have seized political power and transformed the means of
production into State property, the State will cease to exist. In the
old societies the State was an organisation of the exploiting class for
the maintenance of the conditions of exploitation that suited it.
Officially the representatives of the whole society, the exploiting
class only represented itself. But when the State at last becomes the
real representative of the whole society it renders itself superfluous.
In a society which contains no subject class, from which class rule
and the anarchy of production and the collisions and excesses of the
struggle for individual existence have been removed, there is
nothing to repress, and no need for a repressing force like the State.
The first act wherein the State really appears as representative of
the entire society—the appropriation of the means of production in
the name of society—is also its last independent act as State. In
place of the government over persons, there will be an
administration of things and the control of productive processes. The
State is not abolished; it dies away.[6]
In effect, these two indications of opinion point to a condition of
society which is not fundamentally different from that contemplated
by the anarchist school. Both look forward to a period when men will
live in free associations, and when the administration of social affairs
will be conducted without the exercise of compulsion.
It will have been seen that what Marx and his school contemplate is
an economic revolution brought about in accordance with the natural
laws of historic evolution. But in order to understand the full import
of this revolution in the mind of Marx, we must remember that he
regards the economic order of society as the groundwork of the
same, determining all the other forms of social order. The entire
legal and political structure, as well as philosophy and religion, are
constituted and controlled in accordance with the economic basis.
This is in harmony with his method and his conception of the world,
which is the Hegelian reversed: ‘For Hegel the thought process,
which he transforms into an independent subject under the name
idea, is the creator of the real, which forms only its external
manifestation. With me, on the contrary, the ideal is nothing else
than the material transformed and translated in the human brain.’
His conception of the world is a frank and avowed materialism.
And to a world thus understood he applies the dialectic method of
investigation. Dialectic is a word current in the Hegelian and other
philosophies. It sounds rather out of place in a materialistic view of
the world. In the system of Marx it means that the business of
inquiry is to trace the connection and concatenation in the links that
make up the process of historic evolution, to investigate how one
stage succeeds another in the development of society, the facts and
forms of human life and history not being stable and stereotyped
things, but the ever-changing manifestations of the fluent and
unresting real, the course of which it is the duty of science to reveal.
Both Marx and Fr. Engels, moreover, are fond of expressing the
development of capitalism in the language of the well-known
Hegelian threefold process—thesis, antithesis, and synthesis. Private
property resting on a man’s own labour of the former times is the
thesis. The property resting on other men’s labour of the capitalistic
era is the negation of this individual property. The expropriation of
the capitalists by the proletariat is the negation of the negation, or
synthesis. But how far this use of the Hegelian terms is merely a
form of literary expression, or how far it is a survival in Marx of a
real belief in Hegelianism, it is not easy to determine.[7]
The whole position of the Marx school may be characterised as
evolutionary and revolutionary socialism, based on a materialistic
conception of the world and of human history. Socialism is a social
revolution determined by the laws of historic evolution—a revolution
which, changing the economic groundwork of society, will change
the whole structure.
It may now be convenient to sum up the socialism of the Marx
school under the following heads:—

(1) Materialistic conception of the world and of history.


(2) Dialectic method of investigation.
(3) The economic order is the basis of all social order; the
entire legal and political structures of society, religion, and
philosophy are to be explained in accordance with the
economic basis.
(4) The historic evolution of capitalism; how, from the
fifteenth century onwards, the capitalist class was
developed, and how a corresponding proletariat was
created.
(5) The capitalist class grows by the appropriation and
accumulation of the surplus value contained in the product
of labour, whilst the proletariat is reduced to a subsistence
wage. It is social production and capitalistic appropriation.
(6) Organisation in the factory; anarchy in society as a
whole.
(7) This anarchy is intensified, especially in the great
commercial crises, showing that the middle class are no
longer able to control the productive forces.
(8) All these contradictions can be solved only by an explicit
recognition of the social character of production. The
proletariat seizes political power and transforms the means
of production into social property.
(9) The State, which has hitherto been an arrangement for
holding the producing class in subjection, will become
superfluous, and die a natural death. Henceforward,
government will consist simply in the control of industrial
processes.

The work of Marx is a natural history of capital, especially in its


relation to labour, and in its most essential features is a development
of two of the leading principles of the classic economics—that labour
is the source of value, but that of this value the labourer obtains for
himself merely a subsistence wage, the surplus being appropriated
by the exploiting capitalist. Marx’s great work may be described as
an elaborate historical development of this glaring fundamental
contradiction of the Ricardian economics, the contradiction between
the Iron Law of Wages and the great principle that labour is the
source of wealth. Marx’s conception of labour is the same as that of
Ricardo, and as a logical exposition of the historic contradiction
between the two principles, on the basis of Ricardo, the work of
Marx is quite unanswerable. It is obvious, however, that the
definition of labour assumed both in Ricardo and Marx is too narrow.
The labour they broadly posit as the source of wealth is manual
labour. In the early stages of industry, when the market was small
and limited, and the technique was of the simplest and rudest
description, labour in that sense might correctly enough be
described as the source of value. But in modern industry, when the
market is world-wide, the technique most complex, and the
competition most severe, when inventiveness, sagacity, courage, and
decision in initiative, and skill in management, are factors so
important, no such exclusive place as has been claimed can be
assigned to labour. The Ricardian principle, therefore, falls to the
ground.
And it is not historically true to maintain, as Marx does, that the
profits of the capitalist are obtained simply by appropriating the
products of unpaid labour. In initiating and managing, the capitalist
is charged with the most difficult and important part of the work of
production. As a natural consequence, it follows that Marx is also
historically inaccurate in roundly explaining capital as the
accumulation of unpaid labour appropriated by the capitalist. In past
accumulation, as in the control and management of industry
generally, the capitalist has had the leading part. Capital, therefore,
is not necessarily robbery, and in an economic order in which the
system of free exchange is the rule and the mutually beneficial
interchange of utilities, no objection can be raised to the principle of
lending and borrowing of money for interest. In short, in his theory
of unpaid labour as supplying the key to his explanation of the
genesis and development of the capitalistic system, Marx is not true
to history. It is the perfectly logical outcome of certain of the leading
principles of the Ricardian school, but it does not give an adequate
or accurate account of the facts of economic evolution.
In his theory of unpaid labour Marx is not consistent with the
general principles of his own philosophy of social evolution. With him
history is a process determined by material forces, a succession of
orderly phenomena controlled by natural laws. Now we may waive
the objection suggested by the principle enunciated in the Marx
school itself, that it is not legitimate to apply ethical categories in
judgment on economic processes that are merely natural; which,
however, Marx does with revolutionary emphasis throughout some
hundreds of pages of his great work. It is more important to point
out, in perfect consistency with the principles of the school, that the
energy and inventiveness of the early capitalists especially were the
most essential factors in determining the existence and development
of a great economic era, and that the assertion of freedom was an
indispensable condition in breaking the bonds of the old feudal order,
which the new system displaced. Instead, therefore, of living and
growing rich on the produce of unpaid labour, the capitalist had a
great social and industrial function to perform, and played a great
part in historic evolution. The position and function of the workman
was subordinate.
In short, Marx has not sufficiently recognised the fact that the
development of the new social forces brought with it a new set of
functions: that of initiating and directing industrial enterprise. These
functions are not comprehended in the narrow definition of labour,
but they are, nevertheless, most essential to progress; and the men
that performed them have a most complete historical reason for
their existence and a share in the results of industry. We need not
add that such an argument does not justify all they did as the heads
of the new industry. There is ample evidence that they were often
rough, hard, cruel, and unscrupulous in the prosecution of their
industrial enterprises. Nor does it prejudice the question whether the
like direction of industry must and should continue in the future.
There can be no doubt that in his theory of surplus value obtained
from unpaid labour, Marx, as agitator and controversialist, has fallen
into serious contradiction with himself as scientific historian and
philosopher. The theory that labour is the source of value was widely
accepted among economists during his early life, and by its justice
and nobleness it was well adapted to the comfortable optimism
prevalent among so many of the classical school. The economists,
however, did not follow the principle to its obvious conclusion: that if
labour is the source of wealth, the labourer should enjoy it all. It was
otherwise with the socialists, who were not slow to perceive the
bearing of the theory on the existing economic order. In his
controversial treatise against Proudhon, Marx gives a list of writers
(beginning with the political economy of Hopkins,[8] published in
1822, only five years after the appearance of Ricardo’s great work),
by whom the principle was applied to revolutionary purposes. Its
simplicity and seeming effectiveness must have made it most
attractive. As posited by the classic economy, and applied by the
socialists, Marx accepted the principle. It was an unanswerable
argumentum ad hominem when addressed to an economist of the
Ricardian school; but it should have broken down when confronted
with historical fact. Nevertheless it was made, and continued to be,
the foundation-stone of the system of Marx, and is really its weakest
point. His doctrine of surplus value is the vitiating factor in his
history of the capitalistic system. The most obvious excuse for him is
that he borrowed it from the classic economists.
Fr. Engels sums up the achievement of his friend Marx in the two
great discoveries—the materialistic conception of history, and the
revelation of the secret of the capitalistic method of production by
means of surplus value. Materialism is a very old theory of the world.
It is now given up by competent thinkers, and we need not discuss it
here. Nor need we say that it is a grave exaggeration to maintain
that all social institutions, including philosophy and religion, are to
be explained by reference to the economic factors. History is a
record of the activity of the human mind in very many directions.
Men have had various interests, which have had a substantive, and
so far, an independent value, though they must also be regarded as
an organic whole. It is absolutely impossible to account for all by
reference to any one.
Nevertheless, it is a great merit of Marx that he has so powerfully
called attention to the vast importance of the economic side of
history. The economic factors in the life of mankind have been sadly
neglected, even by philosophic historians. Such neglect has been
partly due to the scarcity of material relating to this aspect of their
subject, partly owing to false conceptions of the function of the
historian, chiefly because their public was a high-bred class, which
had no particular wish to read about such unfashionable topics as
those connected with the daily toil of the lower orders. In this way
the true causation of history has often been overlooked, or totally
misconceived, and results have, in thousands of instances, been
traced to conventional and imaginary agencies, when the real origin
lay deep down in the economic life of the people. We are now
beginning to see that large sections of history will need to be
rewritten in this new light.
To proceed with our criticism of Marx. It is a feature of his
materialistic conception of history that his language respecting the
inevitable march of society would sometimes suggest a kind of
fatalism. But this is more than counterbalanced by his strong
assertion of the revolutionary will. On both sides we see
overstatement. The most prominent feature of his teaching,
however, in this reference, is the excessive stress which he lays on
the virtues and possibilities of the revolutionary method of action.
The evolution he contemplates is attended and disturbed by great
historic breaks, by cataclysm and catastrophe. These and other
features of his teaching, to which objection must be made, were
most pronounced in his early writings, especially in the Manifesto of
the Communist League, but they continue to be visible throughout
his life. According to his latest teaching, a great revolutionary
catastrophe is to close the capitalistic era; and this must be regarded
as a very bad preparation for the time of social peace which is
forthwith to follow. The proletariat, the class which is to accomplish
the revolution, he described as oppressed, enslaved, and
degenerate. How can such a class be expected to perform so great
an historic function well and successfully?
But the main defect of his teaching lies in the arbitrariness and
excessive abstractness that characterise his method of investigation
and presentation; and this defect particularly attaches to the second
great discovery attributed to him by Fr. Engels—his theory of surplus
value.
We shall better understand the position of Marx if we recall some of
the important circumstances in his life and experience. As we have
seen, his family passed from the profession of Judaism to
Christianity when he was six years of age, and he thus lost the
traditions of the faith of his ancestors without living into the
traditions of the new faith. Like many Jews in a similar position the
traditions of the past therefore had little influence on Karl Marx, and
he was so far well fitted to take a wide and unprejudiced view of
human affairs. With his great endowments and vast knowledge he
should have been one of the freest heads in Europe. His practical
energy was not inferior to the range of his intelligence.
All the more regrettable, therefore, is it that Marx should have
adopted such a narrowing system of philosophy as materialism. It is
also remarkable that he, the severest of critics, should have
adopted, at so early an age and without due scrutiny, the theory of
value set forth by Adam Smith and Ricardo, and that he should have
applied it without question during the remainder of his life to the
building up of a vast system of thought, and to a socialistic
propaganda which was meant to revolutionise the world. Another
instance of the premature dogmatism which has so often exercised a
great and not seldom a mischievous influence on human thought.
In this connection it may not be altogether fanciful to observe that
his heredity derived from rabbinical ancestors may account for much
that is peculiar in his way of thinking. The excessive acumen, the
relentless minuteness with which he pursues his course through
details which often seem very unreal, the elaboration which he
bestows upon distinctions which are often abstract and artificial, may
well be regarded as alien to Western modes of thought.
Revolutionary materialism was a strange sphere in which to exercise
a logic after the manner of the rabbi.
However this may be, we know that when his mind was being
formed the Hegelian philosophy was supreme in Germany; and it
can hardly be said that the study of Hegel is a good training for the
study of history, according to the freest and purest conception of the
subject. The study of history, in the highest sense of the word,
requires a modest attitude towards objective fact which is not easily
attained in the philosophy of the schools.
Marx was a German, trained in the school of Hegel; and he passed
most of his life in laborious seclusion, in exile and revolt against
dominant ideas and institutions. Though a materialist, he does not
show sufficient respect for facts, for history. In reading his great
work we feel that the facts are in chronic rebellion against the
formulas to which he seeks to adapt them.
Adam Smith, the founder of Political Economy, was also academic at
the outset of his life; but he was a Scotsman of a period when the
ablest Scotsmen were trained by French clearness and common
sense. And he was not in revolt, like Marx, but in full sympathy with
a cause whose time had come, whereas Marx represented a cause
which had not yet attained to any considerable degree of clearness.
In learning and philosophic power, Marx will compare favourably with
Adam Smith; but in historic reasonableness, in respect for fact and
reality, Smith is decidedly his superior. In Smith’s great work we see
philosophy controlled by fact, by historic knowledge and insight. The
work of Marx, in many of its most important sections, is an arbitrary
and artificial attempt to force his formulas on the facts of history.
Whether the fault lay in the Hegelian philosophy, or in Marx’s use of
it, there can be no doubt that its influence has inflicted most serious
damage on what might otherwise have been a splendid historical
work.
We are therefore obliged to say that the historical work of Marx does
not by any means rise to the highest conception of history. It is
deficient in the free outlook, in the clear perspective, in the
sympathy and impartiality which should characterise the best
historical achievements. The historical work of Marx is placed at the
service of a powerful and passionate propaganda, and of necessity is
disturbed and troubled by the function which it is made to serve.
In dealing with history we must accept facts and men as we find
them. The facts are as they are; and the men of history are not ideal
men. Like other men Marx had to work under human limitations. The
great task of his life was to rouse the proletariat of the world to a
sense of its position, its mission, and destiny, to discover the
scientific conditions under which a new era in the evolution of the
human race could be inaugurated and carried on by the working
classes of all lands. It was a mixed task in which science and
practice were combined, and in which the purely scientific study of
history naturally suffered in the partnership with a very strenuous
revolutionary practice.
We need not say that it was not the fault of Marx that he adopted
the revolutionary career. He was born at a time and in a country
where men of independence and originality of character of necessity
became revolutionists. In face of the European reaction Marx never
made any concession or compromise. He never bowed himself in the
house of Rimmon. Seldom in the history of human thought has there
been a man who travelled right ahead in so straightforward a path,
however formidable the opposition and however apparently hopeless
surrounding circumstances might be. Public opinion had no weight
with him; neither idle sentiment nor amiable weaknesses found any
place in his strongly-marked individuality.
In view of such a career spent in the unflinching service of what he
regarded to be truth, and in the greatest of human causes, it would
be mean and disgraceful not to speak of Marx in terms of profound
respect. His sincerity, his courage, his self-abnegation, his devotion
to his great work through long years of privation and obloquy, were
heroic. If he had followed the broad and well-beaten highway of
self-interest, Marx, with his exceptional endowments both for
thought and action, might easily have risen to a foremost place in
the Prussian State. He disdained the flesh-pots of despotism and
obscurantism so much sought after by the average sensual man, and
spent forty hard and laborious years almost wholly in exile as the
scientific champion of the proletariat. Many men are glad to live an
hour of glorious life. Few are strong and brave enough to live the life
heroic for forty years with the resolution, the courage, and
consistency of Karl Marx.
In the combination of learning, philosophic acumen, and literary
power, he is second to no economic thinker of the nineteenth
century. He seems to have been master of the whole range of
economic literature, and wielded it with a logical skill not less
masterly. But his great strength lay in his knowledge of the technical
and economic development of modern industry, and in his
marvellous insight into the tendencies in social evolution determined
by the technical and economic factors. Whether his theories in this
department are right or wrong, they have suggested questions that
will demand the attention of economic thinkers for a long time to
come. It is in this department, and not in his theory of surplus value,
that Marx’s significance as a scientific economist is to be found.
Notwithstanding all that may justly be said in criticism of Marx, it
remains, then, that his main achievement consists in the work he
has done as scientific inquirer into the economic movement of
modern times, as the philosophic historian of the capitalistic era. It is
now admitted by all inquirers worthy of the name that history,
including economic history, is a succession of orderly phenomena,
that each phase in the line of succession is marked by facts and
tendencies more or less peculiar to itself, and that laws and
principles which we now condemn had formerly an historical
necessity, justification, and validity. In accordance with this
fundamental principle of historical evolution, arrangements and
institutions which were once necessary, and originally formed a
stage in human progress, may gradually develop contradictions and
abuses, and thus become more or less antiquated.
The economic, social, and political forms which were the progressive
and even adequate expressions of the life of one era, become
hindrances and fetters to the life of the succeeding times. This, the
school of Karl Marx says, is precisely the condition of the present
economic order. The existing arrangements of landlord, capitalist,
and wage-labourer under free competition are burdened with
contradiction and abuse. The life of society is being strangled by the
forms which once promoted it. They maintain that the really vital
and powerful tendencies of our time are towards a higher and wider
form of social and economic organisation—towards socialism. Here,
as we believe, is the central point of the whole question. The place
of Marx in history will depend on how far he has made a permanent
contribution towards the settlement of it.
During his lifetime the opinions of Marx were destined to find
expression in two movements, which have played a considerable
part in recent history—the International and the Social Democracy of
Germany. Of the International, Marx was the inspiring and
controlling head from the beginning; and the German Social
Democracy, though originated by Lassalle, before long fell under
Marx’s influence. Marx wrote the famous inaugural address of the
International and drew up its statutes, maintaining a moderation of
tone which contrasted strongly with the outspoken vigour of the
communist manifesto of 1847. But it was not long before the
revolutionary socialism which underlay the movement gained the
upper hand. The International no doubt afforded a splendid
opportunity for the propaganda of Marx. The fortunes of the
International and of the German Social Democracy will be sketched
in subsequent chapters.

[1] Franz Mehring, Geschichte der Deutschen


Sozialdemokratie, part i. p. 156.
[2] An English translation of vol. i. by Messrs. Moore
and Aveling has appeared, Engels being editor.
There are translations also of vols. ii. and iii.
[3] This book of Engels, Eugen Dühring’s
Revolutionising of Science, is better known in its
much shorter form, Entwickelung des Sozialismus
von der Utopie zur Wissenschaft. Eng. tr. Socialism:
Utopian and Scientific.
[4] See Fr. Engels’ Umwälzung der Wissenschaft, p.
253, and passim.
[5] Das Kapital, i. 48.
[6] Umwälzung der Wissenschaft, pp. 267, 268.
[7] See Preface to second edition of the Kapital, p. xix.
[8] This, however, must be a mistake for T. Hodgskin,
who in 1825 published a pamphlet, Labour
defended against the Claims of Capital, in which
such views are set forth.
CHAPTER VIII

THE INTERNATIONAL

It is an inevitable outcome of the prevalent historic forces that the


labour question has become international.
From the dawn of history there has been a widening circle of
communities with international relations. Civilisation had its earliest
seats on the banks of the Nile and the Euphrates. The Greeks and
Phœnicians carried it round the shores of the Mediterranean. The
Romans received it from the Greeks, and, after adding to it a
valuable contribution of their own, handed it on to the nations of
Western and Central Europe. The Christian Church spread over the
countries in which the Roman peace prevailed, but did not confine
itself to the limits of the empire.
Amidst the group of nations who thus participated in the Greco-
Roman culture and in the Christian life, there has always been a
special degree of international sympathy: ideas and institutions have
been largely common to them all. Feudalism and the Church,
chivalry and the Crusades, all these were international in their
influence.
Then, as now, great ideas and great movements could not be
confined within national barriers. In the expansive and progressive
epochs of history, particularly, supreme interests have raised men
above the prejudices of race, and have united them by wider and
deeper principles than those by which they are separated into
nations.
At the great religious revolt of the sixteenth century, Germans
combined with the Swedes and the French against their own
countrymen. The Catholic Church, as its name implies, has always
been, and still continues to be, a great international institution.
The enlightenment of the eighteenth century had an international
influence, and at the French Revolution high concerns of political
and social freedom for a time broke through the conventional
feelings of patriotism. Germans, Italians, and even Englishmen, were
in many cases ready to receive the boon of a better order of things
at the price of French victory over their own countrymen. Only for a
time, till the enthusiasm of the Revolution was made subservient to
the selfishness of the new France—an instrument for the colossal
egotism of a single man.
In our time, steam and the electric telegraph have become the
bearers of a widening international movement. All the great human
interests are cultivated and pursued on a wider scale than ever—
religion, science, literature, art.
Commerce and industry have naturally shared in the general
expansion. We have only to scan the operations of the great markets
and exchanges in any daily paper as a proof of this. In a small space
round the Bank of England, financial transactions are carried on
which powerfully affect the entire world. Even the very simple
breakfast of an ordinary citizen is a great international function, in
which the productions of the most diverse countries combine to
appease his wants.
The methods and appliances of this modern industry have been
developed in England since the middle of the eighteenth century.
Not many years ago England was still the supreme, almost the
exclusive, representative of the new industry; now it is becoming the
common possession of all countries dominated by European culture,
and is rapidly gaining ground in the long-isolated nations of the East.
The competition for business among the capitalists of various
countries grows more intense every year. Once carried on chiefly or
entirely for local needs, production has now to work for a market of
wide and often incalculable extent.
Under these circumstances, we need not be surprised that labour,
the prime factor in industry, has international interests and relations
of the most serious importance. Its antagonism to capitalism must
declare itself on the international arena. In the competitive struggles
of the last sixty years, the cheap labour of one nation has not
seldom been thrown into the scale to weigh down the dear labour of
another. Irishmen, Germans, Belgians, and Italians have often
rendered unavailing the efforts of English and French workmen for a
higher standard of living. Continuous emigration from Europe
depresses American labour. The Chinese and other Eastern races,
habituated to a very low standard of subsistence, menace the
workmen of America and Australia. The great industry which is now
being established in the East will be a most serious danger alike to
workmen and capitalists in the Western World.
The capitalists of most countries have long sought to shield
themselves against the consequences of competition by protection,
by combinations tacit or avowed among themselves, of wide and
frequently international magnitude. In view of the facts that we have
indicated, in view of the example thus set them, why should not the
working men seek to regulate their international interests?
Efforts towards the international organisation of labour have
proceeded chiefly from men who, banished from their own country
by reactionary governments, have carried to other lands the seeds of
new thought, and, meeting abroad those of like mind and like fate
with themselves, have naturally planned the overthrow of their
common oppressors. The origin of the famous International
Association of Working Men was largely due to such a group of
exiles.
In 1836, a number of German exiles at Paris formed themselves into
a secret society, under the name of the League of the Just, the
principles of which were communistic.[1] Being involved in a rising at
Paris in 1839, they removed to London. Here they met with
workmen belonging to the nations of Northern Europe, to which
German is a common speech, and the League naturally began to
assume an international character.
This was not the only change which the League underwent. Its
members began to understand that their real duty under the present
circumstances was not conspiracy or the stirring up of revolutionary
outbreaks, but propaganda. The basis of the League had been a
sentimental communism, based on their motto that ‘all men are
brothers.’ From Marx they learned that the emancipation of the
proletariat must be guided by scientific insight into the conditions of
its own existence and its own history; that their communism must
indeed be a revolutionary one, but it must be a revolution in
harmony with the inevitable tendencies of social evolution. The
cardinal point in the theory worked out by Marx and now impressed
upon the League, was the doctrine that the economic conditions
control the entire social structure, therefore the main thing in a
social revolution is a change in economic conditions.
The group of exiles put themselves into communication with Marx,
and a Congress was held in London in 1847, with the result that the
association was reorganised under the name of the Communist
League.
The aim of the League is very comprehensively stated in the first
article of its constitution: ‘The aim of the League is the overthrow of
the bourgeoisie, the rule of the proletariat, the abolition of the old
society resting on class antagonisms, and the founding of a new
society without classes and without private property.’
Marx and Engels were commissioned by the League to set forth its
principles in a manifesto, which, as the manifesto of the communistic
party, was published shortly before the Revolution of February 1848.
We shall best illustrate the spirit and aim of the treatise by quoting
Fr. Engels’ Preface to the edition of 1883:—
‘The Preface to the present edition I must, alas! sign alone. Marx,
the man to whom the entire working class of Europe and America
owes more than any other—Marx rests in the cemetery at Highgate,
and the grass already begins to grow over his grave. Since his death
nothing further can be said of a revisal or completion of the
manifesto. It is therefore the more necessary expressly to make the
following statement.
‘The pervading thought of the manifesto: that the economic
production with the social organisation of each historical epoch
necessarily resulting therefrom forms the basis for the political and
intellectual history of this epoch; that accordingly (since the
dissolution of the primitive common property in land) the entire
history is a history of class struggles—struggles between exploited
and exploiting, ruled and ruling, classes at different stages of social
development; but that this struggle has now reached a stage when
the exploited and oppressed class (the proletariat) can no more free
itself from the exploiting and oppressing class (the bourgeoisie)
without at the same time delivering the whole of society for ever
from exploitation, oppression, and class struggles—this pervading
thought belongs exclusively and alone to Marx.’
‘The history of all society hitherto has been the history of class
struggles’; such is the keynote of the manifesto. ‘But it is a
distinguishing feature of the present time that it has simplified class
antagonisms; the entire human society more and more divides itself
into two great hostile camps, into two great conflicting classes,
bourgeoisie and proletariat.’ The manifesto is for the most part an
exposition and discussion of these two classes, the historical
conditions under which they have grown up, their mutual relations,
past, present, and future.
It would not be easy to give a brief analysis of the manifesto, nor is
it necessary, as we have, in our chapter on Marx, already given an
account of the same views in their maturer and more philosophic
expression. The manifesto is a treatise instinct with the fiery energy
and enthusiasm of a young revolutionary party, and its doctrines are
the doctrines of Marx in a crude, exaggerated, and violent form. In
such a pamphlet, written for propaganda, we must not expect the
self-restraining moderation of statement, the clear perspective, or
the high judicial charity which should characterise a sober historical
exposition.
The Iron Law of Wages is stated in its hardest and most exaggerated
form. To the charge that they desire to abolish private property, its
authors reply that individual property, the produce of a man’s own
labour, is already abolished. What they desire to abolish is the
appropriation of other men’s labour by the capitalist. To the charge
that they wish to abolish the family, they reply to the bourgeoisie
with a tu quoque: ye have already abolished it by the exploitation of
women and children in the factories, which has broken up the family
ties, through the prevalence of prostitution and the common practice
of adultery. The charge of abolishing patriotism they repudiate in the
same manner: the workman has no country.
We cannot understand the manifesto unless we remember that it
was drawn up by young men living in exile, and that it was written in
1847, shortly after some of the earliest inquiries into the condition of
labour both in England and the Continent had revealed facts which
ought to fill every human heart with sorrow and indignation.
As the manifesto of the first international combination of workmen,
it has a special historical importance, and claims special attention.
And apart from that, it is one of the most remarkable utterances of
the nineteenth century.
‘The manifesto,’ says Fr. Engels, ‘was sent to the press at London a
few weeks before the February Revolution. Since then it has made
the tour of the world. It has been translated into almost every
tongue, and in the most different countries still serves as the
guiding-star of the proletarian movement. The old motto of the
League, “All men are brethren,” was replaced by the new battle-cry,
“Proletarians of all lands unite,” which openly proclaimed the
international character of the struggle. Seventeen years later this
battle-cry resounded through the world as the watchword of the
International Working Men’s Association, and the militant proletariat
of all lands has to-day written it on its banner.’[2]
The Revolution of 1848, as we have already seen,[3] was a rising of
the people in France, Italy, Germany, Austria, and Hungary against
antiquated political arrangements and institutions. It was partly an
interruption to the operations of the League, as it was far too weak
to exercise any great influence on the course of events; but it was
also an opportunity, as its members found access to the land of their
birth, and in many parts of Germany formed the most resolute and
advanced wing of the struggling democracy during that troubled
period.
After the triumph of the reaction it became clear that the hope of
effective revolutionary activity had again for a time passed away. A
period of unexampled industrial prosperity set in. Capitalism was
about to enter a far wider phase of development than it had yet
seen, a fact which abundantly showed that the time was not
favourable for an active propaganda in the interests of the
proletariat. When capitalism has become a hindrance to progressive
social development, when it is obviously too weak and narrow a
framework for further evolution, only then is there hope of
successful effort against it. So reasoned Marx and his associates. He
withdrew, therefore, from the scene of action to his study in London.
In 1852 the first international combination of working men came to
a close. Observers who could not reasonably be considered
superficial, thought that the movement had died without hope of
resurrection.
But the triumph of reactionary governments in 1849 was not a
settlement of the great questions that had been raised during that
period of revolution; it was only a postponement of them. Before
many years had passed, the peoples of Europe again began to move
uneasily under the yoke of antiquated political forms. The rising of
Italy against Austria in 1859; the struggle of Prussian Liberals
against the Ministry; the resolve of Bismarck and his Sovereign to
have the Prussian army ready for action in the way of reconstituting
a united Germany on the ruins of the old Federation—these were
only different symptoms of a fresh advance. They were ere long to
be followed by similar activity in France, Spain, and Eastern Europe,
all proving that the history of European communities is an organic
movement, the reach and potency of which often disturb the
forecast of the politician. In the generation after 1848 the
governments were everywhere constrained to carry out the political
programme which the people had drawn out for them during the
revolution.
The social question may seem to have only a remote connection
with the political movements just mentioned, and yet the revival of
the social question was but another sign of the new life in Europe,
which could not be repressed. The founding of the Social Democracy
of Germany by Lassalle, and the appearance of the International on
a wider and worthier scale under the auspices of Marx, were a clear
proof that the working classes of the most advanced countries of
Europe now meant to claim a better share in the moral and material
inheritance of the human race. We have now to sketch the growth of
the movement, which is properly styled the International.
Appropriately enough, the event which gave the first occasion for
the founding of the International Association of Working Men was
the International Exhibition of London in 1862. The workmen of
France sent a deputation to visit the Exhibition. This visit had the
approval and even pecuniary support of the Emperor; and it was
warmly commended by some of the leading Parisian journals as a
means not only of acquainting the workmen with the industrial
treasures of the Exhibition, but of removing from the relations of the
two countries the old leaven of international discord and jealousy. In
the course of their visit the French delegates were entertained by
some of their English brethren at the Freemasons’ Tavern, where
views as to the identity of the interests of labour, and the necessity
for common action in promoting them, were interchanged.
In the following year a second deputation of French workmen
crossed the Channel. Napoleon was interested in the Polish
insurrection of 1863, and it was part of his policy to encourage the
expression of opinion in favour of an intervention in Poland by the
Western Powers. At this visit wishes for the restoration of Poland and
for general congresses in the interest of labour against capital were
expressed. Nothing decisive, however, was done till 1864, when on
the 28th September a great public meeting of working men of all
nations was held in St. Martin’s Hall, London. Professor Beesly
presided, and Karl Marx was present. The meeting resulted in the
appointment of a provisional committee to draw up the constitution
of the new association. This committee consisted of fifty
representatives of different nations, the English forming about half
of its number. At the first meeting of the committee the sum of three
pounds was collected, a humble beginning of the finances of an
association which was designed to shake the world.
The work of drafting the constitution was first of all undertaken by
Mazzini, but the ideas and methods of the Italian patriot were not
suited to the task of founding an international association of labour.
The statutes he drew up were adapted to the political conspiracy,
conducted by a strong central authority, in which he had spent his
life; he was strongly opposed to the antagonism of classes, and his
economic ideas were vague. Marx, on the other hand, was in entire
sympathy with the most advanced labour movement—had indeed
already done much to mould and direct it; to him, therefore, the
duty of drawing up a constitution was transferred. The inaugural
address and the statutes drawn up by him were unanimously
adopted by the committee.
In the inaugural address[4] three points were particularly
emphasised. First, Marx contended that, notwithstanding the
enormous development of industry and of national wealth since
1848, the misery of the masses had not diminished. Secondly, the
successful struggle for the ten-hours working-day meant the break-
down of the political economy of the middle classes, the competitive
operation of supply and demand requiring to be regulated by social
control. Thirdly, the productive association of a few daring ‘hands’
had proved that industry on a great scale, and with all the
appliances of modern science, could be carried on without the
existence of capitalist masters; and that wage-labour, like slave-
labour, was only a transitory form, destined to disappear before
associated labour, which gives to the workman a diligent hand, a
cheerful spirit, and a joyful heart.
The numbers of the workmen gave them the means of success, but
it could be realised only through union. It was the task of the
International to bring about such an effective union, and for this end
the workmen must take international politics into their own hands,
must watch the diplomacy of their Governments, and uphold the
simple rules of morality in the relations of private persons and
nations. ‘The struggle for such a policy forms part of the struggle for
the emancipation of the working class; proletarians of all lands,
unite!’
The preamble to the statutes contains implicitly the leading
principles of international socialism. The economic subjection of the
workmen to the appropriator of the instruments of labour—that is, of
the sources of life—is the cause of servitude in all its forms, of social
misery, of mental degradation and political dependence; the
economic emancipation of the working class is the great aim to
which every political movement must be subordinated; the
emancipation of the working class is neither a local nor a national,
but a social problem, to be solved only by the combined effort of the
most advanced nations.
‘For these reasons the International Association of Working Men has
been founded. It declares:
‘That all societies and individuals who adhere to it recognise truth,
justice, and morality as the rule of their conduct towards one
another, and to all men without distinction of colour, faith, or
nationality. No duties without rights; no rights without duties.’
Such are the leading ideas of the preamble; we have only to develop
them, and we have the programme of international socialism.
Whatever opinion we may hold of the truth and practicability of the
theories set forth in it, we must respect the lucid and masterly form
in which Marx has presented them. It is seldom in the history of the
world that talents and learning so remarkable have been placed at
the service of an agitation that was so wide and far-reaching.
The International Association was founded for the establishment of a
centre of union and of systematic co-operation between the
working-men societies, which follow the same aim—viz. the
protection, the progress and the complete emancipation of the
working class. It would be a mistake to regard its organisation as
one of excessive centralisation and dictatorial authority. It was to be
a means of union, a centre of information and initiative, in the
interests of labour; but the existing societies which should join it
were to retain their organisation intact.
A General Council, having its seat in London, was appointed. While
the president, treasurer, and general secretary were to be
Englishmen, each nation was to be represented in the Council by a
corresponding secretary. The General Council was to summon annual
congresses and exercise an effective control over the affairs of the
Association, but local societies were to have free play in all local
questions. As a further means of union, it was recommended that
the workmen of the various countries should be united in national
bodies, represented by national central organs, but no independent
local society was to be excluded from direct correspondence with the
General Council. It will be seen that the arrangements of the
Association were so made as to secure the efficiency of the central
directing power on the one hand, and on the other to allow local and
national associations a real freedom and abundant scope for
adapting themselves to the peculiar tasks imposed on them by their
local and national position.
As in founding, so in conducting the International, Marx took the
leading part. The proceedings of the various congresses might be
described as a discussion, elucidation, and filling up of the
programme sketched by him in the inaugural address and in the
statutes of the Association. Men representing the schools of
Proudhon (who died in 1865), of Blanqui, and of Bakunin also
exercised considerable influence; but the general tendency was in
accordance with the views of Marx.
It was intended that the first congress for finally arranging the
constitution of the Association should be held at Brussels in 1865,
but the Belgian Government forbade the meeting, and the Council
had to content itself with a conference in London. The first congress
was held at Geneva in September 1866, sixty delegates being
present. Here the statutes as drafted by Marx were adopted. Among
other resolutions it decided on an agitation in favour of the gradual
reduction of the working day to eight hours, and it recommended a
most comprehensive system of education, intellectual and technical,
which would raise the working people above the level of the higher
and middle classes. Socialistic principles were set forth only in the
most general terms. With regard to labour the International did not
seek to enunciate a doctrinaire system, but only to proclaim general
principles. They must aim at free co-operation, and for this end the
decisive power in the State must be transferred from capitalists and
landlords to the workers.
The proposal of the French delegates for the exclusion of the
intellectual proletariat from the Association led to an interesting
discussion. Was this proletariat to be reckoned among the workers?
Ambitious talkers and agitators belonging to this class had done
much mischief. On the other hand, their exclusion from socialistic
activity would have deprived the labourers of the services of most of
their greatest leaders, and the intellectual proletariat suffered from
the pressure of capital quite as much as any other class of workers.
The proposal for their exclusion was rejected.
The second congress, held at Lausanne in 1867, made considerable
progress in the formulating of the socialistic theories. It was resolved
that the means of transport and communication should become the
property of the State, in order to break the mighty monopoly of the
great companies, under which the subjection of labour does violence
to human worth and personal freedom. The congress encouraged
co-operative associations and efforts for the raising of wages, but
emphatically called attention to the danger lest the spread of such
associations should be found compatible with the existing system,
thus resulting in the formation of a fourth class, and of an entirely
miserable fifth. The social transformation can be radically and
definitely accomplished only by working on the whole of society in
thorough accordance with reciprocity and justice.
In the third congress, held at Brussels in September 1868, the
socialistic principles which had all along been implicitly contained in
the aims and utterances of the International received most explicit
statement. Ninety-eight delegates, representing England, France,
Germany, Belgium, Italy, Spain, and Switzerland, assembled at this
congress. It resolved that mines and forests and the land, as well as
all the means of transport and communication, should become the
common property of society or of the democratic State, and that
they should by the State be handed over to associations of workers,
who should utilise them under rational and equitable conditions
determined by society. It was further resolved that the producers
could gain possession of the machines only through co-operative
societies and the organisation of the mutual credit system, the latter
clause being a concession apparently to the followers of Proudhon.
After proposing a scheme for the better organising of strikes, the
congress returned to the question of education, particularly
emphasising the fact that an indispensable condition towards a
thorough system of scientific, professional, and productive
instruction was the reduction of the hours of labour.
The fundamental principle, ‘to labour the full product of labour,’ was
recognised in the following resolution: ‘Every society founded on
democratic principles repudiates all appropriation by capital, whether
in the form of rent, interest, profit, or in any other form or manner
whatsoever. Labour must have its full right and entire reward.’
In view of the struggle imminent between France and Germany, the
congress made an emphatic declaration, denouncing it as a civil war
in favour of Russia, and calling upon the workers to resist all war as
systematic murder. In case of war the congress recommended a
universal strike. It reckoned on the solidarity of the workers of all
lands for this strike of the peoples against war.
At the Congress of Basel in September 1869, little remained for the
International to accomplish in further defining the socialistic position.
The resolution for transforming land from private to collective
property was repeated. A proposal to abolish the right of inheritance
failed to obtain a majority, for while thirty-two delegates voted for
the abolition, twenty-three were against it, and seventeen declined
to vote.[5]
If we now turn from the congresses of the International to consider
the history of its influence in Europe, we shall see that its success
was very considerable. A conference of delegates of English Trade
Unions which met at Sheffield in 1866 most earnestly enjoined the
unions to join the International; and it repeatedly gave real help to
the English trade unionists by preventing the importation of cheap
labour from the Continent. It gained a substantial success in the
effectual support of the bronze-workers at Paris during their lock-out
in 1867. At the beginning of 1868 one hundred and twenty-two
working men’s societies of South Germany, assembled at
Nuremberg, declared their adhesion to the International. In 1870
Cameron announced himself as the representative of 800,000
American workmen who had adopted its principles.
It soon spread as far east as Poland and Hungary; it had affiliated
societies, with journals devoted to its cause, in every country of
Western Europe. The leading organs of the European press became
more than interested in its movements; the Times published four
leaders on the Brussels Congress. It was supposed to be concerned
in all the revolutionary movements and agitations of Europe, thus
gaining a world-historic notoriety as the rallying-point of social
overthrow and ruin. Its prestige, however, was always based more
on the vast possibilities of the cause it represented than on its actual
power. Its organisation was loose, its financial resources
insignificant; the Continental unionists joined it more in the hope of
borrowing than of contributing support.
In 1870 the International resolved to meet at the old hearth of the
revolutionary movement by holding its annual congress in Paris. This
plan was rendered abortive by the Franco-German war. The war,
however, helped to bring the principles of the Association more
prominently before the world. During the Austro-German struggle of
1866 the International had declared its emphatic condemnation of
war; and now the affiliated societies of France and Germany, as well
as the General Council at London, uttered a solemn protest against a
renewal of the scourge. Some of its German adherents likewise
incurred the wrath of the authorities by venturing to protest against
the annexation of Alsace and Lorraine.
All will agree that it is a happy omen for the future that the
democracy of labour as represented by the International was so
prompt and courageous in its denunciation of the evils of war. It
gives us ground to hope that as the influence of the democracy
prevails in the council of nations the passion for war may decline. On
this high theme no men have a better right to speak than the
workers, for they have in all ages borne the heaviest of the burden
of privation and suffering imposed on the world by the military spirit,
and have had the least share in the miserable glories which victory
may obtain.
The relation of the International to the rising of the Commune at
Paris in 1871 is often misunderstood. It is clear that the
International, as such, had no part either in originating or
conducting the Commune; some of the French members joined it,
but only on their individual responsibility. Its complicity after the
event is equally clear. After the fall of the Commune, Karl Marx, in
the name of the General Council, wrote a long and trenchant
manifesto commending it as substantially a government of the
working class, whose measures tended really to advance the
interests of the working class. ‘The Paris of the workers, with its
Commune, will ever be celebrated as the glorious herald of a new
society. Its martyrs will be enshrined in the great heart of the
working class. History has already nailed its destroyers on the pillory,
from which all the prayers of their priests are impotent to deliver
them.’[6]
The Commune was undoubtedly a rising for the autonomy of Paris,
supported chiefly by the lower classes. It was a protest against
excessive centralisation raised by the democracy of Paris, which has
always been far in advance of the provinces, and which found itself
in possession of arms after the siege of the city by the Germans. But
while it was prominently an assertion of local self-government, it was
also a revolt against the economic oppression of the moneyed
classes. Many of its measures were what we should call social-
radical.
In two important points, therefore, the communal rising at Paris had
a very close affinity with socialism. In the first place, it was a
revolutionary assertion of the Commune or local unit of self-
government as the cardinal and dominating principle of society over
against the State or central government. That is to say, the
Commune was a vindication of the political form which is necessary
for the development of socialism, the self-governing group of
workers. And in the second place, the Commune was a rising chiefly
of the proletariat, the class of which socialism claims to be the
special champion, which in Paris only partially saw the way of
deliverance, but was weary of oppression, and full of indignation
against the middle-class adventurers that had on the fall of the
Empire seized the central government of France.
It would, however, be a mistake to assume for the Commune a
clearness and comprehensiveness of aim which it did not really
possess. We should not be justified in saying that the Commune had
any definite consciousness of such an historical mission as has been
claimed for it. The fearful shock caused by the overwhelming events
of the Franco-German war had naturally led to wide-spread
confusion and uncertainty in the French mind; and those who
undertook to direct it, whether in Paris or elsewhere, had painfully to
grope their way towards the renovation of the country. At a time
when it could hardly be said that France had a regular government,
the Commune seized the opportunity to make a new political
departure. The true history of its doings will, we hope, be written
after passion and prejudice have sufficiently subsided to admit of it.
The story of its rise and fall was only one phase of a sad series of
troubles and disasters, which happily do not often overtake nations
in so terrible a form.
From this point the decline and fall of the Association must be dated.
The English trades unions, intent on more practical concerns at
home, never took a deep interest in its proceedings; the German
socialists were disunited among themselves, lacking in funds, and
hampered by the police.
It found its worst enemies perhaps in its own household. In 1869,
Bakunin, with a following of anarchists, had joined the International,
and from the first found themselves at variance with the majority led
by Marx. It can hardly be maintained that Marx favoured a very
strongly centralising authority, yet, as his views and methods were
naturally entirely repugnant to the anarchists, a breach was
inevitable.
The breach came at the Hague Congress in September 1872. Sixty-
five delegates were present, including Marx himself, who with his
followers, after animated discussion, expelled the anarchist party,
and then removed the seat of the General Council to New York. The
congress concluded with a meeting at Amsterdam, of which the chief
feature was a remarkable speech from Marx. ‘In the eighteenth
century,’ he said, ‘kings and potentates used to assemble at the
Hague to discuss the interests of their dynasties. At the same place
we resolved to hold the assize of labour’—a contrast which with
world-historic force did undoubtedly mark the march of time. ‘He
could not deny that there were countries, like America, England—
and, as far as he knew its institutions, Holland also—where the
workmen could attain their goal by peaceful means; but in most
European countries force must be the lever of revolution, and to

You might also like