Now we'll convert the tutorial that we created to a web application. The web part of it is done in JSP and is intentionally primitive from the UI perspective, to concentrate on Cayenne integration aspect. There may be some specifics depending on the web framework used (JSP, Struts, JSF, Click, WebWork, Tapestry, etc.), still the procedure outlined here is quite universal as it relies on the J2EE servlet specification.
A typical Cayenne web application works like this:
- Cayenne files are loaded when an application context is started, using a special servlet filter.
- User requests are intercepted by the filter, and the DataContext is bound to the request thread, so the application can access it easily from anywhere.
- The same DataContext instance is reused within a single user session; different sessions use different DataContexts (and therefore different sets of objects).
For detailed discussion of web application deployment, check this page.
To run the web application from Eclipse, we will use JettyLauncher plugin. If you are using something else (e.g. a Tomcat plugin) it should probably work as well.
- Download and unpack Jetty web container (tested version is 5.1.3).
- Download and unpack JettyLauncher to a local directory. Install it in Eclipse ("Help > Find and Install").
- In Eclipse under "cayenne-tutorial" project folder create a new folder called "webapp" and a subfolder called "WEB-INF".
- Under "WEB-INF" create a new file "web.xml". This is a standard web deployment descriptor:
The following is the contents of web.xml. All the DataContext magic described above is achieved by WebApplicationContextFilter.
- Create the artist browser page - webapp/index.jsp file with the following contents:
- Create the artist editor page webapp/detail.jsp with the following content:
- Run the application. Go to "Run > Run..." menu, select "Jetty Web", right click and select "New"
- Make sure project is "cayenne-tutorial", webapp root is "webapp" and Jetty home points to a directory where you unpacked Jetty:
- Click "Apply" and "Run".
- You will see some Cayenne logs, indicating that the filter was loaded and Cayenne is successfully runing in web app.
- Now go to http://localhost:8080/ URL. You should see "No artists found message" in the web browser and the following output in the Eclipse console:
- You can click on "Create new artist" link to create artists. Existing artists can be edited by clicking on their name:
You are done with the tutorial!