This sections shows how to work with Cayenne in a web application.
The web part of the web application tutorial is done in JSP, which is the least common denominator of the Java web technologies, and is intentionally simplistic from the UI perspective, to concentrate on Cayenne integration aspect, rather than the interface. A typical Cayenne web application works like this:
- Cayenne configuiration is 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). However see "ObjectContext Scope" section of the Web Applications page. The context can be scoped differently depending on the app specifics. For the tutorial we'll be using a session-scoped context.
For more information on the web application deployment, check Web Applications page.
So let's convert the tutorial that we created to a web application:
- In Eclipse under "tutorial" project folder create a new folder "src/main/webapp/WEB-INF".
- Under "WEB-INF" create a new file "web.xml" (a standard web app descriptor):
- Create the artist browser page src/main/webapp/index.jsp file with the following contents:
- Create the artist editor page src/main/webapp/detail.jsp with the following content:
To run the web application we'll use "maven-jetty-plugin". To activate it, let's add the following piece of code to the "pom.xml" file, following the "dependencies" section and save the POM:
- Go to "Run > Run Configurations..." menu, select "Maven Build", right click and select "New"
- Make sure you fill "Name", "Base directory" and "Goals" fields as shown on the screenshot:
- Click "Apply" and "Run". On the first execution it may take a few minutes for Jetty plugin to download all dependencies, but eventually you'll see the logs like this:
- So the Jetty container just started and loaded Cayenne.
- Now go to http://localhost:8080/tutorial/ 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!