Ở bài này chúng ta sẽ thực hiện công việc
Login > Insert > Update > Delete
- Server Glassfish 4.0
- Version Java EE 7
- IDE Netbeans
- 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.jar
Tạ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; } }
Tiếp theo tạo Datasource cho Glassfish
Sau đó tạo entity database
Tạo User xong chúng ta nhớ quay lại hibernate.cfg.xml thêm mapping User này
Tạo class: UserDao Package: dao
UserDao.java
Java Web Service 2016
package dao;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.User;
import org.hibernate.Query;
import org.hibernate.Session;
import util.NewHibernateUtil;
/**
*
* @author Lonely
*/
public class UserDao {
public boolean checkLogin(String username, String password) {
Session session = NewHibernateUtil.getSessionAndBeginTransaction();
try {
String sql = "SELECT u from User u where u.username=:username and u.password=:password";
Query query = session.createQuery(sql);
query.setParameter("username", username);
query.setParameter("password", password);
List<User> list = query.list();
if (list.size() == 1) {
session.close();
return true;
}
} catch (Exception e) {
NewHibernateUtil.rollBackSessions(session);
} finally {
try {
NewHibernateUtil.commitCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
NewHibernateUtil.closeCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return false;
}
public List<User> findAll() {
Session session = NewHibernateUtil.getSessionAndBeginTransaction();
try {
Query query = session.createQuery("SELECT u from User u");
return query.list();
} catch (Exception e) {
NewHibernateUtil.rollBackSessions(session);
} finally {
try {
NewHibernateUtil.commitCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
NewHibernateUtil.closeCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public boolean insert(String username, String password) {
Session session = NewHibernateUtil.getSessionAndBeginTransaction();
try {
User user = new User();
user.setUsername(username);
user.setPassword(password);
session.persist(user);
return true;
} catch (Exception e) {
NewHibernateUtil.rollBackSessions(session);
} finally {
try {
NewHibernateUtil.commitCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
NewHibernateUtil.closeCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return false;
}
public boolean update(String username, String password) {
Session session = NewHibernateUtil.getSessionAndBeginTransaction();
try {
String hql = "UPDATE User SET password = :password WHERE username = :username";
Query query = session.createQuery(hql);
query.setParameter("username", username);
query.setParameter("password", password);
query.executeUpdate();
return true;
} catch (Exception e) {
NewHibernateUtil.rollBackSessions(session);
} finally {
try {
NewHibernateUtil.commitCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
NewHibernateUtil.closeCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return false;
}
public boolean delete(String username) {
Session session = NewHibernateUtil.getSessionAndBeginTransaction();
try {
String hql = "DELETE FROM User WHERE username = :username";
Query query = session.createQuery(hql);
query.setParameter("username", username);
query.executeUpdate();
return true;
} catch (Exception e) {
NewHibernateUtil.rollBackSessions(session);
} finally {
try {
NewHibernateUtil.commitCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
NewHibernateUtil.closeCurrentSessions();
} catch (Exception ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return false;
}
}
Tạo service: UserWebService Pakage: service
Chuyển qua Design
- Xóa Operations hello
- Add Operation checkLogin, insertUser, updateUser, deleteUser
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
Clean and Build > Deploy > Run project
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:
Nếu không gặp lỗi này thì bạn là người may mắn và tiếp tục DeployClick vào project ServiceSoap và Run
==============PHẦN WEB CLIENT=============
Tiếp theo chúng ta lấy đường dẫn này để tạo Web Service Client có tên ServiceSoapClient
http://localhost:8080/ServiceSoap/UserWebService?wsdl
Xóa index.html và tạo
- login.jsp
- index,jsp
- insert.jsp
login.jsp
Java Web Service 2016
<%--
Document : login
Created on : Dec 15, 2016, 1:35:08 PM
Author : Lonely
--%>
<%@ 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>JSP Page</title>
</head>
<body>
<h1>Login!</h1>
<form action="LoginServlet" method="Post">
<input type="text" name="username"/><br/>
<input type="password" name="password"/><br/>
<input type="submit" value="Login" />
</form>
<c:if test="${not empty message}">
<font color="red">${requestScope.message}</font>
</c:if>
</body>
</html>
index.jsp
Java Web Service 2016
<%--
Document : login
Created on : Dec 14, 2016, 8:22:37 PM
Author : Lonely
--%>
<%@ 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>JSP Page</title>
</head>
<body>
<c:choose>
<c:when test="${not empty USER}"><h1>Welcome ${requestScope.USER}<a href="LoginServlet">Logout</a></h1></c:when>
<c:otherwise> <a href="login.jsp">Login</a></c:otherwise>
</c:choose>
<c:if test="${not empty items}">
<table border="1">
<tr>
<th>Username</th>
<th>Password</th>
<th colspan="2"><a href="insert.jsp"> <input type="button" value="Insert"/> </a></th>
</tr>
<c:forEach var="it" items="${items}">
<form action="CrudServlet" method="POST">
<tr>
<td><input type="text" name="username" value="${it.username}"/> </td>
<td><input type="text" name="password" value="${it.password}"/> </td>
<td> <input type="submit" value="Update" name="action"/></td>
<td> <input type="submit" value="Delete" name="action"/></td>
</tr>
</form>
</c:forEach>
</table>
</c:if>
<c:if test="${not empty message}">
${requestScope.message}
</c:if>
</body>
</html>
insert.jsp
Java Web Service 2016
<%--
Document : login
Created on : Dec 15, 2016, 1:35:08 PM
Author : Lonely
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Insert!</h1>
<form action="CrudServlet" method="Post">
<input type="text" name="username" /><br/>
<input type="text" name="password" /><br/>
<input type="submit" value="Insert" name="action" />
</form>
</body>
</html>
Tạo Servlet: LoginServlet Package: controller
LoginServlet.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.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;
import service.UserWebService_Service;
/**
*
* @author Lonely
*/
public class LoginServlet extends HttpServlet {
@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/ServiceSoap/UserWebService.wsdl")
private UserWebService_Service service;
//Xóa hết những phần không dùng đến và để lại method doGet và doPost
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Logout clear session
request.getSession().invalidate();
response.sendRedirect("login.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(checkLogin(username, password)){
HttpSession session = request.getSession();
session.setAttribute("USER", username);
request.setAttribute("items", findAll());
request.getRequestDispatcher("index.jsp").forward(request, response);
}else{
request.setAttribute("message", "Login fail!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
private boolean checkLogin(java.lang.String username, java.lang.String password) {
service.UserWebService port = service.getUserWebServicePort();
return port.checkLogin(username, password);
}
private java.util.List<service.User> findAll() {
service.UserWebService port = service.getUserWebServicePort();
return port.findAll();
}
}
Di chuyển kéo thả các method vào CrudServlet
CrudServlet.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.UserWebService_Service;
/**
*
* @author Lonely
*/
public class CrudServlet extends HttpServlet {
//Đoạn code này tự generate
@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/ServiceSoap/UserWebService.wsdl")
private UserWebService_Service service;
//Xóa hết những phần không dùng đến và để lại method doPost
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String action = request.getParameter("action");
if ("Insert".equalsIgnoreCase(action)) {
if (insertUser(username, password)) {
request.setAttribute("items", findAll());
request.getRequestDispatcher("index.jsp").forward(request, response);
} else {
request.setAttribute("message", "Error insert!");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
} else if ("Update".equalsIgnoreCase(action)) {
if (updateUser(username, password)) {
request.setAttribute("items", findAll());
request.getRequestDispatcher("index.jsp").forward(request, response);
} else {
request.setAttribute("message", "Error update!");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
} else if ("Delete".equalsIgnoreCase(action)) {
if (deleteUser(username)) {
request.setAttribute("items", findAll());
request.getRequestDispatcher("index.jsp").forward(request, response);
} else {
request.setAttribute("message", "Error delete!");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
}
private boolean insertUser(java.lang.String username, java.lang.String password) {
service.UserWebService port = service.getUserWebServicePort();
return port.insertUser(username, password);
}
private boolean updateUser(java.lang.String username, java.lang.String password) {
service.UserWebService port = service.getUserWebServicePort();
return port.updateUser(username, password);
}
private boolean deleteUser(java.lang.String username) {
service.UserWebService port = service.getUserWebServicePort();
return port.deleteUser(username);
}
private java.util.List<service.User> findAll() {
service.UserWebService port = service.getUserWebServicePort();
return port.findAll();
}
}
Clean and build > Deploy > Run project client test
Trước khi Run test chúng ta cài đặt mặc định project ServiceSoapClient như sau rồi run:
Demo login success!
Demo login fail!
View data table
Update password Anna
Insert new user Alibaba / 123456
Delete Anna
Download zip (Import Netbeans)
0 nhận xét:
Post a Comment