如何从 servlet 读取以下路径?
How to read the following path from a servlet?
我有一个在 organizations
地址 (@WebServlet("/organizations")
) 上工作的 servlet。这种在地址 .../organizations
上使用 GET 或 POST 方法的方法会导致调用此 servlet。当我需要与当前组织(例如,12th)合作时,我应该调用 .../organizations/12
。这样我可以写 @WebServlet("/organizations/*")
,但是如何读取这个数字(在本例中为 12)?或者我可以用 @WebServlet("/organizations/{orgNumber}")
之类的变量替换它(这个变体不起作用)?
您没有给我们您的代码,但您可以使用 request
对象和字符串操作来查找您要查找的请求 URI 部分。
@WebServlet("/organizations/*")
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// split the complete URI by /
final var split = request.getRequestURI().split("/");
// ...
// or use substrings
final var partOfPath = request.getRequestURI().substring(20,30);
// ...
// or use pathInfo to split only the path following the domain
final var split = request.getPathInfo().split("/");
// ...
}
}
您可以将其映射到 /organizations/* 并从 getPathInfo() 中提取信息:
@WebServlet("/organizations/*")
public class OrganizationsController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] pathInfo = request.getPathInfo().split("/");
String id = pathInfo[1]; // {id}
String command = pathInfo[2];
// ...
//..
//.
}
}
我有一个在 organizations
地址 (@WebServlet("/organizations")
) 上工作的 servlet。这种在地址 .../organizations
上使用 GET 或 POST 方法的方法会导致调用此 servlet。当我需要与当前组织(例如,12th)合作时,我应该调用 .../organizations/12
。这样我可以写 @WebServlet("/organizations/*")
,但是如何读取这个数字(在本例中为 12)?或者我可以用 @WebServlet("/organizations/{orgNumber}")
之类的变量替换它(这个变体不起作用)?
您没有给我们您的代码,但您可以使用 request
对象和字符串操作来查找您要查找的请求 URI 部分。
@WebServlet("/organizations/*")
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// split the complete URI by /
final var split = request.getRequestURI().split("/");
// ...
// or use substrings
final var partOfPath = request.getRequestURI().substring(20,30);
// ...
// or use pathInfo to split only the path following the domain
final var split = request.getPathInfo().split("/");
// ...
}
}
您可以将其映射到 /organizations/* 并从 getPathInfo() 中提取信息:
@WebServlet("/organizations/*")
public class OrganizationsController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] pathInfo = request.getPathInfo().split("/");
String id = pathInfo[1]; // {id}
String command = pathInfo[2];
// ...
//..
//.
}
}