Spring Data MongoDB example with Spring MVC 3.2
Here is another example web application built with Spring MVC 3.2 and Spring Data 1.2, integrating with the MongoDB document database.
STEP 1: Create new webapp project, I will use maven for this. (Note: I am on my macbook with Maven 3 and Java 6 installed.)
mvn archetype:generate
-DgroupId=com.manishchhabra.blog
-DartifactId=HelloSpringWithMongoDB
-DarchetypeArtifactId=maven-archetype-webapp
-DinteractiveMode=false
You could create the maven project directly in your IDE as well. But I usually create it on the terminal and import it in eclipse by using the following command (Note: The following command is run within your newly created project directory, i.e. run -> cd HelloSpringWithMongoDB)
mvn eclipse:eclipse -Dwtpversion=2.0
STEP 2: Add Spring Framework 3.2 and Spring Data 1.2 dependencies to your pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
STEP 3: Update your web.xml (src/main/webapp/WEB-INF/web.xml) to use Spring’s DispatcherServlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
STEP 4: Add your spring configuration to the dispatcher-servlet.xml
- Use MongoFactoryBean to connect to the MongoDB instance.
- Use MongoTemplate to connect and make queries to the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
STEP 5: Create a model (using Person as an example), service and controller in the new source directory src/main/java
Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Service
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
Controller for the CRUD operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
STEP 5: Create a JSP Page in the folder WEB-INF/jsp called output.jsp (This will currently invoke create and delete).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
STEP 6: That’s it! Its time to run your project. You could either run directly from eclipse or you could run “mvn package” to build a war file and deploy it to your application server. I tested this on tomcat running on port 8080 (http://localhost:8080/HelloSpringWithMongoDB/person) and I could store and delete person with provided names. Working! yeah.. Here is a picture of me playing with the app
Spring Data MongoDB Spring MVC 3.2 Example App
You can view or download the full project code athttps://github.com/manishchhabra/HelloSpringWithMongoDB