Published Copyright © 2009 Skyway Software
Abstract
The most recent version of all Skyway Builder documentation can be
found online at www.skywayperspectives.org2.
2 http://www.skywayperspectives.org
1. Generating Spring applications using meta-data programming and
code generation ............. 1 2. Web Layer Recipes
..........................................................................................................
5
1. Creating the Controller using Spring MVC
....................................................................
5 2. Creating the Controller using Spring Web Flow
............................................................. 7 3.
Creating the Model for Spring MVC
..........................................................................
10 4. Creating the Model for Spring Web Flow
...................................................................
14 5. Creating Model Packages
........................................................................................
16 6. Creating Spring Components
....................................................................................
16 7. Creating the View for Spring MVC
............................................................................
17 8. Scaffolding a Spring MVC application from domain object
............................................. 18 9. Scaffolding
Spring Security
......................................................................................
19 10. Mapping URLs to Operations and Views
...................................................................
20 11. Creating Helper Methods using Operations
............................................................... 23
12. Reusing Operations in Different Contexts
.................................................................
23 13. Hiding the Implementation Technology
....................................................................
24 14. Implementing Post/Redirect/Get (PRG) Pattern
.......................................................... 25 15.
Restricting Direct Access to JSP Pages
......................................................................
26 16. Implementing Controller Methods using Actions and Steps
.......................................... 27 17. Blending Actions
with non-generated Java Code
........................................................ 31 18.
Blending Actions with non-generated Spring Beans
.................................................... 34 19.
Implementing an HTML Form in JSP using standard HTML elements
.............................. 36 20. Implementing an HTML Form in
JSP using Spring Form Tag Library ................................
38 21. Implementing an HTML Form in JSP using Skyway Tag Library
....................................... 40 22. Using Third-Party
Tag Libraries
...............................................................................
42 23. Accessing Request and Session Parameters
............................................................... 43
24. Defining the Scope of Components, Controllers and Services
........................................ 44 25. Managing User
Session Data
..................................................................................
45 26. Responding to User-Generated Events (Events and Commands)
.................................... 45 27. Using Absolute Paths
for Images, CSS and Javascript
................................................... 49 28. Using
CSS
...........................................................................................................
50 29. Using Javascript
...................................................................................................
51 30. Securing Applications - Authentication
.....................................................................
52 31. Securing Applications - Authorization
.......................................................................
55 32. Validating End-User Input on Server using Spring Validator
.......................................... 55 33. Implementing
Client-side Validation using Javascript
................................................... 59 34.
Implementing File Upload for Spring MVC
................................................................ 60
35. Implementing File Upload for Spring Web Flow
......................................................... 63 36.
Streaming binary content
......................................................................................
64
3. Service Layer Recipes
.....................................................................................................
67 1. Creating a Service or Business Facade
.......................................................................
67 2. Creating an Operation
............................................................................................
67 3. Implementing an Operation using Actions and Steps
.................................................... 69 4. Creating
a Contract-First JAX-WS Web service (SOAP)
................................................... 70 5.
Publishing a JAX-WS Web service (SOAP)
...................................................................
71 6. Publishing a AJAX service using DWR
........................................................................
72 7. Consuming a SOAP Web service
...............................................................................
74 8. Consuming a REST Web Service
...............................................................................
75 9. Using Java Code, Spring Beans and Groovy with Services
.............................................. 76 10. Using Groovy
in Actions
........................................................................................
77 11. Accessing Data using Groovy
..................................................................................
78
Skyway Builder 6.3 Recipes
v
4. Data Layer Recipes
.........................................................................................................
80 1. Creating a Domain Object / POJO / JavaBean
.............................................................. 80
2. Creating a Domain Model
.......................................................................................
82 3. Defining relationships
.............................................................................................
83 4. Creating a Data Access Object (DAO)
.........................................................................
85 5. Table and Field Mapping
.........................................................................................
86 6. Relationship Mapping
.............................................................................................
87 7. Implementing DAO using JPA
...................................................................................
88 8. Generating Domain Model from an existing database
................................................... 89 9.
Performing Basic CRUD Operations
...........................................................................
89 10. Performing Complex Queries using JPQL
..................................................................
91 11. Deciding between Defined versus Derived Data Models
.............................................. 92 12. Working with
Related Data
....................................................................................
93 13. Migrating to a Different DBMS
...............................................................................
93
5. Project Recipes
.............................................................................................................
95 1. Creating Project-level Variables and Constants
............................................................ 95 2.
Changing JPA Providers
...........................................................................................
95 3. Changing JTA Providers
...........................................................................................
96 4. JSP Aliases
............................................................................................................
96 5. Adding Spring Contexts
...........................................................................................
97 6. Creating Eclipse-based Skyway Projects
.....................................................................
98 7. Creating Maven-based Skyway Projects
.....................................................................
99 8. Setup an Eclipse Dynamic Web Project for Skyway Builder
........................................... 100 9. Manage project
classpath dependencies manually
..................................................... 101
6. Customizing Code Generation Recipes
.............................................................................
102 1. Customizing Code Generation Configuration
............................................................. 102
2. Customizing Code Generation Templates
..................................................................
103 3. Extending the Code Generation Framework
..............................................................
104
vi
List of Figures 1.1. Spring DSL Model
.........................................................................................................
2 2.1. Model - View - Controller
...............................................................................................
5 2.2. Controller (MVC)
..........................................................................................................
6 2.3. Controller (MVC)
..........................................................................................................
9 2.4. Spring Web Flow - Sample Diagram
................................................................................
10 2.5. Model (MVC)
..............................................................................................................
11 2.6. Spring MVC Model (Example 1) - Operation Inputs/Outputs
................................................ 12 2.7. Spring MVC
Model (Example 2) - Operation Inputs/Outputs
................................................ 13 2.8. Model
(MVC)
..............................................................................................................
15 2.9. Spring Web Flow Model (Example 1) - Model Config
.......................................................... 15 2.10.
View (MVC)
..............................................................................................................
17 2.11. Action Editor
............................................................................................................
28 2.12. Step Palette
..............................................................................................................
29 2.13. Creating an instance of MyJavaClass using Variables
........................................................ 33 2.14.
Web Events and Commands
........................................................................................
46 2.15. Events and Commands - Properties Panel
......................................................................
47 2.16. Events and Commands - 1 Event
..................................................................................
48 2.17. Events and Commands - 2 Events
.................................................................................
48 2.18. Security Settings using Spring Security
..........................................................................
53 2.19. Security Settings - Configured Views
.............................................................................
54 2.20. Security Settings - Security Information Source
............................................................... 54
2.21. Validation
.................................................................................................................
58 2.22. Event and Commands
................................................................................................
59 3.1. DWR Service - Index Page
.............................................................................................
73 3.2. DWR Service - Service Details Page
................................................................................
74 3.3. Accessing Variables using Groovy
...................................................................................
78 4.1. Creating a domain object using Domain Object Editor
........................................................ 81 4.2.
Book domain object with relationship to Authors
.............................................................. 84
4.3. Author domain object with reverse relationship to Book
.................................................... 85 4.4.
Persistence Mapping
....................................................................................................
87 4.5. Relationship Mapping
..................................................................................................
88 4.6. CRUD - Modify Data Access Object Examples
...................................................................
90 5.1. JSP Alias
....................................................................................................................
97 5.2. Adding Spring Contexts to Project
..................................................................................
98
vii
List of Tables 1.1. Spring/Java, Spring DSL, and UML Stereotype
Cross Reference .............................................. 3
2.1. URL Mapping Parameters
.............................................................................................
21 2.2. Binding HTML Form Controls
.........................................................................................
37 2.3. Event Descriptions
.......................................................................................................
46 2.4. Skyway Commands
......................................................................................................
46 2.5. File Upload Suffixes
.....................................................................................................
61 2.6. URL parameters for streamedBinaryContentView
.............................................................. 65
3.1. Web Service WSDL to Skyway Mappings
.........................................................................
70 4.1. Skyway Basic Data Types
..............................................................................................
80 4.2. Relationship Types
.......................................................................................................
83 4.3. JPA Query Examples
....................................................................................................
92 4.4. Comparison of Native and External Data Models
.............................................................. 92
4.5. Scenarios for using external data models
.........................................................................
93
viii
List of Examples 2.1. Annotated Spring Controller (Generated)
..........................................................................
7 2.2. Spring MVC Model (Example 1) - Operation Inputs/Outputs
(Generated) ............................... 13 2.3. Spring MVC
Model (Example 2) - Operation Inputs/Outputs (Generated)
............................... 14 2.4. URL Mapping - Examples
..............................................................................................
22 2.5. URL Mapping - Reusing Actions
.....................................................................................
24 2.6. URL Mapping - Hiding Implementation Technology
............................................................ 25
2.7. URL Mapping - Post/Redirect/Get (PRG)
..........................................................................
26 2.8. Action (Generated)
......................................................................................................
30 2.9. Blending Java Code with Actions - MyJavaClass.java
.......................................................... 32 2.10.
Invoke Java Step - Variable Invocation (Generated Code)
................................................... 33 2.11. Invoke
Java Step - Instance Invocation (Generated Code)
.................................................. 33 2.12. Invoke
Java Step - Static Invocation (Generated Code)
...................................................... 34 2.13.
Blending Spring Beans with Actions - MyBean.java
.......................................................... 35 2.14.
Spring Context File - mycontext.xml
..............................................................................
35 2.15. Invoke Spring Step - Static Invocation (Generated Code)
................................................... 36 2.16. Invoke
Spring Step - Dynamic Invocation (Generated Code)
............................................... 36 2.17. HTML Form
using Standard HTML Controls
....................................................................
37 2.18. JSP Directive for using Spring Form Tag Library
............................................................... 38
2.19. HTML Form using Spring Form Tag Library
.....................................................................
39 2.20. HTML Form using <spring:bind> tag
..............................................................................
39 2.21. JSP Directive to include Skyway JSP Tag Library
............................................................... 40
2.22. HTML Form using Skyway Builder Tag Library
.................................................................
42 2.23. JSP Directive for using Third-Party Tag Library
.................................................................
43 2.24. Using Third-Party Tags
................................................................................................
43 2.25. Invoke Java (inline) - accessing Request Parameters
......................................................... 44 2.26.
Model Scope (Generated)
...........................................................................................
44 2.27. JSP Directive for using Skyway Tab Library
......................................................................
46 2.28. Event and Command - JSP Fragment
.............................................................................
48 2.29. JSP Fragment using pageContext.request.contextPath
variable for absolute pathing ............... 49 2.30. HTML
fragment with absolute pathing - deployed to http://localhost/myapp
........................ 49 2.31. HTML fragment with absolute
pathing - deployed to http://www.myapp.com .......................
50 2.32. Linking to external CSS files
.........................................................................................
51 2.33. Inline javascript
.........................................................................................................
51 2.34. Linking to javascript libraries
.......................................................................................
52 2.35. Validation Class
.........................................................................................................
57 2.36. Using errors tag of the Spring Form Tag Library (edit.jsp)
.................................................. 58 2.37. Sample
client-side validation using javascript
..................................................................
59 2.38. File Upload - HTML
....................................................................................................
61 2.39. File Upload - Upload Web Control (Skyway TagLib)
.......................................................... 62 2.40.
File Upload - HTML
....................................................................................................
63 2.41. Spring Web Flow Configuration
....................................................................................
64 2.42. Accessing MultipartFile
...............................................................................................
64 2.43. Spring Context file -
projectName-generated-web-context.xml
........................................... 65 2.44. Image
Streaming Example - output only
........................................................................
65 2.45. Image Streaming Example - with inputs
.........................................................................
66 2.46. Document Streaming Example - with inputs
...................................................................
66 3.1. Sample java code invoking REST services
.........................................................................
76 3.2. Sample Groovy code invoking REST services
.....................................................................
76 3.3. Using Groovy Code using Invoke Groovy Step
...................................................................
77 3.4. Accessing data using Groovy
.........................................................................................
79 4.1. Domain Object - POJO (Generated)
................................................................................
82
Skyway Builder 6.3 Recipes
ix
4.2. Domain Object - Primary Key Class (Generated)
................................................................ 82
4.3. Code generated for domain object relationships
...............................................................
85
1
PROBLEM
The Spring Framework is one of the most popular JAVA frameworks.
While the Spring Framework and associated Spring technologes reduce
complexity, developing Spring applications requires familiarity
with Spring development concepts and configuration.
SOLUTION
The solution is to provide an abstraction layer on top of Spring
that generates Spring-based artifacts and configuration files, and
additionaly use modelling to implement parts of your solution.
Skyway Builder is an Eclipse-based, code generation tool for
accelerating the development of Spring applications, specifically
Rich Internet Applications (RIAs) and Web Services. Spring provides
a framework that abstracts the complexities of enterprise software,
and Skyway Builder adds an even higher layer of abstraction (a
Spring DSL) to provide a generation framework for Spring.
HOW IT WORKS
The abstraction is accomplished by employing a metadata model to
capture the specifications from the developer, which in turn drives
the code generation process. For defining the specifications,
Skyway Builder provides Eclipse-based tooling which includes the
use of editors, wizards, and modeling artifacts. The Skyway
Generation Framework then converts the metadata into generated code
and Spring application artifacts.
Skyway Builder implements a DSL for Spring that describes all the
major components of a Spring application. This is the metadata
model:
Spring Generation
Application development using Skyway Builder is accomplished by
using (assembling and configuring) Spring DSL artifacts:
Within Skyway Builder, there are graphical (and abstract)
representations of application components. These components have
direct correlations to Java, Spring, JPA, and JEE artifacts.
Summary of Spring DSL Artifacts
• Projects are the top level artifact within the developer's
workspace. All other Spring DSL artifacts must be made within a
Skyway modeling project.
• A Model Package is a Spring DSL artifact for namespacing and
grouping related Spring DSL components. A model package can contain
any top-level Spring DSL elements, including other model packages.
Model packages correlate directly to java packages (and UML
packages), and Spring DSL artifacts created in a model package will
be generated into a matching Java package.
• A Domain Object is a Spring DSL artifact that defines the domain
model of the application. By default a domain object is generated
into a plain old java object (POJO). If a domain object is
associated with a data access object, then the domain object is
annotated as an @Entity (JPA) annotated class, and it's associated
with a primary key class (@IdClass). Fields can be added to domain
objects by using the basic data types, and a domain object can have
relationships to other domain objects.
• A Data Access Object (DAO) is a Spring DSL artifact used to
separate data access logic from application logic. A DAO manages
the persistence of domain objects, and it is generated into
@Repository annotated Spring components, a specialized stereotype
for data access layer components. A DAO can also contain predefined
queries called Named Queries.
• A Named Query is a Spring DSL artifact creating predefined
queries for the data access objects (DAOs). Named queries are
defined using either SQL or JPQL (Java Persistence Query Language),
and Named
Spring Generation
Queries are generated into @NamedQueries and @NamedQuery
annotations in Spring @Repository components.
• A Service is a Spring DSL artifact that defines a service layer
component, and it gets generated into a @Service annotated Spring
component, a specialized stereotype for service layer components. A
Service contains a set of Operations which are generated into
Service methods.
• A Web Controller is a Spring DSL artifact that defines the web
layer of an application using Spring MVC. Web Controllers get
generated into a @Controller annotated Spring component, a
specialized stereotype for web layer components. A Web Controller
contains a set of Operations which are generated into methods for
handling web requests.
• An Operation is a Spring DSL artifact that defines methods for
both Services and Controllers. Operations represent application
logic, and they use inputs and outputs for exchanging data.
Operations are generated directly in the respective Service and
Controller classes, and they are generated slightly differently to
account for the different implementations needed for the Spring
stereotypes.
• An Actions is a Spring DSL artifact for implementing operations
using model-driven development. They are used to implement service
and controller operations in Java using drag-n-drop steps that are
sequenced together into functionality.
• A Component is a Spring DSL artifact that defines a generic
container for data. A component gets generated into an @Component
annotated Spring component, a generic stereotype for Spring managed
components with configurable scope. Components are typically used
as data transfer objects (DTO) and form backing objects.
• A Flow is used to implement the web layer of an application using
Spring Web Flow.
• Java Server Pages (JSP) are used to implement the Presentation
layer of an applicaiton. JSPs are used for both Spring MVC and
Spring Web Flow applications.
• An Exception is a Spring DSL artifact that defines custom
exceptions. Exceptions are generated into exception classes in
Java.
The follow table shows the relationship between the Spring UML
stereotypes, Spring DSL, Spring/JPA components.
Table 1.1. Spring/Java, Spring DSL, and UML Stereotype Cross
Reference
Web Layer Service Layer Data Layer
Spring Stereotypes, Annotations and Interfaces
@Controller
@Component
@RequestMapping
@RequestParm
@ModelAttribute
@WebMethod (JAX-WS)
@WebParm (JAX-WS)
Chapter 2. Web Layer Recipes
The web layer is also referred to as the UI layer. The web layer is
primarily concerned with presenting the user interface and the
behavior of the application (handling user interactions/events).
While the web layer can also contain logic, core application logic
is usually located in the services layer.
Figure 2.1. Model - View - Controller
The Spring DSL artifacts for implementing the web layer of a Spring
MVC application are the Controller, Operation, Component, Action,
Steps and JSP pages. The Spring DSL artifacts for implementing the
web layer of a Spring Web Flow application are the Flows and JSP
pages. These artifacts will be described in detail in a following
chapter.
1. Creating the Controller using Spring MVC PROBLEM
In the context of a Spring MVC application, the controller is
responsible for receiving requests from a web client (typically
from end-user generated events) and invoking a request handler
called an Operation, which orchestrates all the server logic
necessary for processing the request. Spring MVC supports the
grouping of Operations related to an application task into a
Controller. In order to gain the benefits of Spring MVC, a
developer needs to have a pretty in-depth knowledge of Spring MVC.
Creating a Spring Controller is tedious, and identifying the
relationship between Spring Controllers, Model and Views is
difficult because there's no easy way to identify them without
digging through source code or code configuration files.
SOLUTION
The Spring DSL lets you define your controllers using meta-data. To
create a controller a developer must only define a controller and
provide it a common name, and Skyway Builder will generate all the
supporting code and Spring configurations needed. Every operation
that is added to the controller will result in a handler method
being generated into the Spring controller.
Web Layer Recipes
HOW IT WORKS
Controllers are used along with the Operations, Models and Views to
implement an application using Spring MVC. The Web Controller has
essentially two functions: group related Operations and map URLs to
Operations, which orchestrate the task and support the user events
associated with the task.
Figure 2.2. Controller (MVC)
Steps for creating a Controller:
1. Right click the on a Model Package, and select
New-->Controller
2. From the New Controller Wizard, enter a common name for the
controller. The common name is for referencing the controller from
other artifacts. Click Finish
The following figures shows an abbreviated version of the code that
is generated from a Controller artifact. To see the fully generated
code, see the PAM tutorial.
Web Layer Recipes
package com.pam.web;
import javax.annotation.Resource;
// Imports statements for generated classes from referenced data
types, services, and DAOs ...full list omitted for brevity
/** * Request dispatcher for the
<code>AppraisalEntryController</code> controller. * *
@generated */ @Scope("singleton")
@Controller("AppraisalEntryController") @Transactional(isolation =
Isolation.DEFAULT, propagation = Propagation.REQUIRED,
noRollbackForClassName = "java.lang.Exception",
rollbackForClassName =
"org.skyway.execution.exception.RollbackException") public class
BlogController {
/** * Wire in the project level variables that can span both
controllers and services. * * @generated */ @Resource(name =
"SkywayBlog") private SkywayBlog project;
// Annotation-based code to wire in ModelAttributes ...
// Controller Variables, including Getters and Setters ...
// Initialize Bindings ...
2. Creating the Controller using Spring Web Flow PROBLEM
Web Layer Recipes
8
An alternative to Spring MVC is Spring Web Flow, a project from
Spring for simplifying the development of web applications. While
Spring Web Flow is compatible with Spring MVC, Spring Web Flow uses
flows instead of controllers for implementing the web layer of an
application. Since Spring Web Flow has functionality for managing
application state, it is best suited for implementing the
functionality where the activity being performed by the end-user
spans multiple page requests.
For example, an online commerce application typically has checkout
functionality which spans multiple pages. One page may require that
you confirm the items in your order, with the option to add/remove
items and change quantities. The next page may solicit shipping
information, including picking shipping options and providing a
shipping address. The next page is used for entering billing info.
The bottom line is that the checkout process is a unit of work, and
there are many intermediate steps to complete the checkout
process.
With Spring Web Flow the group of related steps to accomplish a
task are referred to as a Flow. While this functionality can be
implemented with Spring MVC, Spring Web Flow has features that make
it considerably easier. However in order to gain the benefits of
Spring Web Flow, a developer needs to have a pretty in-depth
knowledge of Spring and Spring Web Flow, and Spring Web Flow adds
additional configuration requirements to your web application.
While authoring the flow of an application using XML is elegant,
implementing flows using XML can be difficult and tedious because
it’s hard to visualize the application flow from the xml.
SOLUTION
Skyway Builder reduces the complexity of adding Spring Web Flow
support by automatically bootstrapping the project for you. The
moment you add the first flow to your project, Skyway Builder will
add the necessary Spring configuration and libraries. That by
itself is a significant time saver, but Skyway Builder goes one
step further in regards to Spring Web Flow
In addition to configuring your application, Skyway builder also
provides a custom Spring Web Flow editor for authoring flows. The
flow editor is very similar to Skyway Builder’s action editor,
except that you implement flows instead of operations.
You start with an empty canvas which represents a single flow, and
you drop different web flow states (i.e. view, decision, action,
subflow and stop) onto the canvas. State transitions are defined by
drawing lines between the states and specifying the event
associated with the transition. Actions can be added to flows and
states.
HOW IT WORKS
Flows are a group of related steps for accomplishing a task in an
application. Some of the benefits of using Spring Web Flow
are
1. XML-based flow definitions - The flow of the application is
defined in XML. No custom Java is needed to implement a flow
2. Expression language support - An expression language let’s you
leverage logic from the other layers of the web application. Logic
that a developer would typically put into a controller, that isn’t
handled by Spring Web Flow, can beexpressed in XML using the
expression language
3. State management - Variables can be scoped (many scopes are
supported), and Spring Web Flow will automatically handle the
cleanup of those variables when they are out-of-scope.
4. Modularization of flow logic - Flows can be re-used from other
flows.
A Flow is responsible for orchestrating the task (steps) and
supporting the user events associated with the task. Instead of the
MVC-based approach of creating a controller and multiple operations
for
Web Layer Recipes
9
implementing a conversation, with Spring Web Flow you define a flow
with states and expressions. Instead of the MVC-based approach of
defining URL mappings, with Spring Web Flow you define events.
Spring Web Flow also let's you easily separate your logic for
handling a user event (on event id) from the pre- load logic (on
entry) for a particular state.
Figure 2.3. Controller (MVC)
Steps for creating a Flow:
1. Right click the on a Model Package, and select
New-->Flow
2. From the New Web Flow Wizard, enter a common name for the flow.
The common name is for referencing the controller from other
artifacts. Click Next
3. From the Create Webflow Domain Model panel, specify the name and
location of the domain model. As you make changes to the web flow
diagram, the flow domain model will be updated with Spring Web Flow
specific content. The domain model is what's deployed with your
application and interpretted by the Spring Web Flow framework. The
domain model must be located in a folder withing WEB-INF. Click
Finish.
4. Implement the flow using the flow diagram,
The following figures shows a sample flow diagram.
Web Layer Recipes
RELATED RECIPES
3. Creating the View for Spring MVC
3. Creating the Model for Spring MVC PROBLEM
In the context of Spring MVC, a model generally represents the data
that will be passed to and from an operation (defined in a web
controller) and the view. Spring MVC supports various options and
patterns for defining the data that can be passed back and forth,
and a typical Spring MVC application may use a combination of these
options. The flexibility of Spring MVC to have fine-grained control
for defining models is very powerfull, however along with the
flexibility comes considerable variability and complexity in the
implemenation using Spring.
SOLUTION
Through the use of code generation in Skyway Builder, the
complexity of Spring models can be abstracted to makes things
simpler for the developer.
A controller method in Spring can support zero-to-many input
parameters, and the principal mechanisms in Spring for specifying
input parameters are the @RequestParam and the @ModelAttribute
annotations. The @RequestParam annotation is used to bind
individual request parameters, like string and integers, to method
parameters in the controller. The @ModelAttribute annotation is
used to bind complex objects, like domain objects, data transfer
objects and/or form backing objects, to method parameters in a
controller.
In Skyway Builder operations are used to define request handlers
(controller methods), and operation parameters are simply
configured using Input variables. Since these variables are
available to be processed by the operation, the developer using
Skyway Builder doesn't really need to be concerned with the details
of Spring.
Web Layer Recipes
11
Nevertheless here's an overview of what gets generated for input
variables added to an operation::
• the input variable is emitted as a annotated method
parameter
• the annotaton is determined by the variable type
• primitive variables will be annotated with @RequestParam
• complex variables will be annotated with @ModelAttribute
• the annotation name is derived from the variable name
A controller method in Spring can also output model data, and the
principal mechanism in Spring for specifying output model data is
the ModelAndView object. In the event that there isn't any data to
be returned by the method, the controller method can simply return
a String that represents the view that should be rendered. If the
controller method does return data, then a ModalAndView object
needs to be instantiated and each output variable is added as a
model attribute to the ModelAndView object.
In Skyway Builder you simply need to define output parameters on
the Operation, and Skyway Builder will handle all the details
regarding how the model data should be emitted.
Here's an overview of what occurs regarding output variables added
to an operation:
• If you don't have any output variables, the method return type
will be String, and the last line of the operation will return the
corresponding view that should be rendered (as defined in URL
mappings).
• If you have one or more output variables, the method will return
a ModelAndView object, and each output variable will added to the
ModelView. The output variable name will be used as the
ModelAttribute name, and the ModalAndView will be set with the view
that should rendered (as defined in URL mappings).
HOW IT WORKS
Once again a model generally refers to the data that is pased to
and from a controller method (Skyway Operation).
Figure 2.5. Model (MVC)
Controller methods parameters are defined using Operation Input and
Variables.
Steps for defining operation input and output variables:
1. From the Skyway Navigator, double-click on the Operation to
configure, and switch to the Inputs/ Outputs tab.
2. Add input variables by clicking on the Add... button in the
Inputs block, and specify the output variable name. Assign
(assignment) the variable name to either an input variable or
operation variable. The type and collection parameters will be
automatically configured based on the selected assignment
variable.
Let's examine a few scenarios to see exactly what gets generated
based on the configuration of the operation inputs and
outputs.
Example 1
In this first example, an operation was defined with two input
variables and no output variables.
Figure 2.6. Spring MVC Model (Example 1) - Operation
Inputs/Outputs
The following figures shows an abbreviated version of the full
controlller method that is generated from the operation
configuration.
Web Layer Recipes
Example 2.2. Spring MVC Model (Example 1) - Operation
Inputs/Outputs (Generated)
@RequestMapping(value =
"/OrderCheckoutController/AddBillingAddress.action")
@ModelAttribute("billingAddress") Address billingAddress ) throws
java.lang.Exception {
return "/billingoverview.jsp"; }
The operation didn't have any defined output variables. Therefore
the return type for the controller method is String. The orderId
input variable is of type Text. Since Text is a primitive data
type, the method parameter corresponding to this variable is
annotated with the @RequestParam annotation. The variable name
(orderID) is used as the name. The billingAddress input variable is
of type Address. Since Address is a complex type, the method
parameter corresponding to this variable is annotated with the
@ModelAttribute annotation. The variable name (billingAddress) is
used as the name. The output of the controller method is set to the
path of the view that should be used for rendering the
results.
Example 2
In this second example, an operation was defined with one input
variable and an output variable. The output variable is mapped to
an operation variable (shippingOptions) that is defined in the
Variables tab (not shown).
Figure 2.7. Spring MVC Model (Example 2) - Operation
Inputs/Outputs
The following figures shows an abbreviated version of the full
controlller method that is generated from the operation
configuration.
Web Layer Recipes
Example 2.3. Spring MVC Model (Example 2) - Operation
Inputs/Outputs (Generated) @RequestMapping(value =
"/OrderCheckoutController/LoadShippingOptions.action")
public ModelAndView loadShippingOptions(@RequestParam("zipcode")
String zipcode ) throws java.lang.Exception {
ModelAndView mav = new ModelAndView(); Set<ShippingOption>
shippingOptions = null;
//method implementation either hand-coded or generated from action
model
mav.addObject("shipoptions", shippingOptions);
mav.setViewName("/success.jsp"); return mav; }
The operation has atleast one output variable. Therefore the return
type for the controller method is ModelAndView. The zipcode input
variable is of type Text. Since Text is a primitive data type, the
method parameter corresponding to this variable is annotated with
the @RequestParam annotation. The variable name (zipcode) is used
as the name. Since the return type of the controller method is a
ModelAndView object, a ModelAndView object is instantiated. The
operation output variables are added to the ModelAndView object.
The variable name is used as the model attribute name, and the
object (shippingOptions) that was assigned to the output is used as
the model. The view is set on the ModelAndView object to the path
of the view that should be used for rendering the results.
Data Transfer Objects vs. Form Backing Objects vs. Domain
Objects
In MVC the model is the contract between the View and the
Controller. While you can use basic data types, more often than not
you'll want to use complex objects for the model. There are several
options available to the developer. You can use your domain objects
for the model, but this only works if there's a very close
correlation between your domain object and your views. If that's
not the case, then you can create a data transfer object that is
not tied to your domain model, and the request handlers in the
controller would be responsible for mapping data between the data
transfer object and the domain model. A data transfer object is a
general term for a data object that isn't part of the domain model
and isn't intended to be persisted. A form backing object is a
specific reference to data object that is used to capture input
from an end-user, and it can be implemented using a domain object
or a data transfer object.
You can create domain objects and data transfer objects in the
Spring DSL using Domain Objects and Component artifacts,
respectively. If you prefer, you can also use a custom Java
class.
RELATED RECIPES
4. Creating the Model for Spring Web Flow PROBLEM
In the context of Spring Web Flow, a model serves the same function
as a model in Spring MVC. The model generally represents the data
that will be passed to and from a View State (instead of an
Operation) and the view. Spring Web Flow supports various options
and patterns for defining the data that can be passed
Web Layer Recipes
15
back and forth, and a typical Spring Web Flow application may use a
combination of these options. The flexibility of Spring Web Flow to
have fine-grained control for defining models is very powerfull,
however the definition of the models can be difficult because the
models are defined and used in xml (flow).
SOLUTION
Through the use of the Skyway Web Flow editor, defining models is
much simpler because the flow is represented in a diagram. This is
very effective for defining models and to understand the use of
models in a Spring web Flow implementation.
HOW IT WORKS
Once again a model generally refers to the data that is pased to
and from a web flow View State.
Figure 2.8. Model (MVC)
Steps for defining a Model for a Spring Web Flow view state:
1. In a flow diagram, identify a View State for configuring a
model.
2. For the model parameter, specify the variable that should be
used for the model. The model will be the commandObject that can be
used in the JSP to display data to and/or solicit data from the
end-user.
Figure 2.9. Spring Web Flow Model (Example 1) - Model Config
RELATED RECIPES
2. Creating the View for Spring MVC
5. Creating Model Packages PROBLEM
In Java application development it is common to use packages for
organizing and namespacing Java resources according to their
functionality. The Spring DSL abstracts the development of many
different types of Java resources, but there still needs to be a
mechanism for the developer to group related Spring DSL artifacts.
Furthermore the developer often wants to control the package names
that are ultimately emitted in the generated code.
SOLUTION
A Model Package is a Spring DSL artifact for namespacing and
grouping related Spring DSL components. A model package can contain
any top-level Spring DSL elements, including other model packages.
Model packages correlate directly to java packages (and UML
packages), and Spring DSL artifacts created in a model package will
be generated into a matching Java package.
HOW IT WORKS
Steps for creating a Model Package:
1. Right-click on the Spring DSL folder of a Skyway Project, and
select New --> Model Package
2. For the New Model Package window, specify the name of the model
package. The name can be partially filled-in by selecting a
pre-existing model package in the project.
6. Creating Spring Components PROBLEM
In the course of developing web applications there is often a need
to create data objects that aren't a part of the domain model. The
data objects are referred to as data transfer objects (DTO), and
they can be used throughout the application for passing data. When
there isn't a close correlation between the domain objects and the
views of the application, DTOs can be used for creating form
backing objects.
SOLUTION
A Component is a Spring DSL artifact that defines a generic
container for data. A component gets generated into an @Component
annotated Spring component, a generic stereotype for Spring managed
components with configurable scope. Components are typically used
as data transfer objects (DTO) and form backing objects.
HOW IT WORKS
Steps for creating a Component:
1. Right click the on a Model Package, and select
New-->Component
2. From the New Component Wizard, enter a common name for the
component. The common name is for referencing the component from
other artifacts. Click Finish
Web Layer Recipes
7. Creating the View for Spring MVC PROBLEM
In the context of Spring MVC, a view generates the user interface
based on model data. There a variety of JAVA-based technologies for
implementing views, but Java ServerPages (JSP) are the predominant
technology for defining Views. JSPs are designed to be implemented
in a manner that is optimized for web designers. An abstraction
layer like Skyway Builder must allow for the continued use of JSP
pages for implementing views.
SOLUTION
Skyway Builder lets you define your user interface using any view
technology, including Java ServerPages (JSP). This allows
developers very fine grained control of how the user interface
renders in modern web browsers, including desktop and mobile
browsers. The UI developer can leverage JSP tag libraries,
including Java Standard Tag Library (JSTL).
HOW IT WORKS
Steps for creating a JSP:
1. Right click on WebContent folder, and select New-->JSP. This
will open the New JavaServer Page Wizard.
2. From the wizard specify the filename for jsp (i.e. index.jsp)
and click the Next button.
3. Select Skyway JSP File (html) as the template, and click the
Finish button.
Note
If a JSP page is specified directly in the WebContent folder, it
will be accessible as a web resource and through any defined URL
Mappings. A best practice is to put the JSP pages in the WEB-INF
folder so that the JSP is only accessible through a URL
mapping.
RELATED RECIPES
2. Hiding the Implementation Technology
3. Implementing Post/Redirect/Get (PRG) Pattern
4. Implementing an HTML Form in JSP using standard HTML
elements
5. Implementing an HTML Form in JSP using Spring Form Tag
Library
6. Implementing an HTML Form in JSP using Skyway Tag Library
7. Using Third-Party Tag Libraries
8. Scaffolding a Spring MVC application from domain object
PROBLEM
There are several layers to a Spring MVC application, and there are
many Spring, JPA, and Java artifacts needed to implement those
layers. The Skyway Builder Spring DSL simplifies the development of
these artifacts through the use of code generation, but there is
also an opportunity to generate full applications. Other
development platforms, including RAILS and GRAILS, have popularized
this approach to application development. Scaffolding consists of
generating full applications by applying standard application
patterns from a minimal set of inputs provided by the developer.
Whether these scaffolded applications are used as-is or as the
starting point for additional developer customization, scaffolding
is very effective at jump-starting application development.
SOLUTION
Spring MVC scaffolding consists of generating a full Spring MVC
application based on the CRUD application pattern. By only defining
the domain model, which can consist of one or more related domain
objects, the Spring MVC scaffolding engine will create all the web,
service, and data layer components for managing the domain objects,
including create, read, update and delete.
Starting with a domain object, here's what gets created by Spring
MVC scaffolding:
Spring MVC Scaffolding
1. a model package for the data access object layer
2. a data access object (DAO)
3. a set of named queries (JPQL) for the domain object
4. a model package for the service layer
5. a Service with CRUD operations
6. a model package for the controller layer
7. a Controller with fully implemented CRUD operations
8. Junits for controllers and
9. layout managed user interface using Sitemesh
Web Layer Recipes
10.CRUD JSP pages using Spring Form tag library and JSTL
11.client-side validation implemented Spring JS with DOJO
12.integration with Spring Security, including a default DB
implementation of users and authorities
Scaffolding Note
While the Spring MVC scaffolding generates a fully wired and
ready-to-run Spring MVC application based on the CRUD application
pattern, the Spring MVC scaffolding accomplishes this by generating
the appropriate Spring DSL artifacts. This enables an application
developer to continue to refine the scaffolded application, if
needed, using the Spring DSL abstraction layer.
HOW IT WORKS
Before scaffolding an application the developer must create or
import the domain model using the Spring DSL, and the domain model
must be contained within a Model Pacakge.
Here are the steps for using the Spring MVC scaffolding:
Steps for scaffolding a domain object:
1. Right-click on a domain object, and select Scaffolding -->
Generate CRUD
Scaffolding Note
The Spring MVC scaffolding will automatically create the model
packages for the other layers of the application, and the Spring
DSL artifacts will be generated into the appropriate model
packages. If the model package for the domain object ends with
".domain", then the Spring DSL will create ".dao", ".service" and
".web" model packages at the same level as the ".domain" model
package. This is a fairly typical convention for package names in a
Spring MVC application, but the developer can of course move the
artifacts to other packages if needed.
RELATED RECIPES
9. Scaffolding Spring Security PROBLEM
Security is an important part of a web application, and Spring
Security provides a set of security services that integrate with
Spring-based applications. Spring Security offers a lot of options,
but it can be difficult to quickly get a project bootstrapped with
Spring Security.
SOLUTION
Skyway Builder Standard Edition1 has a development accelerator for
bootstrapping a project with Spring Security.
HOW IT WORKS
Here are the steps for using the Spring Security scaffolding:
Steps for scaffolding Spring Security:
1. Right-click on the Spring DSL project, and select Scaffolding
--> Scaffold Spring Security
2. Select a model package to store the Spring Security
artifacts
Skyway Builder will configure the application for Spring Security,
which includes:
Spring Security scaffolding:
1. Create a User domain object and UserDAO for storing user
credentials. These artifacts can be further customized using Spring
DSL if needed.
2. Create a Authorities domain object and AuthoritiesDAO for
storing authorization data. These artifacts can be further
customized using Spring DSL if needed.
3. Enable Spring security in the Security Settings section of the
Enterprise Configuration tab.
4. Configure Secured URLs in the Security Settings section of the
Enterprise Configuration tab.
5. Configure Secured Services in the Security Settings section of
the Enterprise Configuration tab.
6. Configure Secured Data Access Objects in the Security Settings
section of the Enterprise Configuration tab.
7. Configure Security Views in the Security Settings section of the
Enterprise Configuration tab, including login, login success, login
failure, logout success, and access denied views.
8. Configure Security Information Sources in the Security Settings
section of the Enterprise Configuration tab, including database
configuration with queries for AuthoritiesDAO and UserDAO.
9. Create dedicated Spring Security context files:
project-security-context.xml, generated-project-
security-context.xml
While Skyway Builder can fully setup Spring Security in a project
with a few seconds, the configuration is setup to enable further
customization using Spring DSL. See Securing Applications -
Authentication and Securing Applications - Authorization.
RELATED RECIPES
10. Mapping URLs to Operations and Views PROBLEM
In the context of Spring MVC there are request handlers, called
Operations in the Spring DSL, that are implemented in the
controller for defining the behavior of the application and
handling user-generated events. There needs to be a strategy for a
Controller to identify (a) which Operations are available to web
clients, (b) what URL will be used to address the Operation, and
(c) which View should be used to render the response.
SOLUTION
In addition to serving as the container for Operations, a
Controller defines URL Mappings, which associate URLs to Operations
and Views. URL Mappings are the mechanism for specifying which
Operations are
Web Layer Recipes
21
going to be accessible to web clients. This is accomplished by
defining one or more URL Mappings in the Controller.
HOW IT WORKS
A URL Mapping is responsible for defining the url(s) that will
trigger an action. When the defined URL is requested from a web
control, javascript or web client, the operation associated with
(mapped to) the url will handle the request. The URL mapping will
also specify the jsp that will render the response to the request.
Every request will have a response, and the URL mapping specifies
both the operation that will handle the request and the jsp that
will render the response
Code Generation Note
The configuration of a URL mapping is manifested in several places
in the generated Spring MVC application. Here's a summary of the
effects of a URL mapping::
1. an servlet mapping entry (mapping to Spring servlet) will be
added to the web.xml
2. an @RequestMapping entry will be added to the controller
method(s) representing the operation, and the value will be the
configured URL.
3. the view is automatically emitted into the request handler
Each mapping has several parameters:
Table 2.1. URL Mapping Parameters
Parameter Description
URL The URL being mapped, or intercepted by the MVC framework. The
controller that the URL Mapping is being added to will handle all
requests for the specified URL.
Request Handler The operation that will handle the request or
variable that data will be bound to.
When an Operation is specified as the request handler, the
configured URL is being mapped to the functionality corresponding
to the selected Operation.
When an Variable is specified as the request handler, the
configured URL can be used for mapping data to the selected
Variable. (This is primarily an AJAX scenario.)
While a request handler is typically specified, it's not required.
If the request handler is omitted, then the URL will essentially
function as an alias to the View.
View The view that should be rendered following the invocation of
the Operation; the configuration choices are:
• A JSP page
Web Layer Recipes
• Controller or Operation variable
For a specific URL mapping the view cannot be the same as URL
because you would end-up with a circular reference. While you can
workaround this by using an alias to the URL, this approach is
generally not recommended because it exposes the implementation
technology to end-users and potential hackers. See Hide the
Implementation recipse for the best practice approach.
Redirect: By default the request will be forwarded to the view on
the server. The redirect option will instead send the browser a
redirect command to the specified View.
Error View The Error View functions very similarly to the View,
except that it specifies the view that should be rendered following
a binding or validation error. The configuration choices are the
same as View.
Data Validation The Spring validation class and method that should
be used to validate the request.
The configurations needed to achieve the desired page flow pattern
are represented in the following diagram:
Example 2.4. URL Mapping - Examples
URL OPERATION VIEW ----------------------------------
--------------------------------
---------------------------------
/OrderController/LoadHistory.action --> LoadHistory -->
history.jsp
/index.jsp --> LoadPreferences --> layout.jsp
/preferences --> LoadPreferences -->
preferencesummary.jsp
/index.htm --> LoadCatalog --> index.jsp
Web client calls to /OrderController/LoadHistory.action will invoke
the LoadHistory operation and the response will be rendered by
history.jsp. A convention used by Skyway Builder is to
automatically create a URL for new operations using the model
package for namespacing the URL
(i.e."/org/myapp/web//ControllerName/OperationName.action"). This
can be overridden from the operation wizard when the operation is
created, and it can also be overriden after the fact in the URL
mapping tab. Web client calls to /index.jsp will invoke the
LoadPreferences operation and the response will be rendered by
layout.jsp. Web client calls to /preferences will invoke the
LoadPreferences operation and the response will be rendered by
preferencesummary.jsp. The point of this example is that you can
have multiple URLs mapped to the same operation, and the same or
separate View can be specified. Web client calls to
/OrderController/SaveHistory.action will invoke the SaveHistory
operation and the response will be rendered by the view specified
in the operation variable called page. The developer can
dynamically specify the page based on the result of the operation.
Web client calls to /index.htm will invoke the LoadCatalogy
operation and the response will be rendered by index.jsp. See
Hiding the Implementation Technology for more details on this BEST
PRACTICE
RELATED RECIPES
3. Hiding the Implementation Technology
4. Implementing Post/Redirect/Get (PRG) Pattern
11. Creating Helper Methods using Operations PROBLEM
There are occasions where you want to create operations that are
shared by other operations for performing common tasks. The Helper
Operations are typically not intended to be accessible from a web
client, and there needs to be strategy for preventing web clients
from accessing these Operations.
SOLUTION
Create an Operation that doesn't have a defined URL Mapping. This
will result in an Operation that isn't directly accessible to web
clients and is only accessible from other Operations using the
Invoke Operation step. An Operation can have multiple mappings
defined in the Web Controller. If an Operation has at least one
mapping, the Operation is considered public. If a URL Mapping
doesn't exist for Operation, the Operation is considered
private.
It's also possible to define helper operations in the Service layer
of the application, and service operations can called from the web
layer using the Invoke Operation step.
HOW IT WORKS
Since a URL Mapping is responsible for defining the url(s) that
will trigger an operation. Omitting or removing a URL Mapping for a
specified operation will result in the operation only being
available to other operations in the same controller.
Code Generation Note
When an operation is excluded from all URL mappings, the method
generated from the operation won't have the @RequestMapping
annotation, the input parameters won't be annotated with
@RequestParm or @ModelAttribute, and the method won't make use of a
ModelAndView object.
RELATED RECIPES
2. Reusing Operations in Different Contexts
3. Hiding the Implementation Technology
4. Implementing Post/Redirect/Get (PRG) Pattern
12. Reusing Operations in Different Contexts PROBLEM
An operation is a specific set of logic that handles a
user-generated event. There are occasions where an Operation may be
reused in different contexts. There needs to be a strategy for
reusing an Operation in a different context and associating it with
a different View.
Web Layer Recipes
24
SOLUTION
A controller allows for multipe URL mapping entries to the same
Operation. As the long as the URL is unique, addition URL mappings
can be added to the controller and configured to the same
Operation. In this scenario the developer mat also want to specify
a different View for the Action.
HOW IT WORKS
The following two URL mappings are configured for the same
operation but different views.
Example 2.5. URL Mapping - Reusing Actions URL OPERATION VIEW
---------------------------------- --------------------------------
---------------------------------
/OrderController/LoadHistory/detailed --> LoadHistory -->
detailview.jsp
/OrderController/LoadHistory/summary --> LoadHistory -->
summaryview.jsp
Web client calls to /OrderController/LoadHistory/detailed will
invoke the LoadHistory operation and the response will be rendered
by detailview.jsp. Web client calls to
/OrderController/LoadHistory/summary will invoke the LoadHistory
operation and the response will be rendered by
summaryview.jsp.
In both cases the LoadHistory operation is being invoked, however a
different URL and View are specified in the URL Mapping.
Code Generation Note
When two or more URL mappings are configured to the same operation,
the operation logic will be generated to a separate implementation
method, and each controller methods generated from the URL mappings
will call the single implementation method and specify it's own
view.
RELATED RECIPES
2. Creating Helper Methods using Operations
3. Hiding the Implementation Technology
4. Implementing Post/Redirect/Get (PRG) Pattern
13. Hiding the Implementation Technology PROBLEM
One of the best practices in web development is to avoid directly
revealing the implementation technology. This prevents hackers from
identifying the implementation technology, thus reducing a hackers
ability to potentially interfere with the running application. This
practice also makes it easier to change the implementation
technology without impacting end-users of an application (i.e.
bookmarks). There needs to be a strategy to hide the implementation
technology in Spring applications generated by Skyway.
SOLUTION
In the context of JAVA and Spring, implementing this best practice
consists of hiding the fact that you are using JSPs. Don't use JSP
extensions (.jsp) in URLs, and refrain from letting the JSP
extension show up
Web Layer Recipes
25
in the browser's address bar. That doesn't mean you can't use JSPs
for rendering the view. It just means that you hide it from the
end-user. This is accomplished by mapping some other URL with a
different extension to the actual JSP. Since a web application is
typically emitting HTML, the generally preferred extension is .htm
or .html.
HOW IT WORKS
The only server resources that a web client can access are the
resources that are exposed by the developer using a URL mapping. As
part of a URL mapping, the developer specifies the URL, Operation,
and View. For the URL, the developer can name the URL whatever
they'd like. Instead of specifying a URL with a JSP extension, the
URL should have a .html extension.
For each web client request (using a URL with a .html extension), a
JSP page (View configuration from the URL mapping) will generate
the response. However the user's address bar will show the mapped
URL, not the JSP.
Example 2.6. URL Mapping - Hiding Implementation Technology URL
OPERATION VIEW ----------------------
--------------------------------
---------------------------------
/index.html --> LoadData --> index.jsp
/edit.html --> InitEdit --> edit.jsp
Web client calls to index.html will invoke the LoadData operation
and index.jsp will render the response. The end-user's browser bar
will show the requested url (/index.html). Web client calls to
edit.html will invoke the InitEdit operation and edit.jsp will
render the response. The end-user's browser bar will show the
requested url (/edit.html).
RELATED RECIPES
2. Creating Helper Methods using Operations
3. Reusing Operations in Different Contexts
4. Implementing Post/Redirect/Get (PRG) Pattern
14. Implementing Post/Redirect/Get (PRG) Pattern PROBLEM
Post/Redirect/Get (PRG) is a common design pattern for web
applications, to help avoid duplicate form submissions and allow
web applications to behave more intuitively with browser bookmarks
and the reload button. After a web user submits a form to a server,
the server typically generates an HTML page as a response. To the
user, this looks like an ordinary web page, but because it was
generated by an HTTP POST request, it cannot be bookmarked, and
attempting to reload/refresh the page in the browser could cause
the form information to be resubmitted, possibly with unexpected
results (such as a duplicate purchase). Wikipedia2
SOLUTION
To avoid this problem, many web applications use the PRG pattern —
instead of returning an HTML page directly, the POST operation
returns a redirection command (using the HTTP 303 response
code
2 http://en.wikipedia.org/wiki/Post/Redirect/Get
26
(sometimes 302) together with the HTTP "Location" response header),
instructing the browser to load a different page using an HTTP GET
request. The result page can then safely be bookmarked or reloaded
without unexpected side effects. Wikipedia3
HOW IT WORKS
When a post is made to a Skyway Operation, the View is configured
to send a redirect command to the browser to a second URL, using
the URL mapping's redirect option. The redirect results in a second
request (get) being automatically made by the end-user's browser to
another URL. The second URL is mapped to an operation for loading
the model data before being directed to a JSP page for rendering
the view. The redirect results in the second URL being listed in
the browser's address bar. If the end-user refreshes the page, the
original data won't be resubmitted because only the second URL will
be reloaded. If the second URL is configured with an Operation that
loads data, a bookmarked page can be reconstituted.
The following fragment shows two URL mappings working in tandem to
implement the PRG pattern.
Example 2.7. URL Mapping - Post/Redirect/Get (PRG) URL OPERATION
VIEW ---------------------- ----------------------------
---------------------------------
/MyController/SaveOperation.action --> SaveOperation -->
edit.html (w/ REDIRECT)
/edit.html --> LoadOperation --> edit.jsp
When data is posted to the server, the form is configured to post
to the /MyController/ SaveOperation.action URL. The URL mapping for
/MyController/SaveOperation.action is configured to invoke
SaveOperation, which presumably processes the user input. Rather
than emitting the view directly using a JSP, the View is configured
to redirect to a second URL, specified as edit.html. The edit.html
URL has it's own URL mapping entry (get). The URL mapping for
/edit.html is configured to invoke LoadOperation to load data. The
view for edit.html is rendered using the configured JSP page
(edit.jsp)
As far as the end-user is concerned, they submitted data to the
application and they received a response, and they are generally
unaware that two http requests were used to accomplish it.
RELATED RECIPES
2. Creating Helper Methods using Operations
3. Reusing Operations in Different Contexts
4. Hiding the Implementation Technology
15. Restricting Direct Access to JSP Pages PROBLEM
For many modern MVC framework, there is an expectation that all web
client requests will go through a front controller. In the context
of Spring MVC, the front controller is the Spring Dispatcher
Servlet. Web resources, such as JSP pages, that are typically
accessible as web resources must not be directly accessible to web
clients..
3 http://en.wikipedia.org/wiki/Post/Redirect/Get
27
SOLUTION
A common approach for disallowing direct access to JSP pages is to
putting JSP pages in the WEB-INF folder. Any resources located in
WEB-INF folder, including JSP pages, aren't URL addressible.
The supporting web application resources (css, javascript, images)
need to be directly accessible, and they should not be located in
the WEB-INF folder. Only the JSP pages, which are intended to be
accessed through a URL mapping, should be contained in the WEB-INF
folder.
HOW IT WORKS
By placing JSP pages in the WEB-INF folder, web clients can't
directly access the JSP pages. However the developer can use JSP
pages in the WEB-INF folder when specifying the View for URL
Mappings.
RELATED RECIPES
16. Implementing Controller Methods using Actions and Steps
PROBLEM
A controller is responsible for orchestrating the server logic
necessary for processing a request from a web client. The logic
associated with a controller is contained within one or more
related controller methods, that must be implemented to define the
behaviour of the application. There needs to be a mechanism for
leveraging automation for defining and implementing controller
methods.
SOLUTION
The Skyway Generation Framework has generators for the different
layers of a Spring application, and the framework also supports
fine-grained specification of the application logic. The metadata
model encompasses an extensible toolbox of pre-built functionality
(Skyway Steps) that can be used to specify the application logic.
Skyway Steps introduce automation to the application development
process. Using steps to implement logic (instead of custom code) is
very appealing to developers and architects. First of all it
reduces the redundancy of application development. Rather than
continuously having to write the same code over and over with only
minor differences, steps automate the generation of code for the
developer. By using steps there is also more uniformity in the code
because all the code was generated in the same consistent manner
(using a customizable step template). There will also be less
deviation in code as attributed by different developer styles,
conventions or preferences. Enterprise architects love steps
because they are easy to create, and it ensures that developers are
accessing enterprise resources in a prescribed and controlled
manner.
To achieve the desired application behavior, a developer will
1. define a Skyway Operation for each controller method
2. define the signature of the operation using inputs/outputs
3. define at least one action for each Skyway Operation
4. add one or more steps from the Step Pallette (toolbox) to the
Action
5. configure the steps according to application requirements
6. sequence the steps into a flow
Web Layer Recipes
28
The Skyway Generation Framework then converts the Operation and
Action into a controller method and the sequence of steps into
well-formed java code.
HOW IT WORKS
Operations define web controller methods for handling
user-generated events, and Actions are used to model the operation
logic. Skyway Builder enables a Operation to be implemented using a
model-based approach, that defines the logic to be performed by
configuring and sequencing one or more Skyway Steps together.
Steps for creating an Action:
1. Right click the on an operation, and select New-->Action to
open the New Action Wizard.
2. From the New Action panel enter a common name for the Action.
The common name is for referencing the Action from other Actions in
the same operation. Click Finish. The Action Editor will be
opened.
Steps for implementing an Action:
1. Click on a desired step from the step palette. The steps are
grouped by related functionality into drawers.
2. Next click on the location on action canvas that you want to
place the step..
3. Configure the step using the properties in the properties
panel.
4. Repeat the process until all steps are located on the canvas and
configured.
5. Next draw a connector (available from the palette) between
steps. The steps should connected in the order that they must
execute.
6. When done, right-click on the step that you desire to be the
first step to run, and mark it as the Start Step using the menu
option.
Figure 2.11. Action Editor
The Step Palette contains all the available steps. The steps are
divided into functional groups, and they are separated by each
other using drawers.
Web Layer Recipes
Figure 2.12. Step Palette
In order to accomplish more complex tasks the application logic may
be implemented using several Actions. A operation is configured to
call a specific Action (entry point action), which will orchestrate
calls to other Actions (using Invoke Action step) or Operations
(using Invoke Operation step) in the Service layer of the
application.
The following figures shows an abbreviated version of the code that
is generated from an Action artifact. To see the fully generated
code, see the SkywayBlog sample project.
Web Layer Recipes
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import
org.springframework.context.annotation.Scope; import
org.springframework.stereotype.Component;
/** * SelectPost - Action * * @generated */ @Scope("prototype")
@Component("BlogController.BrowseModel.selectPost") public class
SelectPost implements IVariableContextProvider {
/** * @generated */ private transient ApplicationContext
applicationContext;
/** * Reference to Model used by Action * @generated */
@Resource(name = "BlogController.BrowseModel") private BrowseModel
variableStorage;
// Constructor ...
GENERATATED APPLICATION LOGIC GOES HERE }
}
Code Generation Note
The code that is generated by a Skyway step is contributed by
Eclipse plugins. Skyway Builder Community Edition (CE)4 contains a
core set of steps for code generation, and the other editions of
Skyway Builder5 add additional steps. Using the Eclipse plugin
architecture, new steps can be developed to automate the generation
of any java logic. If you are interested in building your own
steps, the Skyway Builder community site6 has a tutorial. While
Skyway Builder includes a default set of code generation options
and templates, Skyway Builder also supports code generation
customization.
4 http://www.skywayperspectives.org/portal/web/guest/builderce 5
http://www.skywayperspectives.org/portal/web/guest/builder 6
http://www.skywayperspectives.org/
3. Accessing Request and Session Parameters
4. Using Groovy in Actions
17. Blending Actions with non-generated Java Code PROBLEM
As described in the Implementing Controller Methods using Actions
and Steps recipe, augmenting the application development process
with modeling-based automation can significantly improve
development productivity and application quality. However it's
important to recognize that modeling- based automation should not
be an all or nothing proposition. Model-based automation must be
complimentary to traditional code-based development. There are
occasions where java code may be better suited to implement a
portion of an Action. Therefore there needs to be a seemless way of
blending java code with generated code.
SOLUTION
Skyway Builder excels at blending models and code. Skyway Builder
let's you drop code into your projects that can be used along-side
the model-based components. In the event that your functionality
cannot be effectively expressed using models (perhaps due to
lacking model-based representations of functionality or
efficiency/performance considerations), you can use regular java
code and java libraries along with your models.
While using java code in conjunction with models is a powerful
feature in itself, Skyway Builder goes the extra step of adapting
(blending) code-based resources to appear as model-based resources
in the modeling environment. For example, if you define POJO's in
your project, they can be used just like POJO's derived from
models.
Another capability afforded by the Skyway Builder application
generation engine is that the generated logic/code can be used
directly from the developer's custom code. The code generated by
Skyway is concise and human-readable, and it's organized and
packaged according to the developers preference. This makes it very
easy for developers to find and use the generated functionality
from within their custom code.
The bottom line is that Skyway Builder makes it easy for your
model-based and code-based artifacts to co- exist and interact.
Java developers can now implement the data, service, and web layers
of their solution entirely in models or through the blending of
models and java code. Custom Java code can be authored along side
models, and both can be fully leveraged by one another.
The Invoke Java step lets you invoke pre-written JAVA code from
your Action. (For Spring integration see Blending Actions with
non-generated Spring Beans) As a developer is sequencing various
Skyway steps to implement an Action, the developer can incorporate
pre-existing JAVA logic into the flow. The JAVA code may be
contained in JAVA libraries (jar) or a source files within the
project.
HOW IT WORKS
In order for a JAVA class to be used by the Invoke Java step, the
class must have a PUBLIC constructor that doesn't require any
arguments. The following figure shows a very basic JAVA class that
will be leveraged from an Action.
Web Layer Recipes
package example.web.mycontroller.mymodel;
public void doThat(String z){ //... return; }
}
Steps for calling JAVA code using Invoke Java Step:
1. From an Action, open the Java drawer in the Skyway Step
Palette.
2. Click on the Invoke Java step in the palette and click on the
Action Canvas. The step will be placed at the location you
click.
3. Switch to the Java panel on the Steps properties.
4. Select an invocation type
• Inline - this invocation type is for invoking java source code
that is embedded directly into the step (Source)
• Variable - this invocation type is for invoking methods on
variables defined in either the Model or Project
• Instance - this invocation type is for creating an instance of a
specified class prior to invoking a java method
• Static - this invocation type is for invoking static methods
without creating an instance of a class
5. After the invocation type is selected, the Java panel will show
the fields that need to be configured. Configure the remaining
fields to invoke the MyJavaClass.
6. Based on the method signature, the Parameters panel will list
any input parameters. The input parameters must be mapped to
variables
The following examples will show the generated code for the various
invocation types.
Inline Invocation
In order to use inline invocation, you must specify the code in the
source window of the Invoke Java Step using the Inline invocation
option. The code will be generated verbatim into the operation
method.
Variable Invocation
In order to use variable invocation, you must create an instance of
the class using an Operation variable. Next configure the Invoke
Java step using the Variable invocation option and specify the
variable, method name and return variable.
Web Layer Recipes
// InvokeJavaStep: Invoke Java
MyJavaClass instanceVariable =
getVariableStorage().getMyclassVar();
String result_1 = instanceVariable.doThis(inputString,
inputInteger);
getVariableContext().set("outputString", result_1);
A reference to MyJavaClass is being obtained from model variables.
Input parameters are being obtained from model variables. The
doThis() method is being called, and input parameters are being
passed. The return parameter is being assigned to model
variable.
Instance Invocation
In order to use instance invocation, configure the Invoke Java step
using the Instance invocation option and specify the class name,
method name and return variable.
Example 2.11. Invoke Java Step - Instance Invocation (Generated
Code)
// InvokeJavaStep: Invoke Java
String result_1 = instanceVariable.doThis(inputString,
inputInteger);
getVariableContext().set("outbean", result_1);
A new reference to MyJavaClass is being instantiated. Input
parameters are being obtained from model variables. The doThis()
method is being called, and input parameters are being passed. The
return parameter is being assigned to model variable.
Static Invocation
In order to use static invocation, configure the Invoke Java step
using the Static invocation option and specify the class name,
method name and return variable.
Web Layer Recipes
// InvokeJavaStep: Invoke Java
getVariableContext().set("outputString", result);
Input parameters are being obtained from model variables. The
doFoo() method is being statically invoked, and input parameters
are being passed. The return parameter is being assigned to model
variable.
RELATED RECIPES
2. Blending Actions with non-generated Spring Beans
18. Blending Actions with non-generated Spring Beans PROBLEM
The Blending Actions with Custom Java Code recipe described how to
use custom java from within Actions, and it was accomplished by
creating an instance to the JAVA classes that contain the code. As
further described in the recipe, there are various options for
creating those instances. However the Invoke Java step doesn't
support having instances of a java class be acquired through
Spring.
SOLUTION
The Invoke Spring step lets you invoke Spring beans from an Action.
By adding one or more beans to a Spring context file and
registering the Spring context file in the Skyway modelling
project, the application developer lets Spring handle instantiating
the bean. Using the Invoke Spring step, the developer can leverage
the logic contained in the bean.
HOW IT WORKS
In order for a Spring bean to be used by the Invoke Spring step,
the class must have a PUBLIC constructor that doesn't require any
arguments. The following figure shows a very basic Spring Bean
(MyBean) that will be leveraged from an Action.
Web Layer Recipes
public class MyBean {
private String country;
public void setCountry(String country) { this.country = country;
}
public MyBean(){ System.out.println("I have been instantiated"); }
public String doThis(String x){ System.out.println(country); return
x+"DONE"; } }
The following Spring context defines a bean call MyBean.
Example 2.14. Spring Context File - mycontext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
</beans>
Steps for calling Spring Beans using Invoke Spring Step:
1. Copy mycontext.xml to the source folder of the same project
(i.e. example-W