Archive

Archive for February, 2014

Spring MVC – Hello World

February 26, 2014 Leave a comment

Berikut ini contoh aplikasi web Spring MVC hello world dengan zero annotation dengan tujuan memahami alur control dengan framework Spring MVC.
Structure project dengan editor yang digunakan Eclipse Helios.

Project Structure HelloWorld

Project Structure HelloWorld

  1. Definisikan DispatcherServlet

Fungsi dari DispatcherServlet adalah menerima semua request dan mendelegasikan request ke controller yang tepat untuk dilakukan pemrosesan. Pendefinisian DispatcherServlet dilakukan di web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<display-name>SpringMVC </display-name>

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

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

</web-app>

2. Definisikan Spring Bean Configuration

DispatcherServlet dengan nama “dispatcherServlet” digunakan untuk mendefinisikan file untuk memuat konfigurasi Spring MVC. By default, “dipatcherServlet” dengan “-servlet” sehingga nama file menjadi dispatcherServlet-servlet.xml

....
<bean name="/" class="com.mvc.controller.IndexController"></bean>
<bean name="/hello.do" class="com.mvc.controller.HalloController"></bean>

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

<property name="suffix">
<value>.jsp</value>
</property>
</bean>
....

Pada Spring bean configuration diatas terdapat  dua controller dan viewResolver. Controller adalah component yang dipanggil oleh Dispatcher Servlet untuk melakukan Business Logic. Sedangkan viewResolver melakukan mapping antara Logical name yang dihasilkan oleh controller dan Physical view location.

3.Spring Controller

IndexController.java

package com.mvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class IndexController extends AbstractController{

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
ModelAndView modelAndView = new ModelAndView("index");

return modelAndView;
}
}

HelloController.java

package com.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HalloController extends AbstractController{

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {

ModelAndView modelAndView = new ModelAndView("helloWorld");
return modelAndView;
}
}

4. View
index.jsp dan helloWorld.jsp hanya untuk menampilkan text static.

Jadi bagaimana alur control Spring MVC?

  • Request diterima DispatcherServlet.
  • DispatcherServlet meneruskan request ke controller
  • Controller memproses request dan mengembalikan model dan view
  • Model dan view diterima DispatcherServlet, kemudian diteruskan ke viewResolver
  • Return dari viewResolver diterima DispatcherServlet, kemudian diteruskan ke client sebagai response.

Referensi : dari berbagai sumber.
Semoga bermanfaat

Spring Auto Component Scanning

February 24, 2014 Leave a comment

Pada umumnya kita mendeklarasikan semua bean di file XML bean configuration, sehingga Spring container dapat mendeteksi bean tersebut. Spring sebenarnya dapat melakukan auto scan bean tersebut menggunakan annotation dan jadi lebih sederhana. Berikut ini example sederhana CRUD satu table ( menggunakan service dan dao layer ).

  • Table books
Book Table

Book Table

  • Model layer ( Book.java )


package com.spring.model;

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

@Entity
@Table(name="books")
public class Book {
@Id
@Column(name="id")
@GeneratedValue
private int id;

@Column(name="book_name")
private String bookName;

@Column(name="author")
private String author;

@Column(name="price")
private int price;

@Column(name="qty")
private int quantity;

public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookName() {
return bookName;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
}

  • DAO layer

BookDao interface ( BookDao.java )

package com.spring.dao;

import java.util.List;

import com.spring.model.Book;

public interface BookDao {
public void addBook(Book book);
public void updateBook(Book book);
public List<Book> listBooks();
public Book getBookById(Integer bookId);
public void removeBook(Integer id);
}

BookDaoImpl ( BookDaoImpl.java )

package com.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.spring.model.Book;

@Repository
public class BookDaoImpl implements BookDao{

@Autowired
private SessionFactory sessionFactory;

@Override
public void addBook(Book book) {

sessionFactory.getCurrentSession().save(book);
}

@Override
public void removeBook(Integer id) {
Book book = (Book)sessionFactory.getCurrentSession()
.load(Book.class, id);
if(null != book) {
sessionFactory.getCurrentSession().delete(book);
}
}

@Override
@SuppressWarnings("unchecked")
public List<Book> listBooks() {
return sessionFactory.getCurrentSession()
.createQuery("from Book").list();
}

@Override
public void updateBook(Book book) {
sessionFactory.getCurrentSession().update(book);
}

@Override
@SuppressWarnings("unchecked")
public Book getBookById(Integer bookId) {
Session session = sessionFactory.getCurrentSession();
List<Book> list = session.createQuery("from Book b where b.id = :bookId")
.setParameter("bookId", bookId)
.list();
return list.size() > 0 ?(Book)list.get(0): null;
}
}

  • Service layer

BookService interface ( BookService.java )

package com.spring.service;

import java.util.List;
import com.spring.model.Book;

public interface BookService {
public void addBook(Book book);
public void updateBook(Book book);
public Book getBookById(Integer bookId);
public List<Book> listBooks();
public void removeBook(Integer id);
}

BookServiceImpl ( BookServiceImpl.java )

package com.spring.service;
import java.util.List;

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

import com.spring.dao.BookDao;
import com.spring.model.Book;

@Service
public class BookServiceImpl implements BookService{
@Autowired
private BookDao bookDao;

@Transactional
public void addBook(Book book) {
bookDao.addBook(book);
}

@Transactional
public void removeBook(Integer id) {
bookDao.removeBook(id);
}

@Transactional
public List<Book> listBooks() {
return bookDao.listBooks();
}

@Transactional
public void updateBook(Book book) {
bookDao.updateBook(book);
}

@Transactional
public Book getBookById(Integer bookId) {
return bookDao.getBookById(bookId);
}
}

  • Main class


package com.spring.main;

import java.util.Iterator;
import java.util.List;

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

import com.spring.model.Book;
import com.spring.service.BookService;
import com.spring.service.BookServiceImpl;

public class Main {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBean.xml");
BookService bsImpl = (BookService) context.getBean("bookServiceImpl");

/*Insert*/
Book book = new Book();
book.setAuthor("JK Rowling");
book.setBookName("Harry Potter");
book.setPrice(100000);
book.setQuantity(100);
bsImpl.addBook(book);

/*Select*/
Book bookDua = bsImpl.getBookById(1);
System.out.println(bookDua.getId());
System.out.println(bookDua.getAuthor());
System.out.println(bookDua.getPrice());
System.out.println(bookDua.getQuantity());
System.out.println(bookDua.getBookName());

/*Update*/
Book bookTiga = bookDua;
bookTiga.setQuantity(11);
bsImpl.updateBook(bookTiga);

/*Select All */
List <Book> bookList = bsImpl.listBooks();
Iterator iter = bookList.iterator();
while(iter.hasNext()){
Book bookEmpat = (Book) iter.next();
System.out.println(bookEmpat.getAuthor());
System.out.println(bookEmpat.getBookName());
}
/*Delete*/
bsImpl.removeBook(1);

}
}

  • Bean configuration xml ( SpringBean.xml )


...
<context:annotation-config />
<context:component-scan base-package="com.spring" />

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

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

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.spring.model.Book</value>
</list>
</property>
</bean>
<tx:annotation-driven/>

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

  • db properties


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=

  • Project Structure
Project Structure

Project Structure

Pada Spring terdapat 4 type auto components scan annotation.

  1. @Component : Annotation bersifat generic yang dapat digunakan pada semua layer
  2. @Service : Annotation class pada service layer
  3. @Repository : Annotation class pada dao layer
  4. @Controller : Annotation class pada presentation layer ( digunakan biasanya di Spring MVC )

Secara umum 4 annotation hampir tidak ada perbedaan, namun untuk readability penggunaan annotation tersebut disesuaikan layer class.

Referensi : dari berbagai sumber.
Semoga bermanfaat.

Spring PropertyPlaceholderConfigurer

February 20, 2014 Leave a comment

Berikut ini example penggunaan PropertyPlaceholderConfigurer class, dalam case ini untuk koneksi database MySql.

db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=

Koneksi class

public class Koneksi {
private DriverManagerDataSource driverManager;

public void setDriverManager(DriverManagerDataSource driverManager) {
this.driverManager = driverManager;
}

public DriverManagerDataSource getDriverManager() {
return driverManager;
}

public void displayInfo(){
String url  = getDriverManager().getUrl();
String user = getDriverManager().getUsername();
String pass = getDriverManager().getPassword();
System.out.println("URL: "+url);
System.out.println("User: " +user);
System.out.println("Password: "+pass);
}

}

Bean Configuration

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

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

<bean id="connection" class="com.util.Koneksi">
<property name="driverManager">
<ref bean="dataSource"></ref>
</property>
</bean>

Result

Capture

Capture

Referensi : dari berbagai sumber.
Semoga bermanfaat.

Spring Bean Autowiring Dengan @Autowired Annotation

February 19, 2014 Leave a comment

Pada Spring framework, @Autowired annotation dapat digunakan untuk melakukan wire bean di setter method, constructor atau field/property. @Autowired annotation melakukan auto wire bean berdasar type data matching ( byType ).

Example.

Person class.

public class Person {

private  int id;
private  String name;
private  String address;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
}

Customer class.

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

public class Customer {

@Autowired
private Person person;
private String loyalty;

public void setLoyalty(String loyalty) {
this.loyalty = loyalty;
}
public String getLoyalty() {
return loyalty;
}

public void setPerson(Person person) {
this.person = person;
}
public Person getPerson() {
return person;
}

public void displayInfo(){
System.out.println("Id Customer: " +person.getId());
System.out.println("Name Customer: "+person.getName());
System.out.println("Address Customer: "+person.getAddress());
System.out.println("Loyalty Customer: "+getLoyalty());
}
}

Bean Configuration

...
<context:annotation-config />

<bean id="person" class="com.person.Person">
<property name="id" value="1" ></property>
<property name="name" value="Ben"></property>
<property name="address" value="Indonesia"></property>
</bean>

<bean id="customer" class="com.person.Person">
<property name="loyalty" value="Gold"></property>
</bean>
...

Result

Capture  Result

Capture Result

Referensi : dari berbagai sumber.
Semoga bermanfaat.

Spring Bean Autowiring

February 18, 2014 Leave a comment

Pada Spring framework, kita dapat wire bean secara otomatis dengan auto-wiring feature. Untuk melakukan tambahkan autowire attibute pada pada <bean>. Spring framework mendukung lima jenis auto-wiring.

  • byName
  • byType
  • Constructor
  • autoDetect
  • none (default)

Contoh

  • Autowiring byName

Circle class

public class Circle {
public void printShape() {
System.out.println("Circle Shape");
}
}

Shape class

public class Shape  {
private Circle circle;
public void setCircle(Circle circle) {
this.circle = circle;
}
public Circle getCircle() {
return circle;
}
}

Bean Configuration

...
<bean id="circle"class="com.shape.Circle" />
<bean id="shape"class="com.shape.Shape" autowire="byName"/>
...

Property circle pada Shape class di-inject dengan bean dengan id circle.

  • Autowiring byType

Rectangle class

public class Rectangle{
public void printShape() {
System.out.println("Rectangle Shape");
}
}

Shape class

public class Shape  {
private Rectangle myRectangle;
public void setRectangle(Rectangle rectangle) {
this.myRectangle = rectangle;
}
public Rectangle getRectangle() {
return myRectangle;
}
}

Bean Configuration

...
<bean id="rectangle" class="com.shape.Rectangle" />
<bean id="shape" class="com.shape.Shape" autowire="byType"/>
....

Property myRectangle pada Shape class di-inject dengan bean dengan type Rectangle.

  • Autowiring constructor

Shape class

public class Shape  {
private Rectangle myRectangle;
public Shape(Rectangle rectangle){
this.myRectangle = rectangle;
}
public Rectangle getRectangle() {
return myRectangle;
}
}

Bean Configuration

.....
<bean id="rectangle" class="com.shape.Rectangle" />
<bean id="shape" class="com.shape.Shape" autowire="constructor" />
.....

Secara umum sama dengan autowiring byType, yaitu men-inject property berdasar tipe property tersebut.  Jika autowiring byType melalui setter injection, autowiring constructor melalui constructor injection.

  • Autowiring autodetect

Autowiring ini bekerja dengan pertama melakukan autowiring constructor. Jika tidak berhasil, melakukan autowiring byType.

Referensi : dari berbagai sumber.
Semoga bermanfaat.

Dependency Injection Pada Spring Framework

February 16, 2014 Leave a comment

Pada Spring framework terdapat 2 jenis DI yaitu :

1. Setter Injection

2.Constructor Injection

Contoh.

Circle class.

package com.shape;

public class Circle {

public void printShape() {
System.out.println("Circle Shape");

}

}

Rectangle class.

package com.shape;

public class Rectangle{

public void printShape() {
System.out.println("Rectangle Shape");

}

}

Drawing class.

package com.shape;

public class Drawing {

private Circle circle; //Setter Injection
private Rectangle rectangle; Constructor Injection

public Drawing(Rectangle rectangleIn){
this.setRectangle(rectangleIn);
}
public void setCircle(Circle circleIn){
this.circle = circleIn;
}

public Circle getCicle(){
return circle;
}
public void setRectangle(Rectangle rectangle) {
this.rectangle = rectangle;
}
public Rectangle getRectangle() {
return rectangle;
}
}

Main class.

package com.main;

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

import com.shape.Drawing;

public class Main {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("BeanEx.xml");
Drawing drawing = (Drawing)context.getBean("drawing");

drawing.getCicle().printShape();
drawing.getRectangle().printShape();
}

}

Bean configuration file ( BeanEx.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:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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-3.2.xsd">

<bean id="rectangle" class="com.shape.Rectangle" />
<bean id="circle" class="com.shape.Circle" />

<bean id="drawing">
<constructor-arg>
<ref bean="rectangle" />
</constructor-arg>

<property name="circle">
<ref bean="circle" />
</property>
</bean>

</beans>

Project Structure

Project Structure


Referensi : dari berbagai sumber.

Semoga bermanfaat.