lab finish

This commit is contained in:
Rémi Heredero 2023-11-15 11:35:22 +01:00
parent 0e8d7b5d31
commit 1708fc117b
2 changed files with 61 additions and 1 deletions

View File

@ -1,17 +1,67 @@
package servlet; package servlet;
import things.Resource;
import things.Things; import things.Things;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.ResolverStyle;
import java.util.Map;
@WebServlet(name = "Things", urlPatterns = {"/things", "/things/*"}) @WebServlet(name = "Things", urlPatterns = {"/things", "/things/*"})
public class ThingsServlet extends HttpServlet { public class ThingsServlet extends HttpServlet {
private final Things things = new Things(); private final Things things = new Things();
public ThingsServlet() { public ThingsServlet() {
super();
things.addSampleResources(); things.addSampleResources();
} }
// TODO: Implement the GET, POST, PUT and DELETE methods. @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
resp.setContentType("application/json");
if(things.getResourceByURI(uri)==null){
resp.sendError(404);
return;
}
resp.getWriter().print(things.getResourceByURI(uri).getJSON());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
Map<String, String[]> params = req.getParameterMap();
Resource.Type type = Resource.Type.valueOf(params.get("type")[0]);
String name = params.get("name")[0];
if(things.getResourceByURI(uri)==null) {
resp.sendError(404);
return;
}
if(type.equals(Resource.Type.THING)) {
things.addThingWithName(name);
} else {
things.addChildToResourceWithURI(uri, name, type);
}
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
if(things.getResourceByURI(uri)==null) {
resp.sendError(404);
return;
}
things.removeResourceByURI(uri);
}
} }

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloServlet</title>
</head>
<body>
<h1>Hello Servlet!</h1>
</body>
</html>