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

Wednesday, October 22, 2014

Spring MVC + Hibernate CRUD Web Application


Spring (4) MVC + Hibernate (4) CRUD Web Application

Scope : Develop an web application with using Spring and Hibernate

Objective : Develop a student management application with CRUD functionality.

Requirements : 
  • Eclipe Java EE IDE
  • JDK 1.6
  • MySQL Server 5.5
Step 1 : Create a dynamic web project in eclipse and name it as "SpringSimpleStudentMVC". 

Step 2 : The data base properties defined as below. 

/SpringSimpleStudentMVC/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 3 : Create a "Student" domain class under the "com.prem.domain" package.

/SpringSimpleStudentMVC/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 4 : Create "StudentDAO" and "StudentDAOImpl" interface and class file under the "com.prem.dao" package.

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


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 void updateStudent(Student student);

 public void deleteStudent(int id);
}

The "StudentDAOImpl" class looks like as below.

/SpringSimpleStudentMVC/src/com/prem/dao/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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.prem.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.prem.domain.Student;

public class StudentDAOImpl implements StudentDAO {

 @Autowired
 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 @Transactional
 public void saveStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();
 }

 @Override
 public List<Student> getAllStudent() {
  Session session = sessionFactory.openSession();
  List<Student> studentList = session.createQuery("from Student").list();
  session.close();
  return studentList;
 }

 @Override
 public Student getStudentById(int id) {
  Session session = sessionFactory.openSession();
  return (Student) session.load(Student.class, new Integer(id));
 }

 @Override
 public void updateStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();

 }

 @Override
 @Transactional
 public void deleteStudent(int id) {
  Session session = sessionFactory.openSession();  
    Transaction tx = session.beginTransaction();  
    Student student = (Student) session.load(Student.class, id);  
    session.delete(student);  
    tx.commit();  
    Serializable ids = session.getIdentifier(student);  
    session.close();  
 }

}

Step 5: Now the time to create a "StudentService" interface and the "StudentServiceManger" class under the "com.prem.service" package.

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


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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 void updateStudentDeatils(Student student);

 public void deleteStudentDetails(int id);
}

And the StudentServiceManger class as below.

/SpringSimpleStudentMVC/src/com/prem/service/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
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.prem.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.prem.dao.StudentDAO;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Service
public class StudentServiceManager implements StudentService {
 
 @Autowired
 private StudentDAO studentDAO;

 public StudentDAO getStudentDAO() {
  return studentDAO;
 }

 public void setStudentDAO(StudentDAO studentDAO) {
  this.studentDAO = studentDAO;
 }

 @Override
 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
 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 void updateStudentDeatils(Student student) {
  studentDAO.updateStudent(student);
 }

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

}


Step 6 : Now we are going to create the "StudentController" class under the package "com.prem.controller".


/SpringSimpleStudentMVC/src/com/prem/controller/StudentController.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
67
package com.prem.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Controller
public class StudentController {

 @Autowired
 @Qualifier(value="studentService")
 StudentService studentService;

 public StudentService getStudentService() {
  return studentService;
 }

 public void setStudentService(StudentService studentService) {
  this.studentService = studentService;
 }

 @RequestMapping("form")
 public ModelAndView getForm(@ModelAttribute Student student) {
  return new ModelAndView("form");
 }

 @RequestMapping("register")
 @Transactional(readOnly=false)
 public ModelAndView registerUser(@ModelAttribute Student student) {
  studentService.saveStudentDetails(student);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("list")
 public ModelAndView getList() {
  List<Student> studentList = studentService.getAllStudents();
  return new ModelAndView("list", "studentList", studentList);
 }

 @RequestMapping("delete")
 public ModelAndView deleteUser(@RequestParam int id) {
  studentService.deleteStudentDetails(id);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("edit")
 public ModelAndView editUser(@RequestParam int id,
   @ModelAttribute Student student) {
  Student studentObject = studentService.getStudentDeatilsById(id);
  return new ModelAndView("edit", "studentObject", studentObject);
 }

 @RequestMapping("update")
 public ModelAndView updateUser(@ModelAttribute Student student) {
  studentService.updateStudentDeatils(student);
  return new ModelAndView("redirect:list");
 }

}


Step 7 : The spring configurations looks as below.

/SpringSimpleStudentMVC/WebContent/WEB-INF/mvc-dispatcher.xml


 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
67
68
69
70
71
72
73
74
75
76
77
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
  
 <context:annotation-config />
 <context:property-placeholder location="classpath:database.properties" />
 <context:component-scan base-package="com.prem.dao.impl" />
 <context:component-scan base-package="com.prem.service.manager" />
 <context:component-scan base-package="com.prem.controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <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.hibernate4.LocalSessionFactoryBean"
  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>
 
 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 
 <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"
  id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

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


Step 8 : Now the time to create the jsp files for student registration.

/SpringSimpleStudentMVC/WebContent/WEB-INF/pages/form.jsp

 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
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ 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=UTF-8">  
<title>Student Registration Form</title>  
</head>  
<body >  
 <center>  
  
  <div style="color: blue; font-size: 25px">Student  Registration Form</div>  
 
  <c:url var="userRegistration" value="saveUser.html" />  
  <form:form id="registerForm" modelAttribute="student" method="post" action="register">  
   <table width="500px" height="170px">  
    <tr>  
     <td><form:label path="firstName">First Name</form:label>  
     </td>  
     <td><form:input path="firstName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="lastName">Last Name</form:label>  
     </td>  
     <td><form:input path="lastName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="email">Email</form:label>  
     </td>  
     <td><form:input path="email" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="phone">Phone</form:label>  
     </td>  
     <td><form:input path="phone" />  
     </td>  
    </tr>  
    <tr>  
     <td></td>  
     <td><input type="submit" value="Register" /></td>  
    </tr>  
   </table>  
  </form:form>  
  
  <a href="list">View All Students List</a>  
 </center>  
</body>  
</html>  

Step 9 : Now the time to run and see the behavior of the application.

The student registration screen looks like as below.





And the student details screen looks like as below.




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.