Searching...
Saturday, 9 November 2013

Spring Data + Spring MVC Simple Example

12:06
In this example we will see how to integrate SpringData in to Spring MVC.

Environment Used

  1. JAVA 1.7
  2. SPRING 3.2.0
  3. SPRINGDATA 1.2.0
  4. MONGODB
  5. ECLIPSE + MAVEN
  6. TOMCAT 7

1. Create a Maven web Project and add below dependencies

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>

2.Create Spring configuration (dispatcher-servlet..xml)

Create below spring configuration file and place in to web-inf directory
<?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"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"

>
    <mvc:annotation-driven />
    <context:component-scan base-package="com.pretech" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
    </bean>
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
    <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="customermongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo" />
        <constructor-arg name="databaseName" value="customerdb" />
    </bean>

    <bean id="customerService" class="com.pretech.CustomerService">
<!-- <property name="customermongoTemplate" ref="mongoTemplate" />
-->

    </bean>
</beans>

3. Create Customer class (Customer.java)

package com.pretech;

public class Customer {
    public String name;
    public String address;

    public Customer(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }

    public Customer() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }

}

4. Create CustomerService.java

In this class we will use MongoTemplate instance which is defined in our spring configuration to do database operations

package com.pretech;

import java.util.List;

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

public class CustomerService {

    @Autowired
    private MongoTemplate customermongoTemplate;

    public void saveCustomer(Customer customer) {
        if (!customermongoTemplate.collectionExists(Customer.class)) {
            customermongoTemplate.createCollection(Customer.class);
        }
        customermongoTemplate.insert(customer, "customerTable");
    }

    public List<Customer> listCustomers() {
        return customermongoTemplate.findAll(Customer.class, "customerTable");
    }
}

5. Create a Controller class (CustomerController.java)

package com.pretech;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;

@Controller
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/customer", method = RequestMethod.GET)
    public String getCustomerList(ModelMap model) {
        model.addAttribute("customerList", customerService.listCustomers());
        return "customerdetails";
    }

    @RequestMapping(value = "/customer/save", method = RequestMethod.POST)
    public View saveCustomer(@ModelAttribute Customer customer, ModelMap model) {
        customerService.saveCustomer(customer);
        return new RedirectView("/spring-data-mvc-example/customer");
    }

}

6.Create a Jsp page to Insert and View Customer details (customerdetails.jsp)

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
    <h2>SpringData MVC example</h2>

        <form action="customer/save" method="post">
            <label for="name">Customer Name</label>
            <input type="text" id="name" name="name"/>
                        <label for="address">Customer Address</label>
            <input type="text" id="address" name="address"/>

            <input type="submit" value="Submit"/>
        </form>

    <table border="2">
        <c:forEach var="customer" items="${customerList}">
            <tr>
                <td>${customer.name}</td>
                <td>${customer.address}</td>

            </tr>
        </c:forEach>
    </table>
</body>
</html>

7. Update web.xml

Add spring dispatcher and listener details in to web.xml
<welcome-file-list>
        <welcome-file>customerdetails.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

8. Final Structure


image

9. Start MongoDB and Deploy Application in to Tomcat

Build this maven project (mvn clean install) and deploy war in to tomcat. (Make sure that your mongodb is up and running) Once war is deployed we will get below screen to submit and view customer details.

Example

image

image

Document details in MongoDB

image

Done!!!!

Download this example :
https://github.com/kkvinodkumaran/myrepository/tree/master/spring-data-mvc-example

0 comments: