我想将两个占位符值传递给 API,例如位置 id 的详细信息:组织的 50 是 5
api.xxx.com/organization/5/location/50
下面是我的代码,它给出了 404。但是如果您只是为了组织而编写代码,那么该代码就可以工作。
如何让它与两个占位符一起使用?
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/organization/*/location/*")
public class LocationServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] pathInfo = request.getPathInfo().split("/");
if (pathInfo.length == 4) {
String organizationId = pathInfo[2];
String locationId = pathInfo[4];
// Implement your logic here to fetch data based on organizationId and locationId
// You can return the results as JSON or any other format.
// For example:
// LocationInfo locationInfo = locationService.getLocationInfo(organizationId, locationId);
// response.getWriter().write(locationInfo.toString());
response.getWriter().write("Organization ID: " + organizationId + ", Location ID: " + locationId);
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write("Invalid URL");
}
}
}
问题在于您尝试访问路径参数的方式。 Java 中的数组是 0 索引的,因此当您分割路径时,您应该使用正确的索引访问值。
我将更改以下内容
您可以尝试修改此代码来解决该问题吗?
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/organization/*/location/*")
public class LocationServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] pathInfo = request.getPathInfo().split("/");
if (pathInfo.length == 4) {
String organizationId = pathInfo[1];
String locationId = pathInfo[3];
// Implement your logic here to fetch data based on organizationId and locationId
// You can return the results as JSON or any other format.
// For example:
// LocationInfo locationInfo = locationService.getLocationInfo(organizationId, locationId);
// response.getWriter().write(locationInfo.toString());
response.getWriter().write("Organization ID: " + organizationId + ", Location ID: " + locationId);
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write("Invalid URL");
}
}
}