EclipseLink – 16 – Servlet & JSP & JPA & Bootstrap

Merhaba Arkadaslar
Onceki bolumlerde Java SE uygulamalari gerceklestirdik. Bu bolumde JPA uygulamamizi bir Servlet&JSP ile yapacagiz. Bu bolumde isin icine bir miktar Bootstrap da katacagiz.

Kullanacagimiz teknolojiler ;

  • Servlet&JSP
  • JPA/EclipseLink
  • Oracle/MySQL
  • Apache Tomcat
  • Bootstrap

Burada Bootstrap’i incelemeyecegiz zaten benim de pek bildigim bir konu degil 🙂
Ufak bir arastirma ile form icin ve datatable icin kullanabilecegim linkleri buldum. Bu konuda onerebileceginiz siteler varsa paylasirsaniz sevinirim.

Simdi biz uygulamamiza donelim. Oncelikle Dynamic Web Project olusturdum ve Maven Project olarak convert ediyorum. Burada bu konulardan bahsetmeyecegim Maven ve Servlet&JSP yazilarimda ilgili bilgileri bulabilirsiniz.

pom.xml

Onceki bolumlerde kullandigimiz pom.xml dosyasina benzer sekilde ayni dosyayi kullanabiliriz.
Burada ek olarak JSTL tag’i kullanacagimiz icin ilgili jar’lar icin dependency tanimlarini da ekleyelim.

...

	<repositories>
		<repository>
			<id>codelds</id>
			<url>https://code.lds.org/nexus/content/groups/main-repo</url>
		</repository>
	</repositories>

	<!-- 
	Last Update Date : 22.09.2018
	 -->
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.jpa -->
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>org.eclipse.persistence.jpa</artifactId>
			<version>2.7.3</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.12</version>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>jstl-api</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
		<dependency>
			<groupId>org.apache.taglibs</groupId>
			<artifactId>taglibs-standard-impl</artifactId>
			<version>1.2.5</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
		</dependency>

	</dependencies>
...

persistence.xml

persistence.xml dosyamiz yine META-INF klasorunde yer alacak. Bunun icin yeni bir source folder olusturabiliriz.

...
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
	<persistence-unit name="EmployeePersistenceUnit"
		transaction-type="RESOURCE_LOCAL">
		
		<class>model.Employee</class>
		
		<properties>
				
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa.schema" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="123456" />
			<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
		<!-- 					
			<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1520:xe" />
			<property name="javax.persistence.jdbc.user" value="Levent" />
			<property name="javax.persistence.jdbc.password" value="123456" />
				
		-->		
		</properties>	
	</persistence-unit>
</persistence>
...

Model

Oncelikle model sinifimizi olusturalim , onceki bolumlerde kullandigimiz Employee siniflarina benzer sekilde ;

Employee.java

package model;

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

@Entity
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.TABLE)
	private int id;
	private String name;
	private String surname;
	private int salary;

	public Employee() {
		super();
	}

	public Employee(String name, String surname, int salary) {
		super();
		this.name = name;
		this.surname = surname;
		this.salary = salary;
	}
        
        //getters and setters
...
}

Java SE uygulalarimizda oldugu gibi EntityManagerFactory ‘u kendimiz olusturmamiz gereklidir. Burada basit olarak bir Servlet ornegi yaptigimiz icin @PersistenceContext ve @PersistenceUnit annotationlarini kullanamayiz.

EntityManagerFactory objemizi olusturalim ;

EntityManagerUtility.java

package utility;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerUtility {

	private EntityManagerUtility() {
		throw new AssertionError();
		// Enforce noninstantiability with a private constructor
		// Joshua Bloch , Effective Java Item 04
	}

	private static EntityManagerFactory entityManagerFactory = Persistence
			.createEntityManagerFactory("EmployeePersistenceUnit");
	
	public static EntityManager getEntityManager() {
		return entityManagerFactory.createEntityManager();
	}

}

Data Access Object (DAO)

Data Access Object (DAO) design pattern yapisina uygun olarak interface ve siniflarimizi olusturalim. Onceki orneklerimizde ayni siniflari kullanmistik.

EmployeeDAO.java

package dao;

import java.util.List;

import model.Employee;

public interface EmployeeDAO {

	public Employee insertEmployee(Employee employee);

	public Employee findEmployee(int id);

	public List<Employee> findAllEmployees();

	public void removeEmployee(int id);
}

EmployeeDAOImpl.java

package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import model.Employee;
import utility.EntityManagerUtility;

public class EmployeeDAOImpl implements EmployeeDAO {

	@Override
	public Employee insertEmployee(Employee employee) {
		EntityManager entityManager = EntityManagerUtility.getEntityManager();
		entityManager.getTransaction().begin();
		entityManager.persist(employee);
		entityManager.getTransaction().commit();
		entityManager.close();
		return employee;
	}

	@Override
	public Employee findEmployee(int id) {
		EntityManager entityManager = EntityManagerUtility.getEntityManager();
		Employee employee = entityManager.find(Employee.class, id);
		entityManager.close();
		return employee;
	}

	@Override
	public List<Employee> findAllEmployees() {
		EntityManager entityManager = EntityManagerUtility.getEntityManager();
		TypedQuery<Employee> query = entityManager.createQuery("Select e from Employee e", Employee.class);
		List<Employee> employees = query.getResultList();
		entityManager.close();
		return employees;

	}

	@Override
	public void removeEmployee(int id) {

		EntityManager entityManager = EntityManagerUtility.getEntityManager();
		Employee employee = entityManager.find(Employee.class, id);
		if (employee != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(employee);
			entityManager.getTransaction().commit();
			entityManager.close();
		}

	}
}

Service

Service Layer icin sinifimizi yazalim , Service Layer’dan DAO sinifimiza ulasim sagliyoruz.

EmployeeService.java

package service;

import java.util.List;

import model.Employee;

public interface EmployeeService {
	
	public Employee insertEmployee(Employee employee);

	public Employee findEmployee(int id);

	public List<Employee> findAllEmployees();

	public void removeEmployee(int id);
}

EmployeeServiceImpl.java

package service;

import java.util.List;

import model.Employee;
import dao.EmployeeDAO;
import dao.EmployeeDAOImpl;

public class EmployeeServiceImpl implements EmployeeService {

	private EmployeeDAO employeeDAO;

	public EmployeeServiceImpl() {
		employeeDAO = new EmployeeDAOImpl();
	}

	@Override
	public Employee insertEmployee(Employee employee) {
		return employeeDAO.insertEmployee(employee);
	}

	@Override
	public Employee findEmployee(int id) {
		return employeeDAO.findEmployee(id);
	}

	@Override
	public List findAllEmployees() {
		return employeeDAO.findAllEmployees();

	}

	@Override
	public void removeEmployee(int id) {
		employeeDAO.removeEmployee(id);
	}
}

Controller

Simdi de Servlet sinifimizi yazalim.
@WebServlet annotation ile Servlet tanimini yapabiliriz. doPost metodunu inceleyecek olursak kullanicinin forma girdigi name, surname ve salary bilgilerini aliyoruz ve kayit olarak tabloya ekliyoruz. Daha sonrasinda tum kayitlari getirip request dispatch ediyoruz.

doGet metodunda ise id bilgisini aliyoruz ve kaydi sildikten sonra tekrar tum kayitlari getirip request dispatch ediyoruz.

Yani doPost metodunu kayit eklemek icin doGet metodunu kayit silmek icin kullaniyoruz. Tabi istersek farkli Servlet’ler kullanabiliriz.

EmployeeController.java

package controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.EmployeeService;
import service.EmployeeServiceImpl;
import model.Employee;

@WebServlet("/employeeController")
public class EmployeeController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private final EmployeeService employeeService = new EmployeeServiceImpl();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String employeeName = req.getParameter("name");
		String employeeSurname = req.getParameter("surname");
		int employeeSalary = Integer.parseInt(req.getParameter("salary"));

		Employee employee = new Employee(employeeName, employeeSurname, employeeSalary);
		employeeService.insertEmployee(employee);

		List<Employee> allEmployees = employeeService.findAllEmployees();
		req.setAttribute("allEmployees", allEmployees);
		RequestDispatcher dispatcher = req.getRequestDispatcher("employee.jsp");
		dispatcher.forward(req, resp);

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		int employeeId = Integer.parseInt(req.getParameter("employeeId"));
		employeeService.removeEmployee(employeeId);

		List<Employee> allEmployees = employeeService.findAllEmployees();
		req.setAttribute("allEmployees", allEmployees);
		RequestDispatcher dispatcher = req.getRequestDispatcher("employee.jsp");
		dispatcher.forward(req, resp);
	}

}

View

Yazinin basinda belirttigim gibi ornekte bootstrap kullandim. Isin Bootstrap css kismini bir koseye birakacak olursak basit olarak bir form olusturdum ve submit edildiginde HTTP POST istegi EmployeeController doPost tarafindan yakalanacak.

Bootstrap icin gerekli js ve css dosyalarimi WebContent/resources dizininde ilgili dosyalarda yer alacaktir.

....
<script src="resources/js/bootstrap.min.js"></script>
<link href="resources/css/bootstrap.min.css" rel="stylesheet">
...
<form class="form-horizontal" action="employeeController" method="POST">
...

c:forEach ile allEmployees request attribute’u yazdiralim. JSTL tag’i kullanabilmek icin oncelikle @taglib directive’i eklememiz gerektigini unutmayalim. Tabi unun icin pom.xml dosyamiza ilgili dependency tanimlarini eklememiz gereklidir.
employeeId bilgisini linke parametre olarek ekliyoruz. Boylece hangi Employee kaydi silinecek belirtmis oluruz.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
...
<c:forEach items="${allEmployees}" var="employee">
	<tr>
		<td><c:out value="${employee.name}" /></td>
		<td><c:out value="${employee.surname}" /></td>
		<td><c:out value="${employee.salary}" /></td>
		<td><a href="employeeController?employeeId=${employee.id}"
			class="btn btn-danger" type="button">Button</a></td>
	</tr>
</c:forEach>	

Run Application

employee.jsp dosyamizi calistiralim ve forma veri girerek yeni kayitlar ekleyelim.
Daha sonrasinda Delete butonu ile ilgili kaydi silebiliriz.

servlet and jpa form

Bu ornek daha da gelistirilebilir , update islemi ve validasyon islemi yapilabilir. Ornek olmasi acisindan bizim icin simdilik yeterli olacaktir.

Github source code :
injavawetrust.servlet.jpa

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply to Levent Erguder Cancel reply

Your email address will not be published. Required fields are marked *