Introduction To Spring Framework
Introduction To Spring Framework
<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.
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>
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";
}
}
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() {
}
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;
}
@Column(name = "DIVISION")
public String getDivision() {
return division;
}
5. On src folder, create new xml for hibernate configuration (hibernate.cfg.xml), this file is
mapping all of model class we use
<hibernate-configuration>
<session-factory>
<mapping class="id.co.quadras.training.spring.model.Contact" />
</session-factory>
</hibernate-configuration>
<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>
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);
}
import id.co.quadras.training.spring.model.Employee;
import java.util.List;
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;
</body>
</html>
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);
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>
<html>
<body>
<h1>Tambah Pegawai</h1>
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>
END;
/
4. Run on server
1. Create model class (Division.java) as container for marshalled web service xml and json
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
}
@XmlElement
public String getFullName() {
return fullName;
}
@XmlElement
public String getShortName() {
return shortName;
}
@XmlElement
public String getJobDecription() {
return jobDecription;
}
@Override
public String toString() {
return "Division [Short Name=" + shortName + ", Full Division Name="
+ fullName + "]";
}
import id.co.quadras.training.spring.model.Division;
import java.util.List;
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;
}
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