@Secured pada controller spring boot

Bagaiamana sebuah controller pada aplikasi spring boot hanya bisa diakases oleh user yang mempunyai ROLE admin ?

Bismillah

misalnya kita mempunyai sebuah controller seperti ini :

@Controller
@RequestMapping("/kontak")
@Secured("ROLE_ADMIN")
public class KontakController {
@RequestMapping("/save")
public void save(){
}
}

Maka untuk mengakses controller tersebut hanya user-user yang mempunyai role admin saja yang bisa mengaksesnya, selain user tersebut maka akan muncul error Access is denied

Catatan :
aplikasi menggunakan spring boot, spring data jpa, spring security, thymeleaf dan database mariadb

Alhamdulillah

Advertisements

belajar spring boot

Spring boot,

Bismillah

q> Ini praktek dari halaman :
http://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html

q> Cek versi java

java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) Server VM (build 24.65-b04, mixed mode)

q> Cek versi maven

mvn -v
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-15T01:29:23+08:00)
Maven home: /usr/local/apache-maven/apache-maven-3.2.5
Java version: 1.7.0_67, vendor: Oracle Corporation
Java home: /opt/java/32/jdk1.7.0_67/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.13.0-24-generic", arch: "i386", family: "unix"

q> Buat folder boot

mkdir boot

q> Masuk ke dalam folder boot

cd boot

q> Buat file pom.xml

gedit pom.xml

q> Copy-paste code ini ke pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
</parent>

<!-- Additional lines to be added here... -->

</project>

q> Jalankan perintah ini

mvn package

Perintah di atas akan membuat folder target pada project.

q>Kemudian jalankan perintah ini

mvn dependency:tree

Pada saat ini, project belum ada dependency terhadap library lain. Seperti ini gambar tree dependency :

Selection_658

q> Tambahkan dependencies pada pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
q> Kemudian jalankan lagi perintah ini :
mvn dependency:tree

Pada saat ini sudah terlihat dependency, seperti pada gambar ini :

Selection_659

q> Ketikkan perintah ini untuk membuat struktur folder src/main/java, maven akan melakukan compile terhadap file java yang berada pada src/main/java

mkdir -p src/main/java

q> Buat file controller,

gedit src/main/java/Example.java 

q> Copy-paste code ini ke dalam file Example.java


import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

@RequestMapping("/")
String home() {
return "Hello World!";
}

public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}

}

q> Menjalankan aplikasi spring boot, pada posisi path /boot, jalankan perintah ini :

mvn spring-boot:run

q> Buka browser, dan akses alamat : localhost:8080

Selection_656

 

q> Struktur project folder dan file :
Selection_657

 

q> Menjadikan project spring-boot menjadi file jar

q> Tambahkan code ini pada file pom.xml tepat di bawah tag dependencies

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

q> Jalankan lagi perintah ini :

mvn package

q> Maka akan menghasilkan file myproject-0.0.1-SNAPSHOT.jar pada folder target

q> Jalankan file jar ini menggunakan perintah :

java -jar target/myproject-0.0.1-SNAPSHOT.jar

q> Kemudian buka browser dan akses halaman localhost:8080

q> Waw, projectnya menjadi file jar dan bisa dijalankan dengan java -jar

q> Project ini sudah di-upload ke github : https://github.com/saifiahmada/boot

Alhamdulillah

client side pagination dan sorting spring mvc datatables

membuat paging (pagination) dan sorting, spring mvc + datatables + bootstrap

Bismillah

q> Melanjukan tulisan sebelumnya
https://saifiahmada.wordpress.com/2014/12/27/client-side-validator-menggunakan-jquery-validation/

q> Hasil yang akan didapat pada tulisan kali ini  :

Selection_641

q> Langkah2 praktek :

1. buat bean entity User

package com.saifiahmada.maven.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Size;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotBlank;

@Entity
public class User {

	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid", strategy="uuid2")
	private String id;
	@Size(min=3, message="minimal 3 karakter")
	@NotBlank(message="tidak boleh kosong")
	private String username;

	@Size(min=3, message="minimal 3 karakter")
	@NotBlank(message="tidak boleh kosong")
	private String password;

	public String getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

2. buat interface UserRepository

package com.saifiahmada.maven.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.saifiahmada.maven.entity.User;

public interface UserRepository extends JpaRepository<User, String>  {

}

3. buat class UserService

package com.saifiahmada.maven.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.saifiahmada.maven.entity.Partner;
import com.saifiahmada.maven.entity.User;
import com.saifiahmada.maven.repository.UserRepository;

@Service
public class UserService {

	@Autowired
	private UserRepository userRepository;

	public List<User> findAll() {
		return userRepository.findAll();
	}

	public void save(User user) {
		userRepository.save(user);
	}

	public User findOne(String id) {
		return userRepository.findOne(id);
	}

	public void delete(String id) {
		userRepository.delete(id);
	}

}

4. buat class UserController

package com.saifiahmada.maven.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.saifiahmada.maven.entity.User;
import com.saifiahmada.maven.service.UserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;

	@RequestMapping(value="/form", method=RequestMethod.GET)
	public String form(Model model){
		model.addAttribute("entity", new User());
		return "user-form";
	}

	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(Model model){
		model.addAttribute("entities", userService.findAll());
		return "user-list";
	}

	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String add(@Valid @ModelAttribute("entity") User user, BindingResult result) {

		if (result.hasErrors()) {
			return "user-form";
		}
		userService.save(user);
		return "redirect:/user/form.html?success=true";
	}

	@RequestMapping(value="/edit/{id}")
	public String edit(@PathVariable("id") String id, Model model){
		model.addAttribute("entity", userService.findOne(id));
		return "user-form";
	}

	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable("id") String id, Model model){
		userService.delete(id);
		model.addAttribute("entity", new User());
		model.addAttribute("listModel", userService.findAll());
		return "user-form";
	}

}

5. buat file user-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp" %>

<a href="/user/form.html" class="btn btn-success">Add</a>
<br/>
<br/>

<table id="entity" class="table table-bordered table-hover table-striped">
	<thead>
		<tr>
			<th>Username</th>
			<th>Password</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${entities}" var="l">
			<tr>
				<td>${l.username }</td>
				<td>${l.password }</td>
				<td><a href="/user/edit/${l.id}.html">Edit</a></td>
				<td><a href="/user/delete/${l.id}.html">Delete</a></td>
			</tr>
		</c:forEach>
	</tbody>
</table>

<script type="text/javascript">
	$(document).ready(function() {
		var table = $('#entity').DataTable();
	});
</script>

6. buat file user-form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp"%>

<c:if test="${param.success eq true }">
	<div class="alert alert-success">Data berhasil disimpan</div>
</c:if>

<form:form commandName="entity" action="/user/add.html"
	cssClass="form-horizontal formUser">

	<c:if test="${ ! empty entity.id}">
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">Id</label>
			<div class="col-sm-10">
				<form:input path="id" cssClass="form-control" readonly="true" disabled="true" />
				<form:hidden path="id"/>
			</div>
		</div>
	</c:if>

	<div class="form-group">
		<label for="username" class="col-sm-2 control-label">Username</label>
		<div class="col-sm-10">
			<form:input path="username" cssClass="form-control" />
			<form:errors path="username" />
		</div>
	</div>

	<div class="form-group">
		<label for="password" class="col-sm-2 control-label">Password</label>
		<div class="col-sm-10">
			<form:input path="password" cssClass="form-control" />
			<form:errors path="password" />
		</div>
	</div>

	<input type="submit" value="Simpan" class="btn btn-success" />
	<a href="/user/form.html" class="btn btn-success">Reset</a>
	<a href="/user/list.html" class="btn btn-success">List</a>

</form:form>

<script type="text/javascript" >
	$(document).ready( function() {

		$(".formUser").validate(
			{
				rules : {
					username : {
						required : true,
						minlength : 3
					},
					password : {
						required : true,
						minlength : 3
					}

				},
				highlight : function (element) {
					$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
				},
				unhighlight : function (element) {
					$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
				}
			}
		);

	} );
</script>

7. tambahkan definition pada file general.xml

<definition name="user-list" extends="common">
		<put-attribute name="title" value="User List" />
		<put-attribute name="body" value="/WEB-INF/jsp/user-list.jsp" />
		<put-attribute name="current" value="user-list" />
	</definition>

	<definition name="part-form" extends="common">
		<put-attribute name="title" value="Part Form" />
		<put-attribute name="body" value="/WEB-INF/jsp/part-form.jsp" />
		<put-attribute name="current" value="part-list" />
	</definition>

8. tambahkan link untuk menu User pada file classic.jsp

<li class="${current == 'user-list' ? 'active' : '' }"><a href="/user/list.html">User</a></li>

9. pagination dan sorting pada sisi client (client side)

pada halaman user-list.jsp terdapat script javascript seperti ini

<script type="text/javascript">
	$(document).ready(function() {
		var table = $('#entity').DataTable();
	});
</script>

dari script di atas ada method DataTable(), method inilah yang membuat list user mempunyai paging dan sorting,
tetapi untuk script tersebut masih melakukan paging dan sorting dari sisi client (client side)

Berdasarkan http://www.datatables.net/
dijelaskan :

DataTables is a plug-in for the jQuery Javascript library.
It is a highly flexible tool, based upon the foundations of progressive enhancement,
and will add advanced interaction controls to any HTML table.

Untuk mengintegrasikan datatables dan bootstrap 3 (karena aplikasi ini menggunakan bootstrap 3) buka halaman ini
https://datatables.net/examples/styling/bootstrap.html

q> Untuk user-form.jsp juga sudah ada client validator

Selection_642

q> Tampilan ketika form berhasil disimpan

Selection_643

q> Sorting client side

Selection_644

Alhamdulillah

client side validator menggunakan jquery validation

Masih lanjut

Bismillah

q> Lanjutkan gan :
https://saifiahmada.wordpress.com/2014/12/27/server-side-validator-menggunakan-hibernate-validator/

q> Langkah-langkah :
1. buka halaman http://jqueryvalidation.org/

2. find (Ctrl+F) : ajax CDN
copy link http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js
paste pada file classic.jsp

Selection_640

3. tambahkan class “formCustomer” untuk tag <form:form> pada customer.jsp

<form:form commandName="customer" action="/customer/add.html"
cssClass="form-horizontal formCustomer">

4. tambahkan script javascript ini pada akhir customer.jsp

<script type="text/javascript">
$(document).ready( function() {
$(".formCustomer").validate(
{
rules : {
nama : {
required : true,
minlength : 3
},
alamat : {
required : true,
minlength : 5
},
noHp : {
required : true,
minlength : 11
}
},
highlight : function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight : function (element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
}
}

);

});
</script>

q> Hasil :

q> Hasil sebelum script highlight dan unhighlight ditambahkan pada javascript

Selection_638
q> Hasil setelah script highlight dan unhighlight ditambahkan pada javascript

Selection_639

Alhamdulillah

server side validator menggunakan hibernate validator

Server side validator, melanjutkan tulisan sebelumnya, aplikasi menggunakan framework spring mvc, spring data jpa dan hibernate entity manager

Bismillah

q> Melanjutkan tulisan ini :
https://saifiahmada.wordpress.com/2014/12/25/membuat-crud-sederhana-spring-mvc/

q> Langkah-langkah praktek :

1. tambahkan mvc namespace pada dispatcher-servlet
2. tambahkan tag <mvc:annotaion-driven /> pada dispatcher-servlet
3. tambahkan dependency hibernate validator 5.1.0 final pada pom.xml
4. tambahkan annotation pada domain object
5. tambahkan @Valid dan BindingResult pada parameter method add pada controller
6. tambahkan tag <form:errors> pada JSP
7. testing hasil

q> – – – mulai – – –

1. tambahkan mvc namespace pada dispatcher-servlet

Selection_637

2. tambahkan tag <mvc:annotaion-driven /> pada dispatcher-servlet

<mvc:annotaion-driven />

3. tambahkan dependency hibernate validator 5.1.0 final pada pom.xml

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
</dependency>

4. tambahkan annotation pada domain object

@Id
 @GeneratedValue
 private Integer id;
 
 @Size(min=3, message="minimal 3 karakter!")
 @NotBlank
 private String nama;
 
 @Size(min=5, message="minimal 5 karakter!")
 @NotBlank
 private String alamat;
 @Size(min=11, message="minimal 11 karakter!")
 @NotBlank
 private String noHp;

5. tambahkan @Valid dan BindingResult pada parameter method add pada controller

@RequestMapping(value = "/add", method=RequestMethod.POST)
public String add(Model model, @Valid @ModelAttribute("customer") Customer customer, BindingResult result){

logger.info("method add");

if (result.hasErrors()) {
model.addAttribute("customers", customerService.findAll());
return "customer";
}
customerService.save(customer);
return "redirect:/customer/awal.html?success=true";
}

6. tambahkan tag <form:errors> pada JSP

<form:errors path="nama" />
<form:errors path="alamat" />
<form:errors path="noHp" />

7. testing hasil

Selection_636

Ketika tombol simpan ditekan, maka akan muncul pesan bahwa minimal karakter harus dipenuhi

Alhamdulillah

membuat crud sederhana spring mvc

Create Read Update Delete menggunakan spring mvc, spring data jpa, hibernate entity manager, tiles, mysql

Bismillah

q> Melanjutkan tulisan sebelumnya :
https://saifiahmada.wordpress.com/2014/12/13/menambah-menu-stok/

q> Langkah-langkah praktek :
1. Buat bean entity Customer
2. Buat interface CustomerRepositroy
3. Buat class CustomerService
4. Tambahkan definition pada general.xml
5. Tambahkan menu pada classic.jsp
6. Buat file customer.jsp pada /WEB-INF/jsp/
7. Tambahkan class controller CustomerController

1. Buat bean entity Customer

package com.saifiahmada.maven.entity;

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

@Entity
public class Customer {

	@Id
	@GeneratedValue
	private Integer id;

	private String nama;

	private String alamat;

	private String noHp;

	public Integer getId() {
		return id;
	}

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

	public String getNama() {
		return nama;
	}

	public void setNama(String nama) {
		this.nama = nama;
	}

	public String getAlamat() {
		return alamat;
	}

	public void setAlamat(String alamat) {
		this.alamat = alamat;
	}

	public String getNoHp() {
		return noHp;
	}

	public void setNoHp(String noHp) {
		this.noHp = noHp;
	}

}

2. Buat interface CustomerRepositroy

package com.saifiahmada.maven.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.saifiahmada.maven.entity.Customer;

public interface CustomerRepository extends JpaRepository<Customer, Integer> {

}

3. Buat class CustomerService

package com.saifiahmada.maven.service;

import java.util.List;

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

import com.saifiahmada.maven.entity.Customer;
import com.saifiahmada.maven.repository.CustomerRepository;

@Service
public class CustomerService {

	@Autowired
	private CustomerRepository customerRepository;

	public void save(Customer customer) {
		customerRepository.save(customer);
	}

	public List<Customer> findAll() {
		return customerRepository.findAll();
	}

}

4. Tambahkan definition pada general.xml

	<definition name="customer" extends="common">
		<put-attribute name="title" value="Customer" />
		<put-attribute name="body" value="/WEB-INF/jsp/customer.jsp" />
		<put-attribute name="current" value="customer" />
	</definition>

5. Tambahkan menu pada classic.jsp

<li class="${current == 'customers' ? 'active' : '' }">
<a href="/customer/awal.html">Customer</a></li>

6. Buat file customer.jsp pada /WEB-INF/jsp/

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp"%>

<form:form commandName="customer" action="/customer/add.html"
	cssClass="form-horizontal">

	<c:if test="${ ! empty customer.nama }">
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">Id</label>
			<div class="col-sm-10">
				<form:input path="id" cssClass="form-control" readonly="true" disabled="true" />
				<form:hidden path="id"/>
			</div>
		</div>

	</c:if>

	<div class="form-group">
		<label for="nama" class="col-sm-2 control-label">Nama</label>
		<div class="col-sm-10">
			<form:input path="nama" cssClass="form-control" />
		</div>
	</div>

	<div class="form-group">
		<label for="alamat" class="col-sm-2 control-label">Alamat</label>
		<div class="col-sm-10">
			<form:input path="alamat" cssClass="form-control" />
		</div>
	</div>

	<div class="form-group">
		<label for="noHp" class="col-sm-2 control-label">No HP</label>
		<div class="col-sm-10">
			<form:input path="noHp" cssClass="form-control" />
		</div>
	</div>

	<input type="submit" value="Simpan" class="btn btn-success" />
	<a href="/customer/awal.html" class="btn btn-success">Reset</a>

</form:form>

<br />

<table class="table table-bordered table-hover table-striped">
	<thead>
		<tr>
			<th>Nama</th>
			<th>Alamat</th>
			<th>No. HP</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${customers}" var="c">
			<tr>
				<td>${c.nama }</td>
				<td>${c.alamat }</td>
				<td>${c.noHp }</td>
				<td><a href="/customer/edit/${c.id}.html">Edit</a></td>
				<td><a href="/customer/delete/${c.id}.html">Delete</a></td>
			</tr>
		</c:forEach>
	</tbody>
</table>

7. Tambahkan class controller CustomerController

package com.saifiahmada.maven.controller;

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

import com.saifiahmada.maven.entity.Customer;
import com.saifiahmada.maven.service.CustomerService;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

	@Autowired
	private CustomerService customerService;

	@ModelAttribute("customer")
	public Customer getCustomer(){
		return new Customer();
	}

	@RequestMapping(value="/awal")
	public String awal(Model model){
		model.addAttribute("customer", new Customer());
		model.addAttribute("customers", customerService.findAll());
		return "customer";
	}

	@RequestMapping(value = "/add", method=RequestMethod.POST)
	public String add(@ModelAttribute("customer") Customer customer){
		customerService.save(customer);
		return "redirect:/customer/awal.html";
	}

	@RequestMapping(value = "/edit/{id}")
	public String edit(@PathVariable("id") Integer id, Model model){
		Customer customer = customerService.findOne(id);
		model.addAttribute("customer", customer);
		model.addAttribute("customers", customerService.findAll());
		return "customer";
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id, Model model){
		customerService.delete(id);
		model.addAttribute("customers", customerService.findAll());
		return "customer";
	}

}

q> Jalankan jetty untuk melihat hasilnya

q> Awal menu Customer di-klik
Selection_632

q> Edit salah satu data, kemudian tekan tombol simpan

Selection_633

q> Masukkan data baru

Selection_634

q> Data tersimpan

Selection_635

Alhamdulillah

menambah menu stok

Menu stok akan coba kita tambahkan guys 😀

Bismillah

Melanjutkan tulisan sebelumnya :
https://saifiahmada.wordpress.com/2014/12/13/membuat-modal-bootstrap-untuk-form-simpan/

1. buat bean entity Stok

2. buat interface StokRepository

3. buat class StokService

4. buat class StokController

5. buat file stoklist.jsp pada /WEB-INF/jsp/stoklist.jsp

6. tambahkan definition untuk stok pada general.xml

7. tambahkan menu stok pada classic.jsp

8. Insert data stok secara manual

9. testing hasil

q> – – – mulai – – –

1. buat bean entity Stok


package com.saifiahmada.maven.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Stok {

@Id
private Integer id;

private Integer jumlah;

@OneToOne
@JoinColumn(name="id", referencedColumnName="id")
private Barang barang;

public Integer getId() {
return id;
}

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

public Integer getJumlah() {
return jumlah;
}

public void setJumlah(Integer jumlah) {
this.jumlah = jumlah;
}

public Barang getBarang() {
return barang;
}

public void setBarang(Barang barang) {
this.barang = barang;
}

}

2. buat interface StokRepository


package com.saifiahmada.maven.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.saifiahmada.maven.entity.Stok;

public interface StokRepository extends JpaRepository<Stok, Integer> {

}

3. buat class StokService


package com.saifiahmada.maven.service;

import java.util.List;

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

import com.saifiahmada.maven.entity.Stok;
import com.saifiahmada.maven.repository.StokRepository;

@Service
public class StokService {

@Autowired
private StokRepository stokRepository;

public void save(Stok stok){
stokRepository.save(stok);
}

public List<Stok> findAll(){
return stokRepository.findAll();
}

}

4. buat class StokController


package com.saifiahmada.maven.controller;

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 com.saifiahmada.maven.service.StokService;

@Controller
public class StokController {

@Autowired
private StokService stokService;

@RequestMapping("/stok/list")
public String list(Model model){
model.addAttribute("stoks", stokService.findAll());
return "stok";
}

}

5. buat file stoklist.jsp pada /WEB-INF/jsp/stoklist.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp" %>

<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>Kode</td>
<td>Barang</td>
<td>Stok</td>
</tr>
</thead>
<tbody>
<c:forEach items="${stoks}" var="stok">
<tr>
<td>${stok.barang.kode}</td>
<td>${stok.barang.nama}</td>
<td>${stok.jumlah}</td>
</tr>
</c:forEach>
</tbody>

</table>

6. tambahkan definition untuk stok pada general.xml

<definition name="stok" extends="common">
<put-attribute name="title" value="Stok" />
<put-attribute name="body" value="/WEB-INF/jsp/stoklist.jsp" />
<put-attribute name="current" value="stok" />
</definition>

7. tambahkan menu stok pada classic.jsp

<li class="${current == 'stok' ? 'active' : '' }"><a
href="/stok/list.html">Stok</a></li>

8. Insert data stok secara manual

Selection_627

9. testing hasil

Selection_628

Alhamdulillah