How To Show Data From Database Using SpringMVC + Hibernate + AngularJS

Hi.. in this article I will create simple web app using SpringMVC + Hibernate + AngularJS to show data from database. Some environment that I need are:

  1. SpringMVC libs.
  2. Hibernate libs.
  3. AngularJS.
  4. Another required libs like database connector, aopalliance, apache common.
  5. IDE. This time, I use netbeans.

I use mySQL as my database. The data that I want to show is from User table and has some data like this:

db

After create project that use SpringMVC and Hibernate framework, I setup application context, dispatcher servlet, and web.xml

which is looks like below

applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <context:component-scan base-package="com.aries.blog" />
    <tx:annotation-driven />
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
         p:driverClassName="com.mysql.jdbc.Driver"
         p:url="jdbc:mysql://localhost:3306/bohayblog?zeroDateTimeBehavior=convertToNull"
         p:username="root"
         p:password="bohay"
         p:initialSize="5"
         p:maxActive="10"
         p:maxIdle="5"
         p:minIdle="2"
         p:maxWait="30000"
         p:removeAbandoned="true"
         p:removeAbandonedTimeout="30"
         p:validationQuery="SELECT 1"/>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:hibernate.cfg.xml">
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>

</beans>

Explanation:
tx:annotation-driven >> for complete explanation please look on Spring Documentation

dispatcher-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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
   
    <context:annotation-config/> 
    <context:component-scan base-package="com.aries.blog.controller"/>

    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    
    <mvc:annotation-driven/>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

</beans>

Explanation:
mvc:annotation-driven >> tag essentially sets Spring context to allow for dispatching requests to Controllers.
mvc:resources mapping=”/js/**” location=”/js/” >> means we can call file from js folder with link baseurl/js.
InternalResourceViewResolver >> find view from /WEB-INF/jsp/ with .jsp as format

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

The next thing that I do is create hibernate configuration file.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <mapping resource="com/aries/blog/model/User.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Explanation:
mapping resource >> Register my hibernate mapping file for table User.

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="bohayblog"/>
  <table-filter match-name="user"/>
</hibernate-reverse-engineering>

Explanation:
table-filter match-name=”user” >> to register User table from bohayblog database.

Now, I ready to create model class & hibernate mapping file, service class, and controller class.
Model Class
User.java

package com.aries.blog.model;

public class User  implements java.io.Serializable {
     private String username;
     private String name;
     private String password;
     private boolean enable;

    public User() {
    }

    public User(String username, String name, String password, boolean enable) {
       this.username = username;
       this.name = name;
       this.password = password;
       this.enable = enable;
    }
   
    public String getUsername() {
        return this.username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return this.password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    public boolean isEnable() {
        return this.enable;
    }
    
    public void setEnable(boolean enable) {
        this.enable = enable;
    }
}

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated May 5, 2015 4:48:37 PM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
    <class name="com.aries.blog.model.User" table="user" catalog="bohayblog">
        <id name="username" type="string">
            <column name="username" length="50" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="name" length="50" not-null="true" />
        </property>
        <property name="password" type="string">
            <column name="password" length="250" not-null="true" />
        </property>
        <property name="enable" type="boolean">
            <column name="enable" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

Service Class
UserService.java

package com.aries.blog.service;

import com.aries.blog.model.User;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
@Transactional
public class UserService {
    
    @Autowired
    private SessionFactory sessionFactory;
    
    public List<User> getAllUser(){
        return sessionFactory.getCurrentSession()
                .createQuery("from User")
                .list();
    }
    
}

Controller
BaseController.java

package com.aries.blog.controller;

import javax.servlet.http.HttpServletRequest;

public class BaseController {
    
    public static final String PARAM_BASE_URL = "baseURL";
    
    public String getBaseURL(HttpServletRequest request){
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
    
}

IndexController.java

package com.aries.blog.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController extends BaseController{
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap model, HttpServletRequest request){
        model.addAttribute(PARAM_BASE_URL, getBaseURL(request));
        return "index";
    }
    
    @RequestMapping(value = "/userlist", method = RequestMethod.GET)
    public String userList(ModelMap model, HttpServletRequest request){
        model.addAttribute(PARAM_BASE_URL, getBaseURL(request));
        return "users";
    }
    
}

UserController.java >> this class handling data from user table by autowired to UserService


package com.aries.blog.controller;

import com.aries.blog.model.User;
import com.aries.blog.service.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping(value = "/getalluser", method = RequestMethod.GET)
    public @ResponseBody List<User> getAllUser(){
        return userService.getAllUser();
    }
    
}

I create simple jsp page to get call the data. But first, lets look to my javascript.
users.js

var myApp = angular.module('mainApp', []);

myApp.controller('UsersController', ['$scope', '$http', function($scope, $http) {

    $scope.listUser = null;
    $scope.resMsg = null;

        $scope.showUserList = function() {
            var urlGetUsers = 'getalluser';
            
            var responEC = $http.get(urlGetUsers, {cache: true, transformResponse: function(data, headersGetter) {
                    try {
                        var jsonObject = JSON.parse(data);
                        keepGoing = true;
                        return jsonObject;
                    }
                    catch (e) {
                        console.log(e);
                        $scope.resMsg = "Error. Cannot Retrieve Data";
                    }
                    return {};
                }});//end ajax 

            responEC.success(function(listUser, status, headers, config) {
                $scope.listUser = listUser;
                if ($scope.listUser == null || $scope.listUser.length == 0) {
                    $scope.resMsg = "No Data";
                }
            });
        };
        
        $scope.showUserList();

    }]);

Explanation:
First, I declare angular module to make my page can read angular function with angular.module(‘mainApp’, []). Then I create function that has ajax function to call getalluser.

Then, here are my jsp.
index.jsp

<%@page import="com.aries.blog.controller.BaseController"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Bohay Blog</title>
        <%
            String baseURL = (String) request.getAttribute(BaseController.PARAM_BASE_URL);
        %>
        <!-- BOOTSTRAP STYLES-->
        <link href="<%=baseURL%>/css/bootstrap.min.css" rel="stylesheet" />
    </head>

    <body>
        <div class="row">
            <div class="col-md-10" style="margin: 10px;">
                <h2>Welcome .. !!</h2>
                <h5>
                    To view sample <a href="<%=baseURL%>/userlist">clik here</a>
                </h5>
            </div>
        </div>
    </body>
</html>

users.jsp


<%@page import="com.aries.blog.controller.BaseController"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <%
            String baseURL = (String) request.getAttribute(BaseController.PARAM_BASE_URL);
        %>
        <title>List Of User</title>
        <!-- BOOTSTRAP STYLES-->
        <link href="<%=baseURL%>/css/bootstrap.min.css" rel="stylesheet" />
        <!-- ANGULAR JS -->
        <script src="<%=baseURL%>/js/angular.js"></script>
        <!--USERS JS -->
        <script src="<%=baseURL%>/js/users.js"></script>
    </head>
    <body>
        <div class="row" ng-controller="UsersController" ng-app="mainApp" style="margin: 10px;">
            <div class="col-md-7">
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        Users
                    </div>
                    <div class="panel-body">
                        <div ng-show="isEmpty(listUser)">
                            {{resMsg}}
                        </div>
                        <div id="dynamic" ng-hide="isEmpty(listUser)">
                            <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="exampleone">
                                <thead>
                                    <tr>
                                        <th>No.</th>
                                        <th>User Name</th>
                                        <th>Name</th>
                                        <th>Is Active</th>
                                    </tr>                                    
                                </thead>
                                <tbody>
                                    <tr ng-repeat="user in listUser">
                                        <td>{{$index + 1}}</td>
                                        <td>{{user.username}}</td>
                                        <td>{{user.name}}</td>
                                        <td>{{user.enable}}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>            
        </div>
    </body>
</html>

Explanation:
To call the angularJS model from outside AngularJS tag, we only need double curly brace tag {{var_name}}.

If you want to get full code of my project, you can download from Here. Hope this simple sample can help you. Happy coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s