Thursday 19 February 2015

Spring-MVC-Hibernate CRUD example using Annotations


Developers most often looks for the tutorials on the topic Spring MVC using Hibernate as it is the latest java web framework. As it is a simple to understand it needs less time to write an application but the sad part is that we spend most of the time in searching for the right tutorial. This tutorial is to help such seekers and to save their valuable time.

In java application development , Spring and hibernate integration is one of the most-perfect combination to develop the enterprise applications in java. Spring is the leading enterprise application framework and Hibernate is the leading ORM framework. So combination of these technologies would result in robust and reliable web application.

This is the step by step tutorial in which we will learn the workflow of the Spring MVC framework and How to write a simple web application to perform the CRUD operations ?

1. Spring MVC workflow

 

The Spring MVC pattern separates the different aspects of web application like business logic, UI Handling and communication between all of them. The main components of MVC pattern are:

Model (M in MVC) 

Spring Model is responsible for handling business logic. Most often the model is nothing but a POJO     class.         

View (V in MVC)

View is responsible for UI part.

Controller (C in MVC)

Controller will handle the communication between Model and View class. Controller is responsible for creating and getting output from model class and rendering this to View to display into the browser.    
The backbone of Spring MVC framework is Dispatcher servlet. This servlet handles all the incoming http request and process the response. Following diagram explains How dispatcher servlet handles the incoming request: 



 

A)     Mapping a Handler : 

 This is the first step to handle the incoming request. Dispatcher servlet first search for the right handler class by mapping the URL.
Note : Please make sure that you have defined the base package using the tag "<base-scan>" in deployment descriptor. Dispatcher servlet will looks only into this package for the appropriate handler class.

B)      Controller :

The Controller takes the incoming request and calls the appropriate service methods depends on GET or POST method and executes the business logic. Controller is responsible to return the view name to dispatcher servlet.
Note : Controller uses ModelAndView class to return the specific view. This class internally uses ViewResolver bean which we have defined in the dispatcher servlet configuration file to find out the view page.

C)      ViewResolver :

Dispatcher servlet take help of ViewResolver bean which is configured in the dispatcher servlet's configuration file. View Resolver will look for the specified view page either at the default location or at the custom location as configured in the configuration file.

D)     View

Once view is finalized, dispatcher servlet rendered the model data to the view to display it in the browser.

2. Spring MVC Hibernate CRUD Example


In this application we need following jars. Please download it and paste them into "WebContent/WEB-INF/lib" folder.

















 
Our final project structure looks like this:


This application consists of just following 5 major components :
                   1)    Different tables in MySQL database.
                   2)    Deployment Descriptor and Spring Configuration file.
                   3)    DAO, Domain, Dto and Service Classes.
                   4)    Controller Class.
                   5)    JSP page.

 

Customer table in MySQL database

First create required tables in MySQL database using following script :
 CREATE TABLE `cb_users_master` (   
  `username` varchar(45) NOT NULL,   
  `password` varchar(45) NOT NULL,   
  `enabled` tinyint(4) NOT NULL DEFAULT '1',   
  PRIMARY KEY (`username`)   
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
  CREATE TABLE `cb_user_roles` (   
  `user_role_id` int(11) NOT NULL AUTO_INCREMENT,   
  `username` varchar(45) NOT NULL,   
  `role` varchar(45) NOT NULL,   
  PRIMARY KEY (`user_role_id`),   
  UNIQUE KEY `uni_username_role` (`role`,`username`),   
  KEY `fk_username_idx` (`username`),   
  CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `cb_users_master` (`username`)   
  ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;   
  CREATE TABLE `cb_customer_master` (   
  `owner_id` bigint(10) unsigned NOT NULL AUTO_INCREMENT,   
  `owner_name` varchar(30) NOT NULL,   
  `owner_add` varchar(100) NOT NULL,   
  `owner_contact_no` decimal(12,0) NOT NULL,   
  PRIMARY KEY (`owner_id`)   
  ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;  


Deployment Descriptor and Spring Configuration File

First To configure the web application context and dispatcher servlet we need to define web.xml.
web.xml
 <?xml version="1.0" encoding="UTF-8"?>   
  <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>Spring-MVC-Hibernate</display-name>   
  <welcome-file-list>   
   <welcome-file>login.jsp</welcome-file>   
  </welcome-file-list>   
  <servlet>   
   <servlet-name>mvc-dispatcher</servlet-name>   
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>   
   <load-on-startup>1</load-on-startup>   
  </servlet>   
  <servlet-mapping>   
   <servlet-name>mvc-dispatcher</servlet-name>   
   <url-pattern>/</url-pattern>   
  </servlet-mapping>   
  <listener>   
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener>   
  <context-param>   
   <param-name>contextConfigLocation</param-name>   
   <param-value>   
          /WEB-INF/mvc-dispatcher-servlet.xml,   
          /WEB-INF/security-config.xml   
        </param-value>   
  </context-param>   
  <filter>   
   <filter-name>springSecurityFilterChain</filter-name>   
   <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>   
  </filter>   
  <filter-mapping>   
   <filter-name>springSecurityFilterChain</filter-name>   
   <url-pattern>/*</url-pattern>   
  </filter-mapping>   
  </web-app>   


In above example, after initialization of web.xml the dispatcher servlet will try to load the application context from the mvc-dispatcher-servlet.xml in which we have configured datasource bean for jdbc connection, secondly hibernate session factory is beaing configured and ViewResolver bean is being added to render the corresponding jsp's.

mvc-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:context="http://www.springframework.org/schema/context"   
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"   
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"   
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd   
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd   
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd   
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">   
    <context:component-scan base-package="com.spring.*">   
     <context:exclude-filter type="regex" expression="com.spring.domain"/>   
    </context:component-scan>   
    <mvc:annotation-driven/>   
    <mvc:default-servlet-handler/>   
    <context:spring-configured/>   
    <mvc:resources mapping="resources/**" location="/WEB-INF/resources/,/resources/,/META-INF/resources/" />   
    <!-- Default Page Handlers -->   
    <mvc:view-controller path="/login" view-name="login"/>   
    <mvc:view-controller path="/home" view-name="home"/>   
    <mvc:view-controller path="/" view-name="home"/>   
    <mvc:view-controller path="/denied" />   
    <mvc:view-controller path="/uncaughtException" />   
    <mvc:view-controller path="/resourceNotFound" />   
    <mvc:view-controller path="/dataAccessFailure" />   
    <!-- Default Page HAndlers Ends -->   
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"   
       p:driverClassName="${jdbc.driverClassName}"   
       p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />   
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">   
       <property name="prefix">   
         <value>/WEB-INF/jsp/</value>   
       </property>   
       <property name="suffix">   
         <value>.jsp</value>   
       </property>   
   </bean>   
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:basename="WEB-INF/messages" >   
       <property name="defaultEncoding" value="UTF-8" />   
    </bean>   
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"    
       p:location="/WEB-INF/jdbc.properties" />   
    <!-- Hibernate properties starts here -->   
    <bean id="sessionFactory"   
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">   
    <property name="dataSource" ref="dataSource" />   
    <property name="configLocation">   
     <value>classpath:hibernate.cfg.xml</value>   
    </property>   
    <property name="annotatedClasses">   
         <list>   
          <value>com.spring.domain.CbOwnerMaster</value>   
        </list>   
       </property>   
    <property name="hibernateProperties">   
     <props>   
      <prop key="hibernate.dialect">${jdbc.dialect}</prop>   
      <prop key="hibernate.show_sql">true</prop>   
      <!-- <prop key="packagesToScan">com.vedar.domain</prop> -->   
     </props>   
    </property>   
   </bean>   
    <tx:annotation-driven transaction-manager="transactionManager"/>   
   <bean id="transactionManager"   
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">   
    <property name="sessionFactory" ref="sessionFactory" />   
   </bean>   
    <!-- Hibernate properties starts here -->   
  </beans>   

Datasource bean defines the jdbc properties like username, password, database URL etc.These properties should be declared in jdbc.properties file and should keep this file in WebContent/WEB-INF folder.Then we have configured the bean ViewResolver by using which Dispatcher servlet will be able to know where the jsp pages are. Dispatcher servlet use the session factory bean to configure hibernate related properties.

DAO, Dto, Domain and Service Classes

Now we have to define an entity class using jpa annotations which would mapped to table cb_owner_master in database.
  
CbOwnerMaster.java
  package com.spring.domain;   
  // Generated 2 Aug, 2014 1:44:14 PM by Hibernate Tools 4.0.0   
  import static javax.persistence.GenerationType.IDENTITY;   
  import java.util.Date;   
  import javax.persistence.Column;   
  import javax.persistence.Entity;   
  import javax.persistence.GeneratedValue;   
  import javax.persistence.Id;   
  import javax.persistence.Table;   
  import javax.persistence.Temporal;   
  import javax.persistence.TemporalType;   
  /**   
  * CbOwnerMaster generated by hbm2java   
  */   
  @Entity   
  @Table(name = "cb_owner_master")   
  public class CbOwnerMaster implements java.io.Serializable,DomainObject {   
    /**   
     *    
     */   
    private static final long serialVersionUID = 1L;   
    private Long ownerId;   
    private String ownerName;   
    private String ownerAdd;   
    private long ownerContactNo;   
    public CbOwnerMaster() {   
    }   
    public CbOwnerMaster(String ownerName, String ownerAdd,   
         long ownerContactNo, String ownerEmailId, Date dateOfRegistration,   
         String ownerStatus) {   
       this.ownerName = ownerName;   
       this.ownerAdd = ownerAdd;   
       this.ownerContactNo = ownerContactNo;   
    }   
    @Id   
    @GeneratedValue(strategy = IDENTITY)   
    @Column(name = "owner_id", unique = true, nullable = false)   
    public Long getOwnerId() {   
       return this.ownerId;   
    }   
    public void setOwnerId(Long ownerId) {   
       this.ownerId = ownerId;   
    }   
    @Column(name = "owner_name", nullable = false, length = 30)   
    public String getOwnerName() {   
       return this.ownerName;   
    }   
    public void setOwnerName(String ownerName) {   
       this.ownerName = ownerName;   
    }   
    @Column(name = "owner_add", nullable = false, length = 100)   
    public String getOwnerAdd() {   
       return this.ownerAdd;   
    }   
    public void setOwnerAdd(String ownerAdd) {   
       this.ownerAdd = ownerAdd;   
    }   
    @Column(name = "owner_contact_no", nullable = false, precision = 12, scale = 0)   
    public long getOwnerContactNo() {   
       return this.ownerContactNo;   
    }   
    public void setOwnerContactNo(long ownerContactNo) {   
       this.ownerContactNo = ownerContactNo;   
    }   
  }   


Here to simplify the things we will define separate Dto classes ,the objects of these classes will be rendered to jsp pages and not of the entity class object. This will help us to customize the things that we need to display as we will have seprate classes which are mapped to database table and which are displayed in jsp pages.

AddOwnerDto.java
 package com.spring.dto;   
  import java.math.BigDecimal;   
  import java.util.Date;   
  import org.springframework.format.annotation.DateTimeFormat;   
  public class AddOwnerDto {   
    private Long ownerId;   
    public Long getOwnerId() {   
       return ownerId;   
    }   
    public void setOwnerId(Long ownerId) {   
       this.ownerId = ownerId;   
    }   
    private String name;   
    private String address;   
    private BigDecimal contactNo;   
    public AddOwnerDto() {   
       super();   
       // TODO Auto-generated constructor stub   
    }   
    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;   
    }   
    public BigDecimal getContactNo() {   
       return contactNo;   
    }   
    public void setContactNo(BigDecimal contactNo) {   
       this.contactNo = contactNo;   
    }   
    @Override   
    public String toString() {   
       return "AddOwnerDto [name=" + name + ", address=" + address   
            + ", contactNo=" + contactNo + ", emailId=" + "]";   
    }   
  }  

Now to perform the hibernate operations like save, update, delete etc. we will define DAO classes. Instead of defining common operations for each class we have defined them in  GenericDao class. If tomorrow you need to define Employee class then you do not need to define all those operations again you can use GenericDao class directly into the Employee class. If you want to define customer related specific operations then you are free to define them in CbOwnerMaster class.

GenericDaoJpa.java
  /**   
  * Generic DOA using JPA   
  */   
  package com.spring.dao;   
  import java.io.Serializable;   
  import java.util.List;   
  import org.hibernate.Session;   
  import org.hibernate.SessionFactory;   
  import org.springframework.beans.factory.annotation.Autowired;   
  import org.springframework.transaction.annotation.Transactional;   
  import com.spring.domain.DomainObject;   
  public class GenericDaoJpa<T extends DomainObject> implements GenericDao<T> {   
    private Class<T> type;   
    @Autowired   
    protected SessionFactory sessionFactory;   
    public GenericDaoJpa(Class<T> type) {   
       super();   
       this.type = type;   
    }   
    @Transactional(readOnly = true)   
    public T get(Object id) {   
       if (id == null) {   
         return null;   
       } else {   
         @SuppressWarnings("unchecked")   
         T o = (T) sessionFactory.getCurrentSession().get(type, (Serializable) id);   
         return o;   
       }   
    }   
    @SuppressWarnings("unchecked")   
    @Transactional   
    public List<T> getAll() {   
       Session session = sessionFactory.getCurrentSession();   
       return session.createQuery(   
            "from " + type.getName() + " o").list();   
    }   
    @Transactional   
    public void save(T object) {   
       Session session = sessionFactory.getCurrentSession();   
       System.out.println("object"+object);   
       session.persist(object);   
       session.flush();   
       session.refresh(object);   
    }   
    @Transactional   
    public void merge(T object) {   
     sessionFactory.getCurrentSession().update(object);   
     return;   
    }   
    public void delete(T object) {   
       if (object != null) {   
         sessionFactory.getCurrentSession().delete(object);   
       }   
    }   
    public void flush() {   
       sessionFactory.getCurrentSession().flush();   
    }   
    public void refresh(T object) {   
       sessionFactory.getCurrentSession().refresh(object);   
    }   
  }   

CbOwnerMasterDaoJpa.java
 package com.spring.dao;   
  import org.springframework.stereotype.Repository;   
  import com.spring.domain.CbOwnerMaster;   
  @Repository("cbOwnerMasterDao")   
  public class CbOwnerMasterDaoJpa extends GenericDaoJpa<CbOwnerMaster> implements   
  CbOwnerMasterDao{   
    public CbOwnerMasterDaoJpa(){   
       super(CbOwnerMaster.class);   
    }   
    public CbOwnerMasterDaoJpa(Class<CbOwnerMaster> type) {   
       super(type);   
       // TODO Auto-generated constructor stub   
    }   
  }   
Now our Dao, Dto and Domain classes are ready and we should go for the service classes which will use those to perform the CRUD operations.

CustomerService.java

  package com.spring.service;   
  import java.math.BigDecimal;   
  import java.math.BigInteger;   
  import java.util.List;   
  import javax.transaction.Transactional;   
  import org.springframework.beans.factory.annotation.Autowired;   
  import org.springframework.beans.factory.annotation.Qualifier;   
  import org.springframework.stereotype.Service;   
  import com.spring.dao.CbOwnerMasterDao;   
  import com.spring.domain.CbOwnerMaster;   
  import com.spring.dto.AddOwnerDto;   
  @Service("OwnerService")   
  public class CustomerService {   
    @Autowired   
    @Qualifier("cbOwnerMasterDao")   
    CbOwnerMasterDao cbOwnerMasterDao;   
    public boolean saveOwnerMaster(AddOwnerDto dto){   
       CbOwnerMaster owner_Master = new CbOwnerMaster();   
       owner_Master.setOwnerAdd(dto.getAddress());   
       owner_Master.setOwnerContactNo(dto.getContactNo().longValue());   
       owner_Master.setOwnerName(dto.getName());   
       try{   
       CbOwnerMaster temp =null;    
       temp=cbOwnerMasterDao.get(dto.getOwnerId());   
       if(temp!=null){   
         temp.setOwnerAdd(dto.getAddress());   
         temp.setOwnerContactNo(dto.getContactNo().longValue());   
         temp.setOwnerName(dto.getName());   
         cbOwnerMasterDao.merge(temp);   
       }   
       else   
       cbOwnerMasterDao.save(owner_Master);   
       return true;   
       }   
       catch(Exception e){   
         e.printStackTrace();   
       }   
       return false;   
    }   
    public List<CbOwnerMaster> getAllOwners() {   
       return cbOwnerMasterDao.getAll();   
    }   
    public AddOwnerDto setOwnerDtoForEdit(String owner_id) {   
       CbOwnerMaster owner = cbOwnerMasterDao.get(Long.parseLong(owner_id));   
       System.out.println(owner);   
       AddOwnerDto temp_Dto = new AddOwnerDto();   
       temp_Dto.setAddress(owner.getOwnerAdd());   
       temp_Dto.setContactNo(new BigDecimal(owner.getOwnerContactNo()));   
       temp_Dto.setName(owner.getOwnerName());   
       temp_Dto.setOwnerId(Long.parseLong(owner_id));   
       return temp_Dto;   
    }   
    @Transactional   
    public boolean deleteOwners(String[] owner_id) {   
       for(String cust_temp : owner_id){   
         try{   
         CbOwnerMaster temp = cbOwnerMasterDao.get(Long.parseLong(cust_temp));   
         if(temp!=null)   
            cbOwnerMasterDao.delete(temp);   
         }   
         catch(Exception e){   
            e.printStackTrace();   
            return false;   
         }   
       }   
       return true;   
    }   
    public CbOwnerMaster getOwnerById(BigInteger owner_id) {   
       CbOwnerMaster owner = cbOwnerMasterDao.get(owner_id.longValue());   
       return owner;   
    }   
  }   

The next step is to define the controller class which will map the incoming http requests and return the corresponding view page.

CustomerController.java
 package com.spring.controller;   
  import java.math.BigDecimal;   
  import java.text.SimpleDateFormat;   
  import java.util.ArrayList;   
  import java.util.Date;   
  import java.util.List;   
  import java.util.regex.Matcher;   
  import java.util.regex.Pattern;   
  import javax.servlet.http.HttpServletRequest;   
  import org.springframework.beans.factory.annotation.Autowired;   
  import org.springframework.beans.factory.annotation.Qualifier;   
  import org.springframework.beans.propertyeditors.CustomDateEditor;   
  import org.springframework.beans.propertyeditors.StringTrimmerEditor;   
  import org.springframework.stereotype.Controller;   
  import org.springframework.validation.BindingResult;   
  import org.springframework.validation.FieldError;   
  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.bind.annotation.RequestParam;   
  import org.springframework.web.servlet.ModelAndView;   
  import org.springframework.validation.Validator;   
  import org.springframework.web.bind.annotation.InitBinder;   
  import org.springframework.web.bind.WebDataBinder;   
  import org.springframework.validation.annotation.Validated;   
  import com.spring.domain.CbOwnerMaster;   
  import com.spring.dto.AddOwnerDto;   
  @Controller   
  @RequestMapping(value="/customer/**")   
  public class CustomerController extends BaseController {   
    @InitBinder   
    public void initBinder(WebDataBinder binder) {   
     SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");   
     sdf.setLenient(true);   
     binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));   
     binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));   
    }   
    @RequestMapping(value="addnew" , method=RequestMethod.GET)   
    public ModelAndView getCustomer(){   
       ModelAndView model =new ModelAndView("addCustomer");   
       model.addObject("newOwner", new AddOwnerDto());   
       return model;   
    }   
    @RequestMapping(value="addnew" , method=RequestMethod.POST)   
    public ModelAndView getCustomerPost(@ModelAttribute("newOwner") @Validated AddOwnerDto ownerDto, BindingResult result){   
       ModelAndView model =new ModelAndView("addCustomer");   
       if (result.hasErrors()) {   
         model.addObject("newOwner", ownerDto);   
         return model;   
    }else{   
      if(isValidForm(ownerDto))   
      {   
         boolean result_Save= customerService.saveOwnerMaster(ownerDto);   
         if(result_Save){   
         model.setViewName("CustomerList");   
         List<CbOwnerMaster> list = customerService.getAllOwners();   
         if(list!=null && list.size()>0){   
            System.out.println("======== List Obtained Size ======="+ list.size());   
            model.addObject("ownerList", list);   
         }   
         model.addObject("message", "sucSave");   
         }   
      }   
       else{   
         model.addObject("newOwner", ownerDto);   
         model.addObject("message", "failSave");   
       }   
    }   
       return model;   
    }   
    @RequestMapping(value="editOrDelete" , method = { RequestMethod.GET, RequestMethod.POST })   
    public ModelAndView addOrEditOwner(@RequestParam("submit") String button_clicked,HttpServletRequest http_request){   
       ModelAndView model = new ModelAndView();   
       if("edit".equalsIgnoreCase(button_clicked)){   
         String owner_id = http_request.getParameter("checkedowner");   
         model.setViewName("addCustomer");   
         model.addObject("isReadOnly",false);   
         model.addObject("newOwner", customerService.setOwnerDtoForEdit(owner_id));   
       }else if("View".equalsIgnoreCase(button_clicked)){   
         String owner_id = http_request.getParameter("checkedowner");   
         model.setViewName("addCustomer");    
         model.addObject("isReadOnly",true);   
         model.addObject("newOwner", customerService.setOwnerDtoForEdit(owner_id));   
       }else{   
         String[] owner_id = http_request.getParameterValues("checkedowner");   
         model.setViewName("CustomerList");   
         boolean ressult_delete = customerService.deleteOwners(owner_id);   
         if(ressult_delete)   
            model.addObject("message", "sucDelete");   
         else   
            model.addObject("message", "failDelete");   
         List<CbOwnerMaster> list = customerService.getAllOwners();   
          model.addObject("ownerList", list);   
       }   
       return model;   
    }   
    public boolean isValidForm(AddOwnerDto ownerDto)   
    {   
       if(isOnlyAlphabates(ownerDto.getName()))   
        return true;   
       else   
         return false;   
    }   
    public boolean isOnlyAlphabates(String name) {   
     char[] chars = name.toCharArray();   
     for (char c : chars) {   
      if(!Character.isLetter(c)) {   
       return false;   
      }   
     }   
     return true;   
    }   
  }   


JSP page

The last part of our application is to define the jsp pages which are responsible for look and feel of our application.

login.jsp
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">   
  <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>   
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">   
  <head>   
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
   <title>Spring MVC Hibernate</title>   
  </head>   
  <body>   
   <div> <!-- class="#Logincontainer" -->    
   <section class="loginform cf">   
   <form name="login" action="/Spring-MVC-Hibernate/resources/j_spring_security_check" method="post" accept-charset="utf-8">   
    <ul>   
  <!--   <li><label for="usermail">Email</label>   
     <input type="email" name="usermail" placeholder="yourname@email.com" required></li>  -->   
     <li><label for="userid">User ID</label>   
     <input type="text" name="username" placeholder="userid" required></li>   
     <li><label for="password">Password</label>   
     <input type="password" name="password" placeholder="password" required></li>   
     <li>   
     <input type="submit" value="Login"></li>   
              <font color="red">   
              <c:if test="${param.login_error != null}">   
                 <br/><br/><br/><br/>Failed to login.   
                   <c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">       
                 Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />   
                   </c:if>   
              </c:if>   
              </font>   
         </ul>   
   </form>   
    </section>   
   </div> <!-- END LoginContainer -->     
  </body>   
  </html>   


home.jsp


  <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>   
  <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>   
  <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->   
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">   
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">   
  <head>   
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
   <title>Home</title>   
   <style>   
   .submenu{   
   display:none;   
   padding: 100px 40px;   
  }   
  .companymenuli:hover > ul{   
   display:block;   
  }   
   </style>   
  </head>   
  <body>   
   <div id="header">   
    <div id="main_menu">   
     <ul>        
            <li class="first_list"><a href="/Spring-MVC-Hibernate/resources/j_spring_security_logout" class="main_menu_first">Logout</a></li>   
     </ul>   
    </div> <!-- END #main_menu -->   
   </div> <!-- END #header -->   
   <form:form name="ownerregi" action="/Spring-MVC-Hibernate/customer" method="GET" accept-charset="utf-8">   
   <input type="submit" value="Customers"/>   
   </form:form>   
  </body>   
  </html>   


To dispaly the list of customers we have define the CustomerList.jsp which also gives the option for CRUD operations.

CustomerList.jsp


  <%@ page language="java" contentType="text/html; charset=ISO-8859-1"    
   pageEncoding="ISO-8859-1"%>    
  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  <html>    
  <head>    
  <title>All Customers</title>    
  </head>    
  <body>    
  <h1>List Customers</h1>    
  <h3><a href="/Spring-MVC-Hibernate/customer/addnew">Add More Customer</a></h3>    
  <form id="ownerListForm" action="/Spring-MVC-Hibernate/customer/editOrDelete" method="POST">   
     <table class="tableGraph" cellspacing="0" width="100%" >   
       <thead>   
        <tr>   
         <th width="5%">&#160;</th>   
         <th width="16%" style="text-align:left;">Name</th>   
         <th width="16%" style="text-align:left;">Address</th>   
          <th width="16%" style="text-align:left;">Contact No</th>   
       </tr>   
      </thead>   
      <tbody>   
        <c:forEach var="owner" items="${ownerList}">   
        <tr>   
         <td><input type="checkbox" id="checkedowner" name="checkedowner" value="${owner.ownerId}" /></td>   
        <td><label style="text-align:left;"><c:out value="${owner.ownerName}" /></label></td>   
         <td><label style="text-align:left;"><c:out value="${owner.ownerAdd}" /></label></td>   
         <td><label style="text-align:left;"><c:out value="${owner.ownerContactNo}" /></label></td>   
       </tr>   
        </c:forEach>   
      </tbody>   
     </table>   
     <div class="buttons mrgn10Btm">   
       <input type="submit" id="submit" name="submit" value="Edit" onclick="return OnSubmitForm(this);"/>   
       <input type="submit" value="Delete" id="submit" name="submit" onclick="return OnSubmitForm(this);"/>   
     </div>   
     </form>   
  </body>    
  </html>   

addCustomer.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"    
    pageEncoding="ISO-8859-1"%>    
   <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>    
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
   <!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=ISO-8859-1">    
   <title>Spring MVC Form Handling</title>    
   </head>    
   <body>    
   <h2>Add Employee Data</h2>    
   <form:form name="ownerregi" action="/Spring-MVC-Hibernate/customer/addnew" modelAttribute="newOwner" method="POST" accept-charset="utf-8">   
      <form:errors path="*" cssStyle="color: #ff0000;"/><br><br>   
      <label for="ownerid">Owner ID</label>   
       <form:input type="text" name="ownerid" path="ownerId" placeholder="XXXXXX" readonly="${isReadOnly}"></form:input><br><br>   
      <label for="name">Owner's Name</label>   
       <form:input type="text" name="name" path="name" placeholder="Owners Name" readonly="${isReadOnly}"></form:input><br><br>   
      <label for="oweraddress">Owners Address</label>   
       <form:input type="text" name="owneraddress" path="address" placeholder="Address" readonly="${isReadOnly}"></form:input><br><br>   
      <!-- <label for="city">City</label>   
       <input type="text" name="city" placeholder="City" required> <br><br> -->   
      <label for="contactno">Contact Number</label>   
      <form:input type="text" name="contactno" path="contactNo" placeholder="+99 999 999 9999" readonly="${isReadOnly}"></form:input><br><br>   
      <c:choose>   
      <c:when test="${isReadOnly eq true}">   
      <form:button onclick="location.href='/Spring-MVC-Hibernate/home'">Back</form:button>   
      </c:when>   
      <c:otherwise>   
      <form:button type="submit" value="Submit" disabled="${isReadOnly}">Submit</form:button>   
      <form:button type="button" value="Cancel" onclick="location.href='/Spring-MVC-Hibernate/customer'" disabled="${isReadOnly}">Cancel</form:button>   
      </c:otherwise>   
      </c:choose>        
  </form:form>   
   <c:if test="${!empty Customers}">    
   <h2>List Customers</h2>    
   </c:if>    
   </body>    
   </html>    

Once you are done with creating source and configuration files, export your application and use Export -> WAR File option and save your Spring-MVC-Hibernate.war file in tomcat's webapp folder.
To login into the application you need to insert user in cb_users_master and cb_user_roles with same username and role as ROLE_ADMIN.

customers  Now start your tomcat server and make sure you are able to access other web pages from webapp folder using a standard browser. Now try a URL http://localhost:8080/Spring-MVC-Hibernate/login and you should see the following resultif everything is fine.























Here is the full source code for above application

Download Spring-MVC-Hibernate.zip


Wednesday 18 February 2015

How to debug remote Java web application using eclipse

Today most of the web applications are developed using java. While developing java applications, debugging is the process by which we can not only save our time and efforts but also increase productivity. Debugging involves local debugging and remote debugging. I will always prefer local debugging over remote debugging. But there are scenarios where local debugging is not possible and we have to go for remote one. But the good news is that today most of the IDE like Netbeans, Eclipse etc. supports remote debugging.

In this post we will learn how to debug java web application deployed using tomcat on remote machine. Both local and remote machine should have windows 7.
To debug remotely the most important thing is that we need source code of our application on our local machine. 
We need to perform two simple steps which will not take much of your time.
            1)    Start the tomcat in debug mode on remote machine.
            2)    Connect local eclipse to remotely running tomcat server  


    1)   Start the tomcat in debug mode on remote machine

        To start the tomcat in debugging mode you need to perform following 3 simple steps:

                1)    Copy following two lines and paste them in startup.bat at the first line after 
                 comments.
                  set JPDA_ADDRESS=8000
                  set JPDA_TRANSPORT=dt_socket

               2)    Change last line in startup.bat
                 call "%EXECUTABLE%" start %CMD_LINE_ARGS%             to
                 call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%.

               3)    Now run the tomcat from command prompt using following command:
                startp.bat
          This will start the tomcat in debugging mode. Now we only need to create run confugarion in elipse and connect to the tomcat we have just started.

2)   Connect local eclipse to remotely running tomcat server

To create the run configuration in eclipse perform following simple steps:

1)    Open eclipse IDE. Click on Run -> Debug Configurations… Please refer to following image 


2)    Now Select Remote Java Application in the list and create new configuration. Please refer to the following image :


3)    This will open following window. Now browse for the application which you want to debug, fill up the IP address of remote machine on which you tomcat is running as a host and port number to which you want to connect. (Default port number of tomcat is 8080). 
Please refer to the following image:


4)    That’s it. Your debug configuration is ready. Now click of debug button. This will connect to the remote machine. To start debugging open the browser and go to your application. This will heat the breakpoints in eclipse.



“Failed to connect to remote VM. Connection refused.”



    Most of the time developer face “Failed to connect to remote VM. Connection refused” issue while debugging remotely. This means that eclipse refused to connect to the specified machine on the specified port number. There can be many reasons why you are facing this issue. Here I have listed some of them:
1)      Most probably may be your application is not running on the remote machine and hence you cannot connect to the machine. To check this out just restart the tomcat in debug mode and try to connect again.
2)      May be your firewall preventing you from connecting to the remote machine.
3)      May be host or port number are incorrect.