Restful: Create > Read > Update > Delete > Search
=============PHẦN WEB SERVICE =============
Tạo project Test23Restful
CrudResource.java
Java Web Service 2016
package sample.restFul;
import dao.UserDao;
import entity.User;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author Lonely
*/
@Path("generic")
public class CrudResource {
@Context
private UriInfo context;
UserDao userDao = new UserDao();
//http://localhost:8080/Test23Restful/webresources/generic/checkLogin?username=Antonio&password=123456
@Path("/checkLogin")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String checkLogin(
@QueryParam("username") String username,
@QueryParam("password") String password) {
boolean result = userDao.checkLogin(username, password);
return result == true ? "true" : "false";
}
//http://localhost:8080/Test23Restful/webresources/generic/showUser
@GET
@Path("/showUser")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<User> findAll() {
return userDao.findAll();
}
//http://localhost:8080/Test23Restful/webresources/generic/search/Antonio
@GET
@Path("search/{username}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<User> findByName(@PathParam("username") String username) {
return userDao.findByUsername(username);
}
//http://localhost:8080/Test23Restful/webresources/generic/delete?username=Antonio
@DELETE
@Path("/delete")
@Produces(MediaType.APPLICATION_JSON)
public String deleteUser(
@QueryParam("username") String username) {
boolean result = userDao.deleteUser(username);
return result == true ? "true" : "false";
}
//http://localhost:8080/Test23Restful/webresources/generic/create?username=Antonio&password=123456
@PUT @Path("/create")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public String insertUser(
@QueryParam("username") String username,
@QueryParam("password") String password) {
boolean result = userDao.insertUser(new User(username, password));
return result == true ? "true" : "false";
}
//http://localhost:8080/Test23Restful/webresources/generic/update?username=Antonio&password=123456789
@POST @Path("/update")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public String updateUser(
@QueryParam("username") String username,
@QueryParam("password") String password) {
boolean result = userDao.updateUser(new User(username, password));
return result == true ? "true" : "false";
}
}
Tạo Entity Database
Sau khi tạo xong Service và Entity Database
-Các bạn tải project ở dưới cùng vào phần src coppy hibernate.cfg.xml và coppy cả package util paste và như hình dưới.
Xong chúng ta vào phần hibernate.cfg.xml sửa lại username & password của msql
Chúng ta không cần quan tâm đến AppliactionConfig.java
Clean and build > Deploy >Run
-Tải tiện ích chrome Boomerang - SOAP & REST Client
-Add library jdbc mysql connector nếu các bạn không test được.
Run chạy Boomerang để test Service Restful
Trên đây là những hình ảnh Test Crud bằng Boomerang - SOAP & REST Client
-Tiếp theo ta đi xây dựng web client
===============PHẦN WEB CLIENT==============
New project Test23RestfulClient
-Coppy và paste vào project của bạn phần template sẵn này
-Tạo servlet: LoginServlet và CrudServlet
LoginServlet.java
Java Web Service 2016
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import entity.User;
import java.util.Collection;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MediaType;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
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");
//===============//
String URI = "http://localhost:8080/Test23Restful/webresources/generic";
Client client =Client.create(); //Add jersey-client-1.19.jar
client.setFollowRedirects(Boolean.TRUE);
WebResource resource = client.resource(URI);
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); //Add jersey-core-1.19.jar
queryParams.add("username", username);
queryParams.add("password", password);
//=======List=========//
GenericType<Collection<User>> gt = new GenericType<Collection<User>>(){};
Collection<User> list = resource.path("showUser").queryParams(queryParams).accept(MediaType.APPLICATION_XML_TYPE).get(gt);
//========Login========//
String res = resource.path("checkLogin").queryParams(queryParams).get(String.class);
boolean result = Boolean.parseBoolean(res);
if(result){
request.setAttribute("items", list);
HttpSession session = request.getSession();
session.setAttribute("USER", username);
request.getRequestDispatcher("index.jsp").forward(request, response);
}else{
request.setAttribute("message", "Login fail check username or password!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
Add library jersey-client-1.19.jar và jersey-core-1.19.jar
CrudServlet.java
Java Web Service 2016
package servlet; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import entity.User; import java.io.IOException; import java.util.Collection; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * * @author Lonely */ public class CrudServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @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"); //===============// String URI = "http://localhost:8080/Test23Restful/webresources/generic"; Client client = Client.create(); //Add jersey-client-1.19.jar client.setFollowRedirects(Boolean.TRUE); WebResource resource = client.resource(URI); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); //Add jersey-core-1.19.jar queryParams.add("username", username); queryParams.add("password", password); //=======List=========// GenericType<List<User>> gt = new GenericType<List<User>>() { }; Collection<User> list = resource.path("showUser").queryParams(queryParams).accept(MediaType.APPLICATION_XML_TYPE).get(gt); //========Insert========// if ("Insert".equalsIgnoreCase(action)) { String res = resource.path("create").queryParams(queryParams).put(String.class); boolean result = Boolean.parseBoolean(res); if (result) { request.setAttribute("message", res); request.setAttribute("items", resource.path("showUser").queryParams(queryParams).accept(MediaType.APPLICATION_XML_TYPE).get(gt)); request.getRequestDispatcher("index.jsp").forward(request, response); } request.setAttribute("message", "Insert fail"); request.setAttribute("items", list); request.getRequestDispatcher("index.jsp").forward(request, response); } else if ("Update".equalsIgnoreCase(action)) { String res = resource.path("update").queryParams(queryParams).post(String.class); boolean result = Boolean.parseBoolean(res); if (result) { request.setAttribute("message", res); request.setAttribute("items", resource.path("showUser").queryParams(queryParams).accept(MediaType.APPLICATION_XML_TYPE).get(gt)); request.getRequestDispatcher("index.jsp").forward(request, response); } request.setAttribute("message", "Insert fail"); request.setAttribute("items", list); request.getRequestDispatcher("index.jsp").forward(request, response); } else if ("Delete".equalsIgnoreCase(action)) { MultivaluedMap<String, String> paramsDelete = new MultivaluedMapImpl(); //Add jersey-core-1.19.jar paramsDelete.add("username", username); String res = resource.path("delete").queryParams(paramsDelete).delete(String.class); boolean result = Boolean.parseBoolean(res); if (result) { request.setAttribute("message", res); request.setAttribute("items", resource.path("showUser").queryParams(queryParams).accept(MediaType.APPLICATION_XML_TYPE).get(gt)); request.getRequestDispatcher("index.jsp").forward(request, response); } request.setAttribute("message", "Insert fail"); request.setAttribute("items", list); request.getRequestDispatcher("index.jsp").forward(request, response); } else if ("search".equalsIgnoreCase(action)) { String pathParam = username; if(username.isEmpty()){pathParam="a";} List<User> res = resource.path("search/"+pathParam+"").accept(MediaType.APPLICATION_XML_TYPE).get(gt); if (res.size()>0) { request.setAttribute("message", "Finding"); request.setAttribute("items", res); request.getRequestDispatcher("index.jsp").forward(request, response); } request.setAttribute("message", "Find not found"); request.setAttribute("items", list); request.getRequestDispatcher("index.jsp").forward(request, response); } } }
-Tạo entity database User
Clean and build > Deploy > Run Test23RestfulClient
Login không thành công.
Login thành công.
Search username Antonio
Insert Ewin Rommel
Update Ewin Rommel123456
Delete Ewin Rommel123456
Download zip (import Netbeans)
0 nhận xét:
Post a Comment