CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

Tạo ứng dụng JSP-Servlet gọi Restful Webservice sử dụng thư viện Jersey Client

Đăng lúc: 04:40 PM - 01/12/2023 bởi Charles Chung - 1284

Trong bài này tôi sẽ hướng dẫn tạo ứng dụng JSP-Servlet gọi Restful Webservice sử dụng thư viện Jersey Client

Giới thiệu

Trong bài này chúng ta sẽ tiến hành tạo ứng dụng JSP&Servlet Client để gọi Restful Webservice của bài Tạo RESTful Web Service trong Java với Jersey và Oracle sử dụng thư viện sử dụng là Jersey 1.x (các bạn có thể sử dụng bản 2.x)

Các bước thực hiện

Bước 1: Tạo Dynamic Web Project

  • Khởi động Eclispe IDE -> vào menu File -> New -> Dynamic Web Project -> Nhập tên "JerseyClientConsumeRestWebservice"
  • Tiêp tục kích vào Next -> Next -> Chọn Generate web.xml deyployment desciptor -> Finish

Bước 2: Convert sang Maven Project

  • Kích chuột phải vào Project vừa tạo -> Configure -> Convert to Maven Project -> Finish

Bước 3: Khai báo các Maven Dependencies cần thiết

  • Mở file pom.xml và cấu hình các Maven Dependencies gồm: jstl, jersey client, gson

<dependencies>

<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->

<dependency>

<groupId>com.sun.jersey</groupId>

<artifactId>jersey-client</artifactId>

<version>1.19.4</version>

</dependency>

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.8.6</version>

</dependency>

</dependencies>

 

Bước 4: Tạo các tệp tin theo cấu trúc mô tả sau

  • Mở tệp web.xml và cấu hình vào bên trong thẻ <web-app> như sau:

<welcome-file-list>

<welcome-file>StudentServlet</welcome-file>

</welcome-file-list>

  • Tạo lớp hanam88.model/Result.java (nhận kết quả trả về từ service)

public class Result {

private int code;

private String message;

public Result(int code, String message) {

super();

this.code = code;

this.message = message;

}

public int getCode() {

return code;

}

public void setCode(int code) {

this.code = code;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

}

  • Tạo lớp hanam88.model/Student.java (nhận thông tin sinh viên trả về từ service)

public class Student implements Serializable {

private static final long serialVersionUID = 1L;

private String studentId;

private String fullName;

private int gender;

private Date birthDay;

private String email;

private String phone;

private String address;

private int active;

public Student() {

}

public String getStudentId() {

return studentId;

}

public Student(String studentId, String fullName, int gender, Date birthDay, String email, String phone,

String address, int active) {

super();

this.studentId = studentId;

this.fullName = fullName;

this.gender = gender;

this.birthDay = birthDay;

this.email = email;

this.phone = phone;

this.address = address;

this.active = active;

}

public void setStudentId(String studentId) {

this.studentId = studentId;

}

public String getFullName() {

return fullName;

}

public void setFullName(String fullName) {

this.fullName = fullName;

}

public int getGender() {

return gender;

}

public void setGender(int gender) {

this.gender = gender;

}

public Date getBirthDay() {

return birthDay;

}

public void setBirthDay(Date birthDay) {

this.birthDay = birthDay;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

public int getActive() {

return active;

}

public void setActive(int active) {

this.active = active;

}

}

  • Tạo lớp hanam88.servlet/StudentServlet.java (xử lý các nghiệp vụ và gọi service)

@WebServlet("/StudentServlet")

public class StudentServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

//khai báo uri service

String uri="http://localhost:8080/RestfulWebServiceJerseyOracle/api";

public StudentServlet() {

super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//Thiết lập utf-8

request.setCharacterEncoding("UTF-8");

//lấy tham số action

var action=request.getParameter("action");

//khởi tạo gson

var gson=new GsonBuilder().setDateFormat("dd/MM/yyyy").create();

//tạo client jersey

var client=Client.create();

//nếu action null thì gọi service lấy toàn bộ sinh viên

if(action==null) {

//thiết lập uri path tài nguyên

WebResource resource=client.resource(uri).path("students");

//lấy gọi GET để lấy dữ liệu trả về string

String data=resource.get(String.class);

//convert string sang list<student>

TypeToken<List<Student>> listOfMyClassObject = new TypeToken<List<Student>>() {};

List<Student> students=gson.fromJson(data, listOfMyClassObject.getType());

//chuyển ra view index để hiển thị

request.setAttribute("students", students);

request.getRequestDispatcher("index.jsp").forward(request, response);

}else if(action.equals("search")) {

String name=request.getParameter("name");

WebResource resource=client.resource(uri).path("students").path("search").path(name);

String data=resource.get(String.class);

TypeToken<List<Student>> listOfMyClassObject = new TypeToken<List<Student>>() {};

List<Student> students=gson.fromJson(data, listOfMyClassObject.getType());

request.setAttribute("students", students);

request.getRequestDispatcher("index.jsp").forward(request, response);

}else if(action.equals("add")) {

response.sendRedirect("create.jsp");

}else if(action.equals("edit")) {

String id=request.getParameter("id");

WebResource resource=client.resource(uri).path("students").path(id);

String data=resource.get(String.class);

Student student=gson.fromJson(data, Student.class);

request.setAttribute("student", student);

request.getRequestDispatcher("edit.jsp").forward(request, response);

}else if(action.equals("save")) {

var st=new Student();

st.setStudentId(request.getParameter("studentId"));

st.setFullName(request.getParameter("fullName"));

st.setAddress(request.getParameter("address"));

try {

st.setBirthDay(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthDay")));

System.out.println(st.getBirthDay());

} catch (ParseException e) {

e.printStackTrace();

}

st.setEmail(request.getParameter("email"));

st.setGender(Integer.parseInt(request.getParameter("gender")));

st.setPhone(request.getParameter("phone"));

st.setActive(Integer.parseInt(request.getParameter("active")));

String data=gson.toJson(st);

WebResource resource=client.resource(uri).path("students");

ClientResponse clientResponse=resource.type("application/json").post(ClientResponse.class, data);

String result=clientResponse.getEntity(String.class);

var rs=gson.fromJson(result, Result.class);

request.getSession().setAttribute("msg", rs.getMessage());

System.out.println(result);

response.sendRedirect("StudentServlet");

}else if(action.equals("update")) {

var st=new Student();

st.setStudentId(request.getParameter("studentId"));

st.setFullName(request.getParameter("fullName"));

st.setAddress(request.getParameter("address"));

try {

st.setBirthDay(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthDay")));

} catch (ParseException e) {

e.printStackTrace();

}

st.setEmail(request.getParameter("email"));

st.setGender(Integer.parseInt(request.getParameter("gender")));

st.setPhone(request.getParameter("phone"));

st.setActive(Integer.parseInt(request.getParameter("active")));

String data=gson.toJson(st);

WebResource resource=client.resource(uri).path("students").path(st.getStudentId());

ClientResponse clientResponse=resource.type("application/json").put(ClientResponse.class, data);

String result=clientResponse.getEntity(String.class);

var rs=gson.fromJson(result, Result.class);

request.getSession().setAttribute("msg", rs.getMessage());

response.sendRedirect("StudentServlet");

}else if(action.equals("delete")) {

String id=request.getParameter("id");

WebResource resource=client.resource(uri).path("students").path(id);

ClientResponse clientResponse=resource.delete(ClientResponse.class);

String result=clientResponse.getEntity(String.class);

var rs=gson.fromJson(result, Result.class);

request.getSession().setAttribute("msg", rs.getMessage());

response.sendRedirect("StudentServlet");

}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

doGet(request, response);

}

}

 

  • Tạo trang jsp WEB-INF/index.jsp (hiển thị danh sách sinh viên)

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

pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>DANH SÁCH SINH VIÊN</title>

<link rel="stylesheet"

href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<H1>DANH SÁCH SINH VIÊN</H1>

<a class="btn btn-primary" href="StudentServlet?action=add">Thêm mới</a>

<form method="get" action="StudentServlet"><input type="hidden" name="action" value="search"/> <input type="text" name="name"/><button>Tìm kiếm</button></form>

<c:if test="${sessionScope.msg!=null}">

<p class="alert alert-success">${sessionScope.msg}</p>

<c:remove var="msg" scope="session" />

</c:if>

<table class="table table-bordered">

<tr>

<th> số</th>

<th>Họ tên</th>

<th>Ngày sinh</th>

<th>Giới tính</th>

<th>Email</th>

<th>Địa chỉ</th>

<th>Điện thoại</th>

<th>Tình trạng</th>

<th></th>

</tr>

<c:forEach var="s" items="${students}">

<tr>

<td>${s.studentId}</td>

<td>${s.fullName}</td>

<td><f:formatDate value="${s.birthDay}" pattern="dd/MM/yyyy" /></td>

<td>

<c:choose>

<c:when test="${s.gender==1}">

<span>Nam</span>

</c:when>

<c:otherwise>

<span>Nữ</span>

</c:otherwise>

</c:choose>

</td>

<td>${s.email}</td>

<td>${s.address}</td>

<td>${s.phone}</td>

<td>

<c:choose>

<c:when test="${s.active==1}">

<span>Đang học</span>

</c:when>

<c:otherwise>

<span>Đã nghỉ</span>

</c:otherwise>

</c:choose>

</td>

<td>

<a class="btn btn-danger" onclick="return confirm('Bạn có muốn xóa không?')" href="StudentServlet?id=${s.studentId}&action=delete">Xóa</a>

<a class="btn btn-success" href="StudentServlet?id=${s.studentId}&action=edit">Sửa</a>

</td>

</tr>

</c:forEach>

</table>

</div>

</body>

</html>

  • Tạo trang jsp WEB-INF/create.jsp (thêm sinh viên)

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

pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Thêm mới sinh viên</title>

<link rel="stylesheet"

href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<h1>Thêm mới sinh viên</h1>

<span style="color: red">${error}</span>

<form action="StudentServlet?action=save" method="post">

<table class="table">

<tr>

<td> số</td>

<td><input type="text" name="studentId" /></td>

</tr>

<tr>

<td>Họ tên</td>

<td><input type="text" name="fullName" /></td>

</tr>

<tr>

<td>Ngày sinh</td>

<td><input type="date" name="birthDay" /></td>

</tr>

<tr>

<td>Giới tính</td>

<td><select name="gender" id="gender">

<option value="1">Nam</option>

<option value="0">Nữ</option>

</select></td>

</tr>

<tr>

<td>Email</td>

<td><input type="email" name="email" /></td>

</tr>

<tr>

<td>Điện thoại</td>

<td><input type="text" name="phone" /></td>

</tr>

<tr>

<td>Địa chỉ</td>

<td><input type="text" name="address" /></td>

</tr>

<tr>

<td>Tình trạng</td>

<td><select name="active" id="active">

<option value="1">Đang học</option>

<option value="0">Dừng</option>

</select></td>

</tr>

<tr>

<td colspan="2">

<button class="btn btn-primary">Lưu</button>

</td>

</tr>

</table>

</form>

</div>

</body>

</html>

  • Tạo trang jsp WEB-INF/edit.jsp (sửa sinh viên)

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

pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Sửa sinh viên</title>

<link rel="stylesheet"

href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<h1>Sửa sinh viên</h1>

<form action="StudentServlet?action=update" method="post">

<table class="table">

<tr>

<td> số</td>

<td><input type="hidden" name="studentId" value="${student.studentId}" />${student.studentId}</td>

</tr>

<tr>

<td>Họ tên</td>

<td><input type="text" name="fullName" value="${student.fullName}" /></td>

</tr>

<tr>

<td>Ngày sinh</td>

<f:formatDate value="${student.birthDay}" pattern="yyyy-MM-dd" var="strdate" />

<td><input type="date" value="${strdate}" name="birthDay" /></td>

</tr>

<tr>

<td>Giới tính</td>

<td><select name="gender" id="gender">

<c:if test="${student.gender==1}">

<option selected value="1">Nam</option>

<option value="0">Nữ</option>

</c:if>

<c:if test="${student.gender==0}">

<option value="1">Nam</option>

<option selected value="0">Nữ</option>

</c:if>

</select></td>

</tr>

<tr>

<td>Email</td>

<td><input type="email" name="email" value="${student.email }" /></td>

</tr>

<tr>

<td>Điện thoại</td>

<td><input type="text" name="phone" value="${student.phone }" /></td>

</tr>

<tr>

<td>Địa chỉ</td>

<td><input type="text" name="address" value="${student.address }" /></td>

</tr>

<tr>

<td>Tình trạng</td>

<td><select name="active" id="active">

<c:if test="${student.active==1}">

<option selected value="1">Đang học</option>

<option value="0">Đã nghỉ</option>

</c:if>

<c:if test="${student.active==0}">

<option value="1">Đang học</option>

<option selected value="0">Dừng</option>

</c:if>

</select></td>

</tr>

<tr>

<td colspan="2">

<button class="btn btn-primary">Cập nhật</button>

</td>

</tr>

</table>

</form>

</div>

</body>

</html>

Bước 5: Run application

  • Kích chuột phải vào project chọn Run As -> Run on Server -> Tomcat v9.0
  • Màn hình danh sách sinh viên

  • Màn hình sửa sinh viên

Kích để tải source code bài Tạo ứng dụng JSP-Servlet gọi Restful Webservice sử dụng thư viện Jersey Client

Training online liên hệ: Charles Chung

Video

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ