31,19 €
Web development is trickyóeven a simple web application has a number of context changes ready to trip up the unwary. Grails takes the everyday pain out of web application development, allowing us to focus on delivering real application logic and create seamless experiences that will address the needs of our users. This book will take the pain out of Grails by showing you exactly how to build a web application with a minimum of fuss.
With this book, even if you are new to Grails, you will be up and running before you know it. You will be able to code faster and your code will be better. This clear and concise book is packed with examples and clear instructions to help you build your first Grails application and gives you the skills to speed up your application development by adding a different angle for learning about the topic. After a brief introduction to the dynamic JVM-based Groovy programming language, which teaches you enough about Groovy to understand the relationship between Grails and the Groovy scripting language, it shows how to use Grails and a number of key plug-ins to deliver valuable web applications. It also takes you through creating, developing, testing, and deploying an example team collaboration application in Grails.
Using an incremental and iterative approach you will learn how to build a basic web application with secure authentication and different levels of authorization. You will learn how to handle file upload allowing users to share files. Some advanced features of object-oriented persistence will be introduced through adding tags for messages and files to giving users a robust categorization system.
You will then build on the basic application to enhance the user experience through AJAX and the RichUI plug-in. You will take a further step into the world of Web 2.0 by adding an RSS feed and a REST service to the application. Once the entire application is up and running, you will learn how to create your own plug-in for tagging. Finally, you will learn how to deploy this application to a production environment.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 347
Veröffentlichungsjahr: 2009
Copyright © 2009 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2009
Production Reference: 2190509
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847196-68-2
www.packtpub.com
Cover Image by Vinayak Chittar (<[email protected]>)
Author
Jon Dickinson
Reviewers
Harshad Oak
Xinyu Liu
Acquisition Editor
Douglas Paterson
Development Editor
Dhiraj Chandiramani
Technical Editor
Shadab Khan
Copy Editor
Leonard D'Silva
Sumathi Sridhar
Indexer
Monica Ajmera
Production Editorial Manager
Abhijeet Deobhakta
Editorial Team Leader
Akshara Aware
Project Team Leader
Lata Basantani
Project Coordinator
Leena Purkait
Proofreader
Angie Butcher
Production Coordinator
Dolly Dasilva
Cover Work
Dolly Dasilva
Jon Dickinson is an independent software development consultant based in the UK. He has been delivering web applications on the Java platform over a range of business domains covering finance, tourism, energy, education, and transport, for the last ten years. He uses a mix of agile methods, pragmatism, and software craftsmanship to deliver valuable software that helps achieve the goals of real users.
He is the principal consultant and founder of Accolade Consulting Ltd. (http://www.accolade-consulting.co.uk) and can be contacted at <[email protected]>.
I would like to thank the people that have helped me on my way to writing this book.
My thanks goes to the people at Packt involved in this project: Douglas Paterson, Usha Iyer, Dhiraj Chandiramani, Leonard D'Silva, Sumathi Sridhar, Leena Purkait, and Shadab Khan. They have been very supportive and patient throughout the process, putting up with my ongoing restructuring of the book and the occasional missed deadline. I have come to realize that it is much easier to refactor code than prose.
The comments of my reviewers have been invaluable in the creation of this book. I can't imagine the end product without them. Thank you to Harshad Oak for invariably being right regarding issues of the books structure, Michael Galpin for his input to the early chapters, Xinyu Liu for some excellent technical review points in the later chapters and Phil Parker for reinforcing structural issues and convincing me to upgrade the book to the latest version of Grails.
To Graeme Rocher and the Grails development team, thank you for taking the issue of productivity in Java web development seriously and doing something about it. To the Grails community at large, and it is getting pretty big, keep up the great work on those plug-ins.
To my wife, Georgia, thank you for your patience and putting up with the lost weekends and evenings. To Amelia and Oliver, thank you for the constant interruptions that put everything else in perspective.
Harshad Oak is the founder of Rightrix Solutions and the editor of IndicThreads.com. He is the author of three books which include Oracle Jdeveloper 10g: Empowering J2EE Development, Pro Jakarta Commons, and J2EE 1.4 Bible. He has also written several articles on Java topics. For his contributions to technology and the community, he has been recognized as an Oracle ACE Director and a Sun Java Champion.
Rightrix Solutions works in the field of technology media and research. It runs the Java portal IndicThreads.com and hosts the annual IndicThreads.com conference in Pune, India.
Xinyu Liu had graduated from the George Washington University. As a Sun Microsystems certified enterprise architect and developer, he has intensive application design and development experience in Java and SOA environments. He is a writer for Java.net and Javaworld.com and covers various topics including JSF, Spring Security, Hibernate Search, Spring Web Flow, and the new Servlet 3.0 specification. He also has a background in physics PhD with several publications in both, high energy and condensed matter fields.
The expectations of our users are increasing, and rightly so. The Internet is no longer the playground of geeks and nerds. Businesses use it to communicate with and support their customers; families use it to keep in touch while whole communities share their experiences with like-minded people. The democratization of the Internet has brought a new wave of software into the lives of people who would otherwise rarely use computers. The most successful of the new generation of web applications have not been written for the expert user, but for the casual user, focusing on ease of use. Web application development frameworks that focus on developer productivity have improved the ability of developers to respond to the demands of their users. Simpler and more intuitive frameworks have allowed the rapid development and refinement of new features.
Java web application development has something of a checkered history; simple isn't it. There may be more than one way to skin a cat, but there are almost infinite numbers of ways to build a Java web application. The options that are available are mind-boggling. Which database server to use? What about the application server? You also better choose an MVC framework while you're at it. Should you use a persistence framework, or hand code SQL statements? If you use an ORM framework, which one is best? Don't forget to choose a logging library. How should the project be laid out? Once you've finished making all these decisions, it's time to start on the configuration to get all of these disparate frameworks working together. Now, eventually you are ready to start coding! No wonder the latest and greatest web applications are built in PHP and Ruby on Rails.
Java still has a lot to offer. It is faster than most other languages that are used for web application development. It is an extremely mature platform, with lots of high quality libraries available. Moreover, its static, strong typing gives you less rope to hang yourself with. However, Java developers need to find technologies that deal with the common activities of web development. Sometimes we need a few choices taken away to help us focus on the problem at hand, creating great software that provides value to our users at less cost to the people paying the bills.
Grails does just this. It removes the need for reams of configuration through a convention-based approach that constrains developers in a healthy way.The decisions concerning project layout and which frameworks to use are removed.This leaves the developers free to use their creative talents for producing great software, rather than tweaking configuration files.
Throughout this book, you will learn how to build a web application using Grails and a number of key plug-ins. You will see that it is possible to achieve a great deal with very little code. Who knows, you may even rediscover your passion for web development on the Java platform!
Chapter 1 presents a short state of the nation of Java web development and makes the case for a framework like Grails. At the end of the chapter, we will install and create a Grails project.
Chapter 2 covers the use of Grails scaffolding to generate some simple pages to manage users and roles for our application.
Chapter 3 shows how to post messages, where we write the first basic functionality for the application by allowing users to post messages that can be shared with other users. This chapter introduces a number of basic concepts for Grails development including: controllers, validation, Groovy Server Pages (GSP), and Grails Object-Relational Mapping (GORM).
Chapter 4 covers an introduction to Groovy. Here we take a short break from the Grails framework to get a better understanding of the Groovy programming language. We will cover just enough of the language to be able to proceed through the rest of the book.
Chapter 5 shows how to use our first external plug-in to add authentication and authorization to the application.
Chapter 6 covers testing, where we introduce the different levels of automated testing that are available in the Grails framework. We see how to write, unit tests with new support for testing in Grails 1.1. We also cover integration tests, and install a functional testing plug-in.
Chapter 7 covers file sharing, where we allow users to share files through the application by introducing file uploads.
Chapter 8 covers some advanced querying techniques, using Hibernate criteria support in GORM, to implement file version history.
Chapter 9 introduces Grails services in more depth. We see how to extract logic from our controllers into services to keep the application maintainable.
Chapter 10 introduces more advanced GORM techniques, such as: persisting inheritance and performing polymorphic queries to enable tagging. We also delve into GSP a bit more by using templates to encapsulate view components.
Chapter 11 covers AJAX and RIA Frameworks — Where we improve the user experience with AJAX to allow users to edit tags in-line and use the RichUI plug-in to create tag clouds and perform auto suggestion when editing tags.
Chapter 12 shows us how to use the Searchable plug-in to add a search feature to our site in a matter of minutes. We also provide an RSS feed and a REST based API for managing messages.
Chapter 13 show us how to build our own plug-in, where we follow the example of the Grails plug-in community and extract our tagging code into a plug-in that we can use on future projects.
Chapter 14 shows how to package and deploy the application to a production ready for use in a production environment. We then discuss some next steps that may be worth investigating to handle real world situations.
To implement the example code in this book, you will need the Java SDK 5 or above. More importantly, you will need to have some experience of web development on the Java platform.
This book is aimed at Java web developers looking for ways to speed up development of web applications on the Java platform. If you are frustrated with integrating the many different frameworks that are available for web development and want to get on with building slick web applications for your users, then this book is for you.
Grails is built on the Groovy language, but experience in Groovy is not required, as you will learn enough about Groovy to understand how to use Grails.
Feedback from our readers is always welcome. Let us know what you think about this book — what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Visit http://www.packtpub.com/files/code/6682_Code.zip to directly download the example code.
The downloadable files contain instructions on how to use them.
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books — maybe a mistake in text or code — we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Grails is a dynamic web development framework on the Java platform for rapid application development. It has taken the coding by convention approach popularized by Ruby on Rails, and applied it as a wrapper over long established open source Java frameworks such as Hibernate and Spring. It uses the flexibility of Groovy to provide a Domain-Specific Language (DSL) for web development.
The goal is to be able to develop web applications with the minimum amount of effort without having to repeat yourself. Grails provides a consistent and reliable environment between all of your projects.
Web development is a tricky business. Even a simple web application has a number of context changes ready to trip up the unwary developer. HTTP requests must be parsed and converted into internal code representations. Once parsed, the data must be validated to make sure no invalid or dangerous information has been sent. The data extracted from these requests is then persisted to rows in database tables. To send a response back to the user, data must be retrieved from the database and converted into the domain model. It is then rendered from the domain model into HTML format and sent back over HTTP. With every user action going through all these different conversions, we can see how web development can become expensive, and this is just the server side. We haven't even considered all the client-side coding that goes into web applications with the rich user experiences that are becoming the norm in the Web 2.0 era.
Over the years, there have been a number of frameworks created to alleviate the cost of building web applications. Web frameworks such as Struts, Spring MVC, Stripes, and JSF help in mapping the HTTP requests to code logic. Object to relational database mapping frameworks allow domain objects to be persisted directly to the database, Hibernate being the most notable. These frameworks have allowed larger and more complicated web applications to be implemented by reducing the workload of the application developer. Unfortunately, a side effect of multiple frameworks is an increased level of configuration that needs to be produced and maintained. The level of knowledge required to create framework configuration files is probably less than writing the code. However, it is notoriously difficult to debug and test the configuration.
Grails helps application developers provide value faster by:
The first benefit Grails provides is a convention-based approach to remove the need for reams of configuration, while still leveraging the power of the mature underlying frameworks. In practice, this means that you don't spend a lot of time wiring your code together in XML configuration files, or muddy your code with endless annotations. Instead, if a class is created, according to the convention in the correct location, it will be wired into Spring as needed or will be treated as a Hibernate entity ready to be persisted in the database.
The convention based approach applies to your development environment as well as the code. As soon as you create a Grails project, you have a defined structure and a set of scripts already available to compile, test, run and package your project. Having all these scripts managed in a consistent and conventional manner greatly reduces the time required to get a project up and running.
Grails also comes configured with a bundled database and application server. So once you have Grails installed, and your project created, there is nothing else you need before you start development.
No longer do you need to spend time setting up a development environment for each project. Tweaking your Ant build scripts slightly for each new environment is a thing of the past, and so is configuring an application and database server for development.
Grails uses a bundled Jetty (http://www.mortbay.org/jetty/) installation for the application server, which is configured to execute against the working code base of your application. Grails is also built on top of Groovy — a dynamic language for the JVM that adds powerful new features to Java. Groovy compiles down to the Java bytecode, which allows it to integrate with any existing Java code. Chapter 4 introduces you to the Groovy language, if you have not used it before.
In development mode, Grails provides an auto-reloading feature (http://www.grails.org/Auto+Reloading), which allows you to make changes to your code and see the changes in your browser with the next refresh. There is no need to restart the application, or to re-deploy to an application server.
It is best practice in software development to try and ensure that all developers in a project are working in the same way and have a common environment on each machine. In reality, there are often conflicts between the configurations of different team member's development environments; team members may configure their application servers differently or use different database versions. You can waste valuable time debugging false problems in your software just because another team member has a configuration slightly different from yours.
Grails comes with a pre-defined application structure. This ensures that all developers will be working in the same way with the same environment configuration.
Any experienced Java web developer will be familiar with the Servlet Specification, which provides a standard set of interfaces for working with HTTP. Grails builds on this specification and provides a DSL for developing web applications. The underlying specification is still available to developers, if they wish to use it, but in- depth knowledge is no longer required. By leveraging the flexibility of the Groovy language, Grails provides an intuitive and simple domain language specific to the web development, upon which you can build great web applications.
The cost of getting up and running with Grails is remarkably low. You will need to download and install the following:
Note that there is no need to download Groovy; it comes bundled with the Grails download.
Compare this to getting set up on a normal Java web project, where the typical download and install list would look something like this:
You will eventually need to download and install an application server and a database server. Fortunately, this work can be put off until later down the line when you are thinking about deployment.
Now that you have had the salesman's pitch for Grails, it's time to see if it can live up to the hype. So, let's get started.
Download Grails from http://www.grails.org and extract the downloaded files to your development folder. Create an environment variable called GRAILS_HOME and point it to the extract location.
You will then need to add the %GRAILS_HOME%/bin to your path. It's that easy!
While working on a Mac, you can modify the environment.plist file in the .MacOSX directory as shown in the following screenshot:
Although Grails is built on top of Groovy, there is no need to install Groovy separately. Grails comes with the groovy-all-x.x.x.jar bundled and executes your Groovy code directly.
The first step is to create a new Grails application with the Grails script, ' create-app'. You will create a new application called 'teamwork'. Open up your command line, go to your development area and run:
You should see something like the following output:
This will create a folder called teamwork and will set up your application structure within this folder. Verify that the application has been configured correctly. Go to the teamwork directory and check that you have a folder structure as shown in the following screenshot:
The grails-app folder will contain the main source code for your application. By examining the layout of this folder, you can see the beginnings of the convention for the layout of your application. The Model View Controller (MVC) (http://java.sun.com/blueprints/patterns/MVC-detailed.html) pattern is enforced through this convention.
Here is the breakdown of the layout:
Once you have confirmed that the structure of your project directory is correct, go into the teamwork directory in your command line and run:
Wait for the message, Server running. Browse to http://localhost:8080/teamwork, to appear in your command line. Then you can open a browser, and you will see the default Grails start page as shown in the following screenshot:
This is an equivalent of your "Hello World" example, when using any other framework. The result is a Java application server running on port 8080 with your application deployed to the context teamwork. This is not bad going for a five-minute job.
Grails comes with Jetty and HSQLDB already configured, which is why we have been able to get an application up and running so quickly. Jetty is a Java application server that can be ran as an embedded component within any Java application. HSQLDB is a lightweight Java SQL database engine that can be run in-memory with minimal configuration.
Grails applications are packaged as a WAR file for deployment, and so, are not limited to running under Jetty. But developing in this environment provides several benefits including:
Now that we have installed Grails and the default page is up and running, it is time to start creating our application. The aim of this book is to build a communication portal for teams. The application will allow team members to share messages and files with the rest of the team. You will need to implement the following:
Once you have finished implementing the application, you will see how to deploy the application into a production environment using Tomcat and MySQL.
Finally, you will finish up with some additional areas to consider and investigate further, which have not been discussed in this book.
There is a common set of problems associated with web development. There has been a constant progression of frameworks that have gradually made life easier for web developers by pulling more and more common tasks into framework code, allowing us to focus on the implementation of application logic. Grails is the next link in the chain. It applies a Domain-specific language for web development to the most mature and popular frameworks and enforces some best practices along the way.
By setting up the Grails version of the "Hello World" application, we have seen that the cost of setting up your development environment is almost nonexistent. In the next chapter, we will see how to use the power of scaffolding to perform basic user management tasks without having to write any logic at all.
We are going to create a web application that will allow members of a team to communicate with one another. We will need to be able to make each of the team members a user of the application, so that in future iterations they can log in and collaborate. In this chapter, we will create a domain class to represent a user and a role in the application. We will add constraints to these domain classes to enforce the integrity of the data that is entered. By the end of this chapter, we will use Grails scaffolding to generate a user interface that allows users and roles to be managed within the application.
Scaffolding is a mechanism used in Grails to allow developers to generate web pages that perform basic CRUD (Create, Read, Update, Delete) operations on the classes that make up the domain model of the application. These "scaffolded" pages are a very useful low-cost mechanism that allows you to verify whether your domain classes are capturing all the necessary information. It is however, extremely rare for a scaffolding to be used in a version of the application released to users, as most web applications require more complex usage scenarios that can be provided through default scaffolding.
When scaffolding is enabled for a domain class, the following pages and actions will be available to work with that domain object:
Scaffolding will handle:
We will see that it is possible to get a significant amount of value from these screens without needing to implement any application logic.
