Reputation: 571
I'm messing around with Maven/Tomcat/Java in Eclipse. I have made this java servlet, but when I go to localhost:xxxx/myapp/rest I don't get a response on my GET request, I get a 404. I thought if I put the @path to /rest I can send a GET request to the url, but it's not working. Does anyone know what the issue is? Thank you!
@Path("/rest")
public class WorldResource {
@GET
@Produces("application/json")
public String getOrders() {
WorldService service = ServiceProvider.getWorldService();
JsonArrayBuilder jab = Json.createArrayBuilder();
for (Country o : service.getAllCountries()) {
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("iso2Code", o.getCode());
job.add("iso3Code", o.getIso3Code());
job.add("capital", o.getCapital());
job.add("continent", o.getContinent());
job.add("region", o.getRegion());
job.add("surface", o.getSurface());
job.add("population", o.getPopulation());
job.add("government", o.getGovernment());
job.add("latitude", o.getLatitude());
job.add("longitude", o.getLongitude());
jab.add(job);
}
JsonArray array = jab.build();
System.out.println(array);
return array.toString();
}
}
Upvotes: 0
Views: 224
Reputation: 118593
This is not a servlet, it's a JAX-RS Resource. This will not work "out of the box" within Tomcat, you'll need to deploy a JAX-RS implementation along with it (like Jersey).
A Servlet would look something like this:
@WebServlet(name = "WorldServlet", urlPatterns = {"/rest"})
public class WorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
try (PrintWriter out = response.getWriter()) {
... // your code
out.println(array.toString());
}
}
}
So, you really just need to look in to installing a JAX-RS provider. Also, when you do that, odds are high it STILL won't be at /rest
, because the JAX-RS implementation is normally rooted at some path, so you might end up with something like /resources/rest
.
That's all configurable of course.
Upvotes: 2
Reputation: 547
This can happen because your servlet is incapable of converting your POJO to appropriate HTTP response.
Instead of return array.toString();
try return Response.status(200).entity(array.toString()).build();
Upvotes: -1