Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Friday, October 17, 2014

Spring Hibernate Dao Support CRUD Application


Spring (3) Hibernate (3) Dao Support CRUD Application

Scope : Develop an application with using Spring Hibernate DAO support.

Objective : Implement a Student management java application with CRUD functionality

Requirements:
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • My SQL Server 5.5

Step 1: Create a Java project In eclipse and named as "SpringSimpleStudent”.
File > New > Java project 

Add the following jars to your build path.
  • asm.jar
  • asm-attrs.jar
  • cglib-2.1.3.jar
  • commons-collections-2.1.1.jar
  • commons-logging-1.1.jar
  • dom4j-1.6.1.jar
  • hibernate3.jar
  • hibernate-annotations.jar
  • hibernate-commons-annotations.jar
  • hibernate-entitymanager.jar
  • javaee.jar
  • javax.persistence.jar
  • jstl.jar
  • mysql-connector.jar
  • servlet-api.jar
  • spring related jars...
Find below the project structure for our example.


Step 2: First we create the "Student" Domain class for this example.

/SpringSimpleStudent/src/com/prem/domain/Student.java

 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.prem.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {
 @Id
 @GeneratedValue
 private int id;

 @Column(name = "FIRSTNAME")
 private String firstName;

 @Column(name = "LASTNAME")
 private String lastName;

 @Column(name = "EMAIL")
 private String email;

 @Column(name = "CONTACTNO")
 private String phone;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}

Step 3: Create a "StudentDAO" interface and "StudentDAOImpl" class for to do the data base persistence.
StudentDAO class as below.

/SpringSimpleStudent/src/com/prem/dao/StudentDAO.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.prem.dao;

import java.util.List;

import com.prem.domain.Student;

public interface StudentDAO {

 public void saveStudent(Student student);

 public List<Student> getAllStudent();

 public Student getStudentById(int id);

 public int updateStudent(Student student);

 public int deleteStudent(int id);
}


And the StudentDAOImpl class as below.


/SpringSimpleStudent/src/com/prem/dao/impl/StudentDAOImpl.java 


 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
44
45
46
47
48
package com.prem.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.prem.dao.StudentDAO;
import com.prem.domain.Student;

public class StudentDAOImpl extends HibernateDaoSupport implements StudentDAO {

 @Autowired
 public void init(SessionFactory factory) {
  setSessionFactory(factory);
 }

 @Override
 @Transactional
 public void saveStudent(Student student) {
  getHibernateTemplate().save(student);
 }

 @Override
 public List<Student> getAllStudent() {
  return (List<Student>) getHibernateTemplate().loadAll(Student.class);
 }

 @Override
 public Student getStudentById(int id) {
  return (Student) getHibernateTemplate().get(Student.class, id);
 }

 @Override
 public int updateStudent(Student student) {
  getHibernateTemplate().update(student);
  return 0;
 }

 @Override
 public int deleteStudent(int id) {
  getHibernateTemplate().delete(getStudentById(id));
  return 0;
 }

}


Step 4: Now the time to create the "StudentService" interface and the "StudentServiceManager" class for manage the business logic.

The "StudentService" interface looks as below.


/SpringSimpleStudent/src/com/prem/service/StudentService.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.prem.service;

import java.util.List;

import com.prem.domain.Student;

public interface StudentService {
 public void saveStudentDetails(Student student);

 public List<Student> getAllStudents();

 public Student getStudentDeatilsById(int id);

 public int updateStudentDeatils(Student student);

 public int deleteStudentDetails(int id);
}
And the "StudentServiceManager" class as below.

/SpringSimpleStudent/src/com/prem/service/manager/StudentServiceManager.java


 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
package com.prem.service.manager;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.prem.dao.StudentDAO;
import com.prem.domain.Student;
import com.prem.service.StudentService;

public class StudentServiceManager implements StudentService {
 @Autowired
 StudentDAO studentDAO;

 @Override
 public void saveStudentDetails(Student student) {
  studentDAO.saveStudent(student);
 }

 @Override
 public List<Student> getAllStudents() {
  return studentDAO.getAllStudent();
 }

 @Override
 public Student getStudentDeatilsById(int id) {
  return studentDAO.getStudentById(id);
 }

 @Override
 public int updateStudentDeatils(Student student) {
  return studentDAO.updateStudent(student);
 }

 @Override
 public int deleteStudentDetails(int id) {
  return studentDAO.deleteStudent(id);
 }

}

Step 5: In this example we are going to define the data base access parameters in a "database.properties" properties file.

The "database.properties" file contains the following parameters as key value pairs.


/SpringSimpleStudent/src/database.properties


1
2
3
4
5
6
7
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.user=root
database.password=1234
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect
Step 6: Now the time comes to play with the spring configurations.
In this example I am not going to create any hibernate configuration file. Instead of that I already defined the domain class with the annotation.

/SpringSimpleStudent/src/spring-config.xml

The "spring-config" file looks as below.

 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
44
45
46
47
<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"
 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">
 <context:annotation-config />

 <bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="database.properties" />
 </bean>

 <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
  id="dataSource">
  <property name="driverClassName" value="${database.driver}"></property>
  <property name="url" value="${database.url}"></property>
  <property name="username" value="${database.user}"></property>
  <property name="password" value="${database.password}"></property>
 </bean>

 <bean
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
  id="sessionFactory">
  <property name="dataSource" ref="dataSource"></property>
  <property name="annotatedClasses">
   <list>
    <value>com.prem.domain.Student</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
   </props>
  </property>
 </bean>

 <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager"
  id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

 <bean id="dataDaoImpl" class="com.prem.dao.impl.StudentDAOImpl" />
 <bean id="studentDAO" class="com.prem.service.manager.StudentServiceManager" />
</beans>


That's all...  
Now the time to implement the Test class for this application. 

For this example I developed "StudentsOperationTest" class and its looks as below.


/SpringSimpleStudent/src/com/prem/test/StudentsOperationTest.java


 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.prem.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.prem.domain.Student;
import com.prem.service.StudentService;
import com.prem.service.manager.StudentServiceManager;

public class StudentsOperationTest {
 public static void main(String[] args) {
  
  ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-config.xml");
  StudentServiceManager studentManager = (StudentServiceManager)appContext.getBean("studentDAO");
  
  // Save 1st student details
  Student student = new Student();
  student.setEmail("test@tester.com");
  student.setFirstName("John");
  student.setLastName("Smith");
  student.setPhone("1234567890");
  studentManager.saveStudentDetails(student);
  
  System.out.println("------- First Student details added ---- " + student.getFirstName());
  
  // Save 2nd student details
  Student student2 = new Student();
  student2.setEmail("dinesh@gmail.com");
  student2.setFirstName("Dinesh");
  student2.setLastName("Karthik");
  student2.setPhone("1234543210");
  studentManager.saveStudentDetails(student2);
  System.out.println("------- Second Student details added ---- " + student2.getFirstName());
  
  // Get first student details
  Student firstStudent = studentManager.getStudentDeatilsById(1);
  
  // Get All students phone numbers
  List<Student> students = studentManager.getAllStudents();
  System.out.println("---------ALL STUDENTS PHONE NO ----------");
  for (Student stu : students) {
   System.out.println(stu.getFirstName() + "---" + stu.getPhone());
  }
  
  // Update firstStudent phone number
  firstStudent.setPhone("0001112222");
  studentManager.updateStudentDeatils(firstStudent);
  System.out.println("------- First Student details updated ---- " + firstStudent.getPhone());
  
  // Get All students phone numbers
  students = studentManager.getAllStudents();
  System.out.println("---------ALL STUDENTS PHONE NO ----------");
  for (Student stu : students) {
   System.out.println(stu.getFirstName() + "---" + stu.getPhone());
  }
  
  // Delete last student details
  studentManager.deleteStudentDetails(2);
  System.out.println("------- Second Student details deleted ---- ");
  
 }
}
Once you run the "StudentsOperationTest" class you able to see the following output from your java console.


 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
Oct 17, 2014 5:00:01 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: table not found: Student
Oct 17, 2014 5:00:01 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: table not found: Student
Oct 17, 2014 5:00:01 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: schema update complete
Oct 17, 2014 5:00:01 PM org.springframework.orm.hibernate3.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@29c58e] of Hibernate SessionFactory for HibernateTransactionManager
Hibernate: insert into Student (EMAIL, FIRSTNAME, LASTNAME, CONTACTNO) values (?, ?, ?, ?)
------- First Student details added ---- John
Hibernate: insert into Student (EMAIL, FIRSTNAME, LASTNAME, CONTACTNO) values (?, ?, ?, ?)
------- Second Student details added ---- Dinesh
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.FIRSTNAME as FIRSTNAME0_0_, student0_.LASTNAME as LASTNAME0_0_, student0_.CONTACTNO as CONTACTNO0_0_ from Student student0_ where student0_.id=?
Hibernate: select this_.id as id0_0_, this_.EMAIL as EMAIL0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.CONTACTNO as CONTACTNO0_0_ from Student this_
---------ALL STUDENTS PHONE NO ----------
John---1234567890
Dinesh---1234543210
Hibernate: update Student set EMAIL=?, FIRSTNAME=?, LASTNAME=?, CONTACTNO=? where id=?
------- First Student details updated ---- 0001112222
Hibernate: select this_.id as id0_0_, this_.EMAIL as EMAIL0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.CONTACTNO as CONTACTNO0_0_ from Student this_
---------ALL STUDENTS PHONE NO ----------
John---0001112222
Dinesh---1234543210
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.FIRSTNAME as FIRSTNAME0_0_, student0_.LASTNAME as LASTNAME0_0_, student0_.CONTACTNO as CONTACTNO0_0_ from Student student0_ where student0_.id=?
Hibernate: delete from Student where id=?
------- Second Student details deleted ---- 

- In this example I did not create the Student table in MySQL manually. The table automatically generated through hibernate. You able to see those entries from the console out put lines 3-6.




Tuesday, October 14, 2014

Spring MVC Security Login


Spring MVC Security Login


Spring MVC Security Login

Scope : In this example explained that how to handle the default Spring security with MVC.

Objective : The user able to login successfully if specify the correct password only.

Requirements:
  • Spring 3.0 
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • ApacheTomcat - 6.0.26

Step 1: Create a dynamic web project in eclipse and named as "SpringMVCLogin".
             File à New à Dynamic Web Project

             Lets prepare the project structure as below.



Step 2: Add all the spring and other related jars to WebContent\WEB-INF\lib. Please refer the default set of jars here (in step 3). In addition the following spring security jars added to the same lib directory in this example.
  • spring-security-config-3.0.5.RELEASE.jar
  • spring-security-core-3.0.5.RELEASE.jar
  • spring-security-web-3.0.5.RELEASE.jar
Step 3: The controller "LoginController" class created under the "com.prem.spring.controller" package.

/SpringMVCLogin/src/com/prem/spring/controller/LoginController.java

package com.prem.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

 @RequestMapping("/home")
 public ModelAndView getHome() {
  String welcomeNote = "Welcome to the Spring secure page...";
  return new ModelAndView("home", "welcomenote", welcomeNote);
 }
}

Step 4: In the "web.xml" need to specified the spring security filter. Find below the complete "web.xml" file for the reference. 

/SpringMVCLogin/WebContent/WEB-INF/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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">
 <display-name>SpringMVCLogin</display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>spring-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring-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/spring-dispatcher-servlet.xml,  
       /WEB-INF/spring-security.xml  
    </param-value>
 </context-param>

 <!-- Spring Security -->
 <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>


Step 5: For this example there are two spring-xxxxxx.xml's defined.

1. spring-dispatcher-servlet.xml - View resolver configured in the dispatcher file.
2. spring-security.xml - The user access credentials and roles defined.

/SpringMVCLogin/WebContent/WEB-INF/spring-dispatcher-servlet.xml


<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 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-3.0.xsd  
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:component-scan base-package="com.prem.spring.controller" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>

</beans>  

/SpringMVCLogin/WebContent/WEB-INF/spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"  
 xmlns:beans="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-3.0.xsd  
           http://www.springframework.org/schema/security  
           http://www.springframework.org/schema/security/spring-security.xsd">  
  
 <http auto-config="true">  
  <intercept-url pattern="/home*" access="ROLE_ADMIN" />  
 </http>  
  
 <authentication-manager>  
  <authentication-provider>  
   <user-service>  
    <user name="prem" password="premen" authorities="ROLE_ADMIN" />  
   </user-service>  
  </authentication-provider>  
 </authentication-manager>  
  
</beans:beans>



Step 6: Now the time to create the index & home jsp pages.

/SpringMVCLogin/WebContent/index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<% response.sendRedirect("home"); %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SpringMVCLogin</title>
</head>
<body>Welcome to Spring Security...
</body>
</html>

/SpringMVCLogin/WebContent/WEB-INF/pages/home.jsp


<html>
<head>
<title>Authenticated User</title>
</head>
<body>
 <center>
  <h1><u>Spring Security</u></h1>
  <h4>${welcomenote}</h4>
  <c:url value="/j_spring_security_logout" var="logoutUrl" />
  <a href="${logoutUrl}">Log Out</a>
 </center>
</body>
</html>

Step 7: Right click on the "SpringMVCLogin" project and go to Run As - Run on Server.

The initial screen looks as below.




Once user enter the wrong username or password, the error screen displayed as below.


If the user enter the correct username & password, the following success screen displayed.