0% found this document useful (0 votes)
194 views18 pages

Introduction To Spring Framework

The document provides steps to create a basic Spring web application using Eclipse and Tomcat. It describes how to configure the application context and dispatcher servlet, add controller classes and JSP pages. It also explains how to set up data access to a database using Hibernate, including creating entity classes, Hibernate configuration files, and integrating Hibernate with Spring.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
194 views18 pages

Introduction To Spring Framework

The document provides steps to create a basic Spring web application using Eclipse and Tomcat. It describes how to configure the application context and dispatcher servlet, add controller classes and JSP pages. It also explains how to set up data access to a database using Hibernate, including creating entity classes, Hibernate configuration files, and integrating Hibernate with Spring.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Introduction to Spring Framework

Basic Spring Web Application


1. Create web application project with Eclipse
 File -> New -> Others
 Choose Dynamic Web Project
 Input your project name, for example "spring-training"
 Choose "2.5" for Dynamic web module version
 Finish
2. Run web application that you created on server, we will use Apache Tomcat as Web
Server
 Right click your project, choose Run As -> Run On Server
3. Copy dependency library to WEB-INF/lib folder on your project
4. Refresh your project
5. Replace web.xml content with this new configuration :
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring Web MVC Application</display-name>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

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

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

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

</web-app>

6. Create one xml file named dispatcher-servlet.xml, it will contain all spring configuration
during our training.

1 Basic Spring Framework Training - Quadra Solution


<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"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

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

<context:component-scan base-package="id.co.quadras.training.spring" />


</beans>

7. Create controllers package in src folder, "id.co.quadras.training.spring.controller"


8. Create a normal Java class (HelloWorldController.java) at
"id.co.quadras.training.spring.controller",
package id.co.quadras.training.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloWorldController {
@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public String createForm(Model model) {
String message = "Hello World from Spring";
model.addAttribute("message", message);
return "helloWorld";
}
}

9. Create JSP file (helloWorld.jsp) in WEB-INF/pages directory


<html>
<body>
<h2>${message}</h2>
</body>
</html>

Project package structure should be like picture below.

2 Basic Spring Framework Training - Quadra Solution


10. Run in tomcat

3 Basic Spring Framework Training - Quadra Solution


Spring framework, data access using Hibernate
1. Create user springtraining in oracle, grant connect and resource to this user
2. Create table employee, this table will be use to our next steps
3. On your IDE, create new package for model class (id.co.quadras.training.spring.model)
4. Create new Java class (Employee.java)

4 Basic Spring Framework Training - Quadra Solution


package id.co.quadras.training.spring.model;

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

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {
private static final long serialVersionUID = -4279265281264354457L;
private String employeeId;
private String employeeName;
private String division;

public Employee() {
}

public Employee(String employeeName) {

this.employeeName = employeeName;
}

@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
@Column(name = "EMPLOYEE_ID", unique = true)
public String getEmployeeId() {
return this.employeeId;
}

public void setEmployeeId(String employeeId) {


this.employeeId = employeeId;
}

@Column(name = "EMPLOYEE_NAME", unique = true, nullable = false, length = 20)


public String getEmployeeName() {
return this.employeeName;
}

public void setEmployeeName(String employeeName) {


this.employeeName = employeeName;
}

@Column(name = "DIVISION")
public String getDivision() {
return division;
}

public void setDivision(String division) {


this.division = division;
}

5. On src folder, create new xml for hibernate configuration (hibernate.cfg.xml), this file is
mapping all of model class we use

5 Basic Spring Framework Training - Quadra Solution


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<mapping class="id.co.quadras.training.spring.model.Contact" />
</session-factory>
</hibernate-configuration>

6. Add xml configuration below to dispatcher-servlet.xml,


<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@//localhost:1521/soa" />
<property name="username" value="springtraining" />
<property name="password" value="rahasia" />
</bean>

<bean
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
id="sessionFactory">
<property name="dataSource" ref="dataSource" />
<property value="id.co.quadras.training.spring.model" name="packagesToScan" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>

7. Create DAO package (id.co.quadras.training.spring.dao)


8. Create new Java class in dao package (EmployeeDao.java), this class will handle all of our
communication between Employee model class and hibernate session

6 Basic Spring Framework Training - Quadra Solution


package id.co.quadras.training.spring.dao;

import id.co.quadras.training.spring.model.Employee;

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.stereotype.Repository;

@Repository("employeeDao")
public class EmployeeDao extends HibernateDaoSupport {
@Autowired
public void setDaoSessionFactory(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}

public List<Employee> getAllEmployee() {


List<Employee> list = getHibernateTemplate().find("from Employee");
return list;
}
}

9. Create service interface package (id.co.quadras.training.spring.service)


10. Create Java interface in this package (EmployeeService.java)
package id.co.quadras.training.spring.service;

import id.co.quadras.training.spring.model.Employee;

import java.util.List;

public interface EmployeeService {


public List<Employee> listAll();
}

11. Create service implement package (id.co.quadras.training.spring.service.impl)


12. Create java class that implemented employe service interface
(EmployeeServiceImpl.java)

7 Basic Spring Framework Training - Quadra Solution


package id.co.quadras.training.spring.service.impl;

import id.co.quadras.training.spring.dao.EmployeeDao;
import id.co.quadras.training.spring.model.Employee;
import id.co.quadras.training.spring.service.EmployeeService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;

@Transactional(readOnly = true)
public List<Employee> listAll() {
List<Employee> list = employeeDao.getAllEmployee();
return list;
}

13. All service layer and model layer is done, then we create presentation layer. Create a
class under controller package (EmployeeController.java)
package id.co.quadras.training.spring.controller;

import id.co.quadras.training.spring.model.Employee;
import id.co.quadras.training.spring.service.EmployeeService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;

@RequestMapping(value = "/employee/list", method = RequestMethod.GET)


public String list(Model model) {
List<Employee> list = employeeService.listAll();
model.addAttribute("list", list);
return "employee/list";
}
}

14. Now create jsp (list.jsp) under WEB-INF/pages/employee folder

8 Basic Spring Framework Training - Quadra Solution


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Daftar Pegawai</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Nama</th>
<th>Divisi</th>
</tr>
<c:forEach var="employee" items="${list}">
<tr>
<td>${employee.employeeId}</td>
<td>${employee.employeeName}</td>
<td>${employee.division}</td>
</tr>
</c:forEach>
</table>

</body>
</html>

Project structure show as picture below

15. Run it on server

9 Basic Spring Framework Training - Quadra Solution


Simple CRUD Application
Now we will add CRUD (Create, Retrieve, Update and Delete) capability in our web application, we will
modify couple code in our last task

1. Open EmployeeDao.java, then add code below


public void save(Employee employee) {
getHibernateTemplate().save(employee);
}

public void update(Employee employee) {


getHibernateTemplate().update(employee);
}

public void delete(final String employeeId) {


Employee employee = find(employeeId);
if(employee != null)
getHibernateTemplate().delete(employee);
}

public Employee find(String employeeId) {


List list = getHibernateTemplate().find("from Employee where employeeId=?", employeeId);
return (Employee) list.get(0);
}

2. Open EmployeeService.java, then add method interface for save, find by id and delete
public Employee getEmployeeById(String id);
public void deleteEmployee(String id);
public void saveEmployee(Employee employeee);

3. Implement all unimplemented method from EmployeeService.java


@Transactional(readOnly = true)
public Employee getEmployeeById(String id) {
return employeeDao.find(id);
}

public void saveEmployee(Employee employee) {


if (StringUtils.hasText(employee.getEmployeeId())) {
employeeDao.update(employee);
} else {
employeeDao.save(employee);
}

public void deleteEmployee(String employeeId) {


employeeDao.delete(employeeId);

4. In controller class (EmployeeController), add code below

10 Basic Spring Framework Training - Quadra Solution


@RequestMapping(value = "/employee/create", method = RequestMethod.GET)
public String createForm(Model model) {
model.addAttribute("employee", new Employee());
return "employee/create";
}

@RequestMapping(value = "/employee/edit/{employeeId}", method = RequestMethod.GET)


public String editForm(@PathVariable("employeeId") String employeeId,
Model model) {
Employee employee = employeeService.getEmployeeById(employeeId);
if (employee == null) {
model.addAttribute("employee", new Employee());
return "employee/create";
}
model.addAttribute("employee", employee);
return "employee/edit";
}

@RequestMapping(value = "/employee/delete/{employeeId}", method = RequestMethod.GET)


public String delete(@PathVariable("employeeId") String employeeId,
Model model) {
employeeService.deleteEmployee(employeeId);
return "redirect:/employee/list";
}

@RequestMapping(value = "/employee/save", method = RequestMethod.POST)


public String save(@ModelAttribute("employee") Employee employee,
Model model) {
employeeService.saveEmployee(employee);
return "redirect:/employee/list";
}

5. Create 2 jsps file under employee directory, one for edit (edit.jsp) and one for create
(create.jsp) form.
edit.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<body>
<h1>Ubah Pegawai</h1>
<c:url value="/employee/save" var="action" />
<form:form method="post" action="${action}" commandName="employee">
<form:hidden path="employeeId" />
<table>
<tr>
<td>Nama</td>
<td><form:input path="employeeName" /></td>
</tr>
<tr>
<td>Divisi</td>
<td><form:input path="division"/></td>
</tr>
</table>
<input type="submit" value="Simpan" name="submit" />
</form:form>
</body>
</html>

11 Basic Spring Framework Training - Quadra Solution


create.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<body>
<h1>Tambah Pegawai</h1>

<c:url value="/employee/save" var="action" />


<form:form method="post" action="${action}" commandName="employee">
<table>
<tr>
<td>Nama</td>
<td><form:input path="employeeName" /></td>
</tr>
<tr>
<td>Divisi</td>
<td><form:input path="division"/></td>
</tr>
</table>
<input type="submit" value="Simpan" name="submit" />
</form:form>
</body>
</html>

6. Modify list.jsp, add such button and link for delete and edit data
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Daftar Pegawai</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Nama</th>
<th>Divisi</th>
<th colspan="2"></th>
</tr>
<c:forEach var="employee" items="${list}">
<tr>
<td>${employee.employeeId}</td>
<td>${employee.employeeName}</td>
<td>${employee.division}</td>
<td><ahref="<c:url
value='/employee/edit/${employee.employeeId}'/>">Ubah</a></td>
<td><ahref="<c:url
value='/employee/delete/${employee.employeeId}'/>">Hapus</a></td>
</tr>
</c:forEach>
</table>
<a href="<c:url value='/employee/create'/>">Tambah</a>
</body>
</html>

7. Run project in server

12 Basic Spring Framework Training - Quadra Solution


13 Basic Spring Framework Training - Quadra Solution
Calling Store Procedure using Hibernate
In this task we will try to calling store procedure through hibernate. The scenario is: when user delete
employee data, it won't deleted totally from database. But, this data will be moved to another table in
database. In other word, we move the data.

1. Create a store procedure (deleteEmployee) in oracle.


CREATE OR REPLACE PROCEDURE SPRING_TRAINING.deleteEmployee(employeeId IN VARCHAR2)
IS
BEGIN
insert into employee_backup
select * from employee where employee_id=employeeId;
delete from employee where employee_id=employeeId;
commit;

END;
/

2. Create table backup (employee_backup), based on employee table


create table EMPLOYEE_BACKUP as
select * from EMPLOYEE
END;

3. Modify delete method in Employee Dao class, into this


public void delete(final String employeeId) {
getHibernateTemplate().execute(new HibernateCallback<Serializable>() {
public Serializable doInHibernate(org.hibernate.Session session)
throws HibernateException, SQLException {
session.beginTransaction();
session.createSQLQuery("CALL
deleteEmployee(:employeeId)").setString("employeeId", employeeId).executeUpdate();
session.getTransaction().commit();
session.close();
return null;
}
});
}

4. Run on server

14 Basic Spring Framework Training - Quadra Solution


Calling JAX-RS (JSON & XML) Web Service
Calling Rest web service is easy in Spring. Spring provide RestTemplate class for calling restful web
services. We will call some restful web services with JSON format to get master data

1. Create model class (Division.java) as container for marshalled web service xml and json

15 Basic Spring Framework Training - Quadra Solution


package id.co.quadras.training.spring.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "division")
public class Division {
String shortName;
String fullName;
String jobDecription;

public Division() {
// TODO Auto-generated constructor stub
}

public Division(String shortName, String fullName) {


this.shortName = shortName;
this.fullName = fullName;
}

@XmlElement
public String getFullName() {
return fullName;
}

public void setFullName(String fullName) {


this.fullName = fullName;
}

@XmlElement
public String getShortName() {
return shortName;
}

public void setShortName(String shortName) {


this.shortName = shortName;
}

@XmlElement
public String getJobDecription() {
return jobDecription;
}

public void setJobDecription(String jobDecription) {


this.jobDecription = jobDecription;
}

@Override
public String toString() {
return "Division [Short Name=" + shortName + ", Full Division Name="
+ fullName + "]";
}

2. Create an interface for retrieve web service (RestService.java)

16 Basic Spring Framework Training - Quadra Solution


package id.co.quadras.training.spring.service;

import id.co.quadras.training.spring.model.Division;

import java.util.List;

public interface RestService {


public List<Division> getAllDivisionJSON();
}

3. Create java class, and implement RestService.java


cpackage id.co.quadras.training.spring.service.impl;

import id.co.quadras.training.spring.model.Division;
import id.co.quadras.training.spring.service.RestService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestServiceImpl implements RestService {
private static final String JSON_URL = "http://localhost:8092/division/all/json";
private static final String XML_URL = "http://localhost:8092/division/single/xml";

@Override
public List<Division> getAllDivisionJSON() {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new
ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
List<Division> resultList = Arrays.asList(restTemplate.getForObject(
JSON_URL, Division[].class));
return resultList;
}

4. Modify EmployeeController.java, add this line in create and edit method


model.addAttribute("divisionList", restService.getAllDivisionJSON());

5. Modify create.jsp and edit.jsp, change division from input to select box, with code below
<form:select path="division" items="${divisionList}" itemLabel="fullName" itemValue="shortName" />

6. Run on server

17 Basic Spring Framework Training - Quadra Solution


18 Basic Spring Framework Training - Quadra Solution

You might also like