Skip to main content

How to create a SpringMVC web application in Eclipse with MongoDB and maven?


Use my previous blog post here to create a basic helloworld SpringMVC web application without integrating it to a specific database. That will be a starting point for you to create this project that I am going to explain here with MongoDB.

To know how to setup MongoDB have a look at my blog post here. This is if you are using a windows environment.

I will list down the files that you need to create.

As an overview, you will create or make use of the following files in this project.

  1. Song.java - This is the POJO or the model class that holds all the fields that should go in your database along with the getters and setters for the fields. Here the class represents a document(a record) that goes in the database.
  2. SongDAO.java - This is a java interface that contains the method declarations of the methods that will be used to perform database manipulations(that is the CRUD operations basically).
  3. SongDAOImpl.java - This class implements the SongDAO interface and provides the concrete implementation of the methods declared in SongDAO.
  4. SongController.java - This is the controller class that handles client requests and calls the methods in the SongDAO to perform database operations and present the relevant vies to the client.
  5. SongRegistration.jsp - This is the view that is used to register and view the already added records to the database
  6. index.jsp
  7. web.xml
  8. spring-servlet.xml
  9. context.xml
  10. pom.xml
Now I will present to you here the outline of the above files so that you can get started with implementing your own SpringMVC web app with MongoDB.

PS: Note the packages that the following files are in and create your webapp structure accordingly. The name of the database is ExampleWebApp.

Song.java


package com.example.springmvc.model;

import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="song")
public class Song {

private String songID;
private String songTitle;
private String vocalist;
public Song() {}
public String getSongID() {
return songID;
}
public void setSongID(String songID) {
this.songID = songID;
}
public String getSongTitle() {
return songTitle;
}
public void setSongTitle(String songTitle) {
this.songTitle = songTitle;
}
public String getVocalist() {
return vocalist;
}
public void setVocalist(String vocalist) {
this.vocalist = vocalist;
}
}

SongDAO.java

package com.example.springmvc.dao;

import java.util.List;

import com.example.springmvc.model.Song;

public interface SongDAO {
public List<Song> listAllSongs();
public Song getSongbyID(String songID);
public List<Song> getSongByTitle(String songTitle); 
public void addSong(Song song);
public void updateSong(Song song);
public void removeSong(Song song);
}


SongDAOImpl.java


package com.example.springmvc.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import com.example.springmvc.dao.dao.SongDAO;
import com.example.springmvc.dao.model.Song;

@Repository
public class SongDAOImpl implements SongDAO{
@Autowired
private MongoTemplate songTemplate;
public List<Song> listAllSongs() {
return songTemplate.findAll(Song.class);
}
public Song getSongbyID(String songID) {
//TODO Implement the method
return null;
}

public List<Song> getSongByTitle(String songTitle) {
// TODO Auto-generated method stub
return null;
}

public void addSong(Song song) {
if (!songTemplate.collectionExists(Song.class)) {
songTemplate.createCollection(Song.class);
}
songTemplate.insert(song);
}

public void updateSong(Song song) {
//TODO implementation of update
}

public void removeSong(Song song) {
songTemplate.remove(song);
}
}


SongController.java


package com.example.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import com.example.springmvc.model.Song;
import com.example.springmvc.dao.SongDAO;

@Controller
public class SongController {
@Autowired
private SongDAO songDao;
@RequestMapping(value = "/song", method = RequestMethod.GET)
public String getSongList(ModelMap model) {
model.addAttribute("songList", songDao.listAllSongs());
return "SongRegistration"; //This is the name of the JSP file to render
}
@RequestMapping(value = "/song/register", method = RequestMethod.POST)
public View addSong(@ModelAttribute Song song, ModelMap model) {
songDao.addSong(song);
return new RedirectView("/springmvc/song");
}
}


SongRegistration.jsp


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
    <h2>Song Registration</h2>
        <form action="song/register" method="post">
            <label for="songID">Song ID</label>
            <input type="text" id="songID" name="songID"/>
            <label for="songTitle">Song Title</label>
            <input type="text" id="songTitle" name="songTitle"/>
            <label for="vocalist">Vocalist</label>
            <input type="text" id="vocalist" name="vocalist"/>
            <input type="submit" value="Submit"/>
        </form> 
        <table border="1">
        <c:forEach var="song" items="${songList}">
            <tr>
            <td>${song.songID}</td>
                <td>${song.songTitle}</td>
                <td>${song.vocalist}</td>
            </tr>
        </c:forEach>
    </table>  
</body>
</html>


index.jsp


<html>
<body>
    <h2>Welcome to Home Page - OSCA</h2>
    <p>
        <a href="song">Click here</a> to register a song.
    </p>
</body>
</html>

web.xml


<!--!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd"-->

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
         
  <display-name>ExampleWebApp</display-name>
  
  <servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>    
  
  <servlet-mapping>
      <servlet-name>spring</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
   <!-- Other XML Configuration -->
  <!-- Load by Spring ContextLoaderListener -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/context.xml</param-value>
  </context-param>
  
   <!-- Spring ContextLoaderListener -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
</web-app>

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:mongo="http://www.springframework.org/schema/data/mongo"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.1.xsd 
     http://www.springframework.org/schema/data/mongo 
     http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd 
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
   
  <context:component-scan base-package="com.example.springmvc.controller" />
  <context:component-scan base-package="com.example.springmvc.dao" />
    
  <context:annotation-config />  
  
  <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
        <property name="host" value="localhost" />
  </bean>
  
  <!-- MongoTemplate for connecting and quering the documents in the database -->
  <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
      <constructor-arg name="mongo" ref="mongo" />
      <constructor-arg name="databaseName" value="ExampleWebApp />
  </bean>
  
  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
  
  <bean
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      
      <property name="prefix">
          <value>/WEB-INF/view/</value>
      </property>
      
      <property name="suffix">
          <value>.jsp</value>
      </property>        
      
  </bean>
</beans>

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd">
 <!-- Empty -->
</beans>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>springmvc</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Example SpringMVC Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    
  <!-- Servlet Library -->
    <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet-api.version}</version>
        <scope>provided</scope>
    </dependency>
    
  <!-- Spring dependencies -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.framework.version}</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.framework.version}</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.framework.version}</version>
    </dependency>
    
    <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring.data.commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.data.mongodb.version}</version>
</dependency>
    
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>
</dependencies>

  <!-- Properties for the dependencies -->
  <properties>
  
  <!-- Spring properties -->
  <spring.framework.version>4.2.5.RELEASE</spring.framework.version>
  <spring.data.commons.version>1.12.1.RELEASE</spring.data.commons.version>
  <spring.data.mongodb.version>1.9.1.RELEASE</spring.data.mongodb.version>
 
  <!-- Other properties -->
  <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
  <junit.version>3.8.1</junit.version>
  <jstl.version>1.2</jstl.version>
  </properties>
  
  <build>
    <finalName>ExampleWebApplication</finalName>
  </build>
</project>


Cheers! Now you are all set. To run the application build the project using Maven clean install in Eclipse and run it on your desired server. I use WildFly(JBoss) to run my project.

Now you will be able to try it out yourself. :) 



Comments

Popular posts from this blog

How to connect my database instance with elastic beanstalk instance in AWS?

If you have deployed your web application in Elastic Beanstalk in AWS and now you need to connect a database to this instance, and your database is actually residing in a different instance, how can you actually connect them? It's easy with Elastic Beanstalk. I will explain an example scenario that I used for connecting my elastic beanstalk web application with another instance containing my MongoDB database. By looking at this, you can customize as per your need. Don't worry. This is easy. :) The only things you need here are the details about the 1. Database name that you need to connect to. Ex:- "myDB" 2. Port at which the database instance is listening. EX:- In the case of MongoDB, the listening port is 27017 3. Host name of your database instance. EX:- Like localhost, in this case, it will be the Public DNS of your database instance 4. The password of your database if exists. First these details need to be set as environment variables in Elastic Be

How to import the Public Certificate of one WSO2 product to the trust store of another?

To demonstrate this point, I will use the 2 products WSO2 API Manager 2.1.0 (referred as APIM from here onwards) and WSO2 Enterprise Integrator 6.1.1 (referred as EI from here onwards). When using EI as the Business Process Server during configuration of Workflows in APIM, one step to perform is to import the public certificate of EI to the truststore of APIM [1]. So now let's see how this can be done. Step 1: Go to <EI_HOME>/repository/resources/security/ folder and execute the following keytool command. This command is used to export the public certificate of EI as a certificate file called wso2carbon.cer. Since the default keystore in EI is wso2carbon.jks, we have specified it as the keystore and the default alias is wso2carbon. Provide wso2carbon as the keystore password when prompted as it is the default password. After executing the above command from within the security folder in EI, you will see that a file with the name of wso2carbon.cer is created