In the first part of this tutorial, we got the web application set up so that we can start building on it.
In the xml files, we have referenced three classes by this point that we will need to stub out so that our application will run.
@Entity @Table(name = "entry") //because I always forget about case sensitivity between Linux and Windows public class Entry { @Id @GeneratedValue(strategy = GenerationType.AUTO) protected Long id; private String title; private String text; //getters and setters... }
For now we just need a way of getting entries from the database. We’ll put in the other method later.
@Transactional(readOnly = true) public class EntryRepository { @Autowired protected SessionFactory sessionFactory; public List<Entry> getAll() { return sessionFactory .getCurrentSession() .createCriteria(Entry.class) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .list(); } }
On the home page lets simply list the titles of all Entry object in the database.
@Controller public class HomeController extends ParameterizableViewController { @Autowired private EntryRepository entryRepository; @RequestMapping(method = RequestMethod.GET) public String showPage( HttpServletRequest request, HttpServletResponse response, ModelMap model) { model.put("entrylist", entryRepository.getAll()); return getViewName(); } }
We told out HomeController to expect a file named index.html to be available. So lets make this file and put it in the webapp directory.
<html>
<head><title>Sandbox - Hibernate and Spring</title></head>
<body>
<h1>Sandbox</h1>
<a href="/entry/create">Create an entry</a>
<h2>Entries</h2>
[#list entrylist as item]
<p>${item.title}</p>
[/#list]
</body>
</html>You will need to follow some instructions for setting this up to run with a tool such as maven or ant. I haven’t posted instructions here yet, but you should be able to find them easily enough on the net.
Once these classes are in place, lets build the project and run jetty.
When the application runs for the first time, the database tables will get created. So when we browse to our application and hit the /index page, we will see our page but there will be no entries listed. You can add some entries manually into your database to see that they will be loaded by the controller.
A sequence of events starts off from the servlet that we mapped in the web.xml file…
Now that we have our application basics set up, we can move on to Part 3 of the tutorial where we will look at GET and POST methods of the annotated controllers.
RSS feed for comments on this post · TrackBack URI
Leave a reply