-Tôi sử dụng
- Server Glassfish 4.0
- Java EE 7
- IDE NetBeans
- Mysql Workbench
-Tạo database ABCShop nhưng tôi sẽ thay nó bằng database cũ là EJB vì tôi đã có một bài viết về cách tạo Resources cho Glassfish với database EJB.
-Vì sao phải tạo Resources ? vì Glassfish không tự tạo như Tomcat.
Chúng ta làm việc với database bằng Entity vì vậy nó cần Resources
Database Mysql Workbench
CREATE DATABASE `ejb` /*!40100 DEFAULT CHARACTER SET utf8 */;
CREATE TABLE `product` (
`id` varchar(45) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`price` float DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Sau khi tạo database thì các bạn tạo luôn Resources cho Glassfish tại đây=============PHẦN WEB SERVICE =============
Tạo project service tên: ABCShop
- Frameworks Hibernate 4.3.1
- Database connection jdbc:mysql://localhost:3306/ejb
(ejb là tên của database trong mysql của bạn)
Cấu hình cho hibernate.cfg.xml
hibernate.cfg.xml
Java Web Service 2016
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ejb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234567</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Add library connector JDBC mysql-connector-java-5.1.39-bin.jarTạo java class: NewHibernateUtil Package: util
Coppy toàn bộ nội dung code bên dưới vào NewHibernateUtil.java chú ý phần này chúng ta không cần code nó.
NewHibernateUtil.java
Java Web Service 2016
package util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class NewHibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
String hibernate_cfg_path = "hibernate.cfg.xml";
Configuration configuration = new Configuration().configure(hibernate_cfg_path);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public static Session getSessionAndBeginTransaction() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
return session;
}
public static Session commitCurrentSessions() throws Exception {
Session session = sessionFactory.getCurrentSession();
if (session.isOpen()) {
Transaction t = session.getTransaction();
if (t.isActive()) {
try {
t.commit();
} catch (Throwable ex) {
return session;
}
} else {
return session;
}
}
return null;
}
public static void rollBackCurrentSessions() {
rollBackSessions(sessionFactory.getCurrentSession());
}
public static void rollBackSessions(Session session) {
if (session != null) {
if (session.isOpen()) {
Transaction t = session.getTransaction();
try {
t.rollback();
} catch (Exception ex) {
ex.printStackTrace();
} catch (Throwable ta) {
} finally {
if (session.isOpen()) {
session.close();
}
}
}
}
}
public static void closeCurrentSessions() throws Exception {
Session session = sessionFactory.getCurrentSession();
if (session != null) {
try {
if (session.isOpen()) {
session.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Sau đó tạo entity database tên Package: modelTạo class: ProductDao Package: dao
ProductDao.java
Java Web Service 2016
package dao; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import model.Product; import org.hibernate.Query; import org.hibernate.Session; import util.NewHibernateUtil; /** * * @author Lonely */ public class ProductDao { public List<Product> findAll() { Session session = session = NewHibernateUtil.getSessionAndBeginTransaction(); try { Query query = session.createQuery("SELECT p FROM Product p"); return query.list(); } catch (Exception e) { NewHibernateUtil.rollBackSessions(session); } finally { try { NewHibernateUtil.commitCurrentSessions(); } catch (Exception ex) { Logger.getLogger(ProductDao.class.getName()).log(Level.SEVERE, null, ex); } finally { try { NewHibernateUtil.closeCurrentSessions(); } catch (Exception ex) { Logger.getLogger(ProductDao.class.getName()).log(Level.SEVERE, null, ex); } } } return null; } public boolean insert(Product p) { Session session = session = NewHibernateUtil.getSessionAndBeginTransaction(); try { Product p1 = new Product(); p1.setId(p.getId()); p1.setName(p.getName()); p1.setPrice(p.getPrice()); p1.setQuantity(p.getQuantity()); session.persist(p1); return true; } catch (Exception e) { NewHibernateUtil.rollBackSessions(session); } finally { try { NewHibernateUtil.commitCurrentSessions(); } catch (Exception ex) { Logger.getLogger(ProductDao.class.getName()).log(Level.SEVERE, null, ex); } finally { try { NewHibernateUtil.closeCurrentSessions(); } catch (Exception ex) { Logger.getLogger(ProductDao.class.getName()).log(Level.SEVERE, null, ex); } } } return false; } public boolean update(String id, int quantity) { Session session = session = NewHibernateUtil.getSessionAndBeginTransaction(); try { String hql = "UPDATE Product SET quantity = :quantity WHERE id = :id"; Query query = session.createQuery(hql); query.setParameter("id", id); query.setParameter("quantity", quantity); query.executeUpdate(); return true; } catch (Exception e) { NewHibernateUtil.rollBackSessions(session); } finally { try { NewHibernateUtil.commitCurrentSessions(); } catch (Exception ex) { Logger.getLogger(ProductDao.class.getName()).log(Level.SEVERE, null, ex); } finally { try { NewHibernateUtil.closeCurrentSessions(); } catch (Exception ex) { Logger.getLogger(ProductDao.class.getName()).log(Level.SEVERE, null, ex); } } } return false; } }
Tạo service: ProductWebService Pakage: service
Chuyển qua Design
- Xóa Operations hello
- Add Operations getAllProducts, addProduct, sellProduct
Chú ý: phần này các bạn cần làm việc bằng Design để Generate code để khi Deploy tránh lỗi
Quay lại chế độ code Source import tất cả bằng Ctrl + Shift + i Click project: Clear and build > Deploy > Run
Nếu bạn gặp lỗi đừng quá lo lắng!
Nếu các bạn gặp lỗi như trên hình fix lỗi như sau và Clean and Build lại:
Click vào project ABCShop và Run
===============PHẦN WEB CLIENT==============Tiếp theo chúng ta lấy đường dẫn WSDL này để tạo Web Service Client có tên ABCShop-Client
http://localhost:8080/ABCShop/ProductWebService?wsdl
Xóa index.html và tạo
- product.jsp
- index,jsp
- sell.jsp
product.jsp
Java Web Service 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add new product</title>
<!-- main JS libs -->
<script src="js/libs/modernizr.min.js"></script>
<script src="js/libs/jquery-1.10.0.js"></script>
<script src="js/libs/jquery-ui.min.js"></script>
<script src="js/libs/bootstrap.min.js"></script>
<!-- Style CSS -->
<link href="css/bootstrap.css" media="screen" rel="stylesheet">
<link href="style.css" media="screen" rel="stylesheet">
<script src="js/general.js"></script>
<!--End template-->
<!--Validate Boostrap 3-->
<script src="http://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/validate.css">
<!--End Validate Boostrap 3-->
</head>
<body>
<div class="container_fix">
<div class="form_fix">
<!--table + form-->
<form action="ProductServlet" method="Post" id="contact_form">
<div class="field_text">
<div class="form-group form-group_fix">
Id product
<input type="text" name="id" placeholder="Enter id" class="form-control" />
</div>
<div class="form-group form-group_fix">
Name product
<input type="text" name="name" placeholder="Enter name" class="form-control" />
</div>
<div class="form-group form-group_fix">
Price product
<input type="text" name="price" placeholder="Enter price" class="form-control" />
</div>
<div class="form-group form-group_fix">
Quantity product
<input type="number" name="quantity" placeholder="Enter quantity" class="form-control" />
</div>
<span class="btn btn-large btn-green"><input type="submit" value="Add New" /></span>
</form>
</div>
<!--end table +form-->
<div class="message">
<c:if test="${not empty message or error}">
<!--Note-->
<div class="comment-list styled clearfix">
<ol>
<li class="comment">
<div class="comment-body">
<div class="comment-arrow"></div>
<div class="comment-avatar">
<div class="avatar">
<img src="images/icon-login.gif" alt=""/>
</div>
</div>
<div class="comment-text">
<div class="comment-author clearfix">
<a href="#" class="link-author">
<c:if test="${not empty message}">
<font color="#bd1313"><c:out value="${requestScope.message}"/></font>
</c:if>
</a>
</div>
<!-- <div class="comment-entry">
<c:if test="${not empty error }">
<font color="#bd1318"><c:out value="${requestScope.error}"/></font>
</c:if>
</div>-->
</div>
<div class="clear"></div>
</div>
</li>
</ol>
</div>
</c:if>
</div>
</div>
<!--endNote-->
<!--Validate Boostrap 3-->
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>
<script src="js/validate.js"></script>
<!--End Boostrap 3-->
</body>
</html>
index.jsp
Java Web Service 2016
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show Product</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style>
.table{
background-color: #bcdcea;
margin: auto;
padding: 5px;
width: 90%;
}
</style>
<script src="js/libs/modernizr.min.js"></script>
<script src="js/libs/jquery-1.10.0.js"></script>
<script src="js/libs/jquery-ui.min.js"></script>
<script src="js/libs/bootstrap.min.js"></script>
<link href="css/bootstrap.css" media="screen" rel="stylesheet">
<link href="style.css" media="screen" rel="stylesheet">
<script src="js/general.js"></script>
<!--End template-->
<!--Validate Boostrap 3-->
<script src="http://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/validate.css">
<!--End Validate Boostrap 3-->
</head>
<body>
<div class="container_fix">
<!--login logout-->
<div class="form_fix">
<a href="product.jsp"><input type="button" value="Add New Product" /> </a>
</div>
<!--messages-->
<div class="message">
<c:if test="${not empty message}">
<div class="comment-list styled clearfix">
<ol>
<li class="comment">
<div class="comment-body">
<div class="comment-arrow"></div>
<div class="comment-avatar">
<div class="avatar">
<img src="images/messages.png" alt=""/>
</div>
</div>
<div class="comment-text">
<div class="comment-author clearfix">
<a href="#" class="link-author">
<font color="#bd1313">${requestScope.message}</font>
</a>
</div>
<div class="comment-entry">
<font color="#bd1353">
<c:choose>
<c:when test="${not empty items}">
----------001-------List not empty----
</c:when>
<c:otherwise>
----------002-------List empty----
</c:otherwise>
</c:choose>
</font>
</div>
</div>
<div class="clear"></div>
</div>
</li>
</ol>
</div>
</c:if>
</div>
<!--endContainer-->
<div class="bang_nhatky">
<c:if test="${not empty items}">
<!--Table 1-->
<table border="1" class="table table-hover" >
<tr>
<th>ID.</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sell</th>
<!--<th>Birth</th>-->
</tr>
<tbody>
<c:forEach var="it" items="${items}">
<tr>
<td class="active"><c:out value="${it.id}"/> </td>
<td class="info"><c:out value="${it.name}"/></td>
<td class="danger"><c:out value="${it.price}"/></td>
<td class="success" style="width: 100px;"><c:out value="${it.quantity}"/> </td>
<td class="warning" style="width: 30px;"><span class="btn btn-hover btn-white"><a href="sellServlet"><input type="button" value="Sell"/></a> </span></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</div>
</div>
<!--Validate Boostrap 3-->
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>
<script src="js/validate.js"></script>
<!--End Boostrap 3-->
</body>
</html>
sell.jsp
Java Web Service 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sell Product</title>
<!-- main JS libs -->
<script src="js/libs/modernizr.min.js"></script>
<script src="js/libs/jquery-1.10.0.js"></script>
<script src="js/libs/jquery-ui.min.js"></script>
<script src="js/libs/bootstrap.min.js"></script>
<!-- Style CSS -->
<link href="css/bootstrap.css" media="screen" rel="stylesheet">
<link href="style.css" media="screen" rel="stylesheet">
<script src="js/general.js"></script>
<!--End template-->
<!--Validate Boostrap 3-->
<script src="http://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/validate.css">
<!--End Validate Boostrap 3-->
</head>
<body>
<div class="container_fix">
<div class="form_fix">
<!--table + form-->
<form action="sellServlet" method="Post" id="contact_form">
<div class="field_text">
<div class="form-group form-group_fix">
ID Product:
<select name="id">
<option value="0" selected>(please select id)</option>
<c:forEach var="it1" items="${items}">
<option value="${it1.id}" /><c:out value="${it1.id}"/> </option>
</c:forEach>
</select>
</div>
<div class="form-group form-group_fix">
Quantity:
<input type="number" name="quantity" placeholder="Enter quantity" class="form-control" />
</div>
<span class="btn btn-large btn-green"><input type="submit" value="Sell" name="action"/></span>
</form>
</div>
<!--end table +form-->
<div class="message">
<c:if test="${not empty message or error}">
<!--Note-->
<div class="comment-list styled clearfix">
<ol>
<li class="comment">
<div class="comment-body">
<div class="comment-arrow"></div>
<div class="comment-avatar">
<div class="avatar">
<img src="images/icon-login.gif" alt=""/>
</div>
</div>
<div class="comment-text">
<div class="comment-author clearfix">
<a href="#" class="link-author">
<c:if test="${not empty message}">
<font color="#bd1313"><c:out value="${requestScope.message}"/></font>
</c:if>
</a>
</div>
<c:if test="${not empty error }">
<font color="#bd1318"><c:out value="${requestScope.error}"/></font>
</c:if>
</div>
<div class="clear"></div>
</div>
</li>
</ol>
</div>
</c:if>
</div>
</div>
<!--endNote-->
<!--Validate Boostrap 3-->
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>
<script src="js/validate.js"></script>
<!--End Boostrap 3-->
</body>
</html>
Tạo Servlet: ProductServlet Package: controller
Kéo thả hai phương thức đó vào ProductServlet
ProductServlet.java
Java Web Service 2016
package controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.WebServiceRef; import service.Product; import service.ProductWebService_Service; /** * * @author Lonely */ public class ProductServlet extends HttpServlet { @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/ABCShop/ProductWebService.wsdl") private ProductWebService_Service service; //Xóa hết những phần không liên quan và để lại methd doPost như bên dưới @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get value from input String id = request.getParameter("id"); String name = request.getParameter("name"); String price = request.getParameter("price"); String quantity = request.getParameter("quantity"); //Setter to model product Product p = new Product(); p.setId(id); p.setName(name); p.setPrice(Float.parseFloat(price)); p.setQuantity(Integer.parseInt(quantity)); //Boolean add and get list if (addProduct(p)) { if (getAllProducts() != null) { request.setAttribute("items", getAllProducts()); request.getRequestDispatcher("index.jsp").forward(request, response); } request.setAttribute("message", "Error get list!"); request.getRequestDispatcher("product.jsp").forward(request, response); } request.setAttribute("message", "Error add the new product!"); request.getRequestDispatcher("product.jsp").forward(request, response); } private boolean addProduct(service.Product p) { service.ProductWebService port = service.getProductWebServicePort(); return port.addProduct(p); } private java.util.List<service.Product> getAllProducts() { service.ProductWebService port = service.getProductWebServicePort(); return port.getAllProducts(); } }
Di chuyển kéo thả các method vào sellServlet
sellServlet.java
Java Web Service 2016
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceRef;
import service.ProductWebService_Service;
/**
*
* @author Lonely
*/
public class sellServlet extends HttpServlet {
@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/ABCShop/ProductWebService.wsdl")
private ProductWebService_Service service;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Check get list
if (getAllProducts() != null) {
//Get id to combobox by list
request.setAttribute("items", getAllProducts());
request.getRequestDispatcher("sell.jsp").forward(request, response);
} else {
request.setAttribute("message", "Error get list product!");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get value from input
String id = request.getParameter("id");
String quantity = request.getParameter("quantity");
//Boolean update a new quantity product by id
if (sellProduct(id, Integer.parseInt(quantity))) {
if (getAllProducts() != null) {
request.setAttribute("items", getAllProducts());
request.getRequestDispatcher("index.jsp").forward(request, response);
}
request.setAttribute("message", "Error get list product!");
request.getRequestDispatcher("product.jsp").forward(request, response);
}
request.setAttribute("message", "Error insert product!");
request.getRequestDispatcher("product.jsp").forward(request, response);
}
private boolean sellProduct(java.lang.String id, int quantity) {
service.ProductWebService port = service.getProductWebServicePort();
return port.sellProduct(id, quantity);
}
private java.util.List<service.Product> getAllProducts() {
service.ProductWebService port = service.getProductWebServicePort();
return port.getAllProducts();
}
}
Trước khi test chúng ta cài đặt mặc định project ABCShop-Client như sau rồi test:
Click chuột phải chọn Properties ABCShop-Client
Clean and build > Deploy > Run project client testRun test
Chưa có css + image các bạn tải project ở phía dưới và vào phần ABCShop-Client > web coppy phần khoanh đỏ ảnh bên dưới
Chuyển sang project ABCShop-Client paste vào Web Pages như hình dưới
Run lại project sẽ được như hình bên dưới! Nếu add new product mà gặp lỗi như hình bên dưới này thì các bạn xem lại file hibernate.cfg.xml hoặc có thể coppy trong project download bên dưới
Severe: No CurrentSessionContext configured!
org.hibernate.HibernateException: No CurrentSessionContext configured!
Download zip (import Netbeans)
ABCShop.zip - ABCShop-Client.zip
ABCShop.zip - ABCShop-Client.zip
0 nhận xét:
Post a Comment