0

我有一个在organizations地址(@WebServlet("/organizations"))上工作的 servlet。这种在地址上使用 GET 或 POST 方法的方式.../organizations会导致调用此 servlet。当我需要与当前组织(例如 12th)合作时,我应该致电.../organizations/12. 这样我可以写@WebServlet("/organizations/*"),但是如何读取这个数字(在这种情况下是 12)?或者我可以用某种变量替换它@WebServlet("/organizations/{orgNumber}")(这个变体不起作用)?

4

2 回答 2

1

您没有向我们提供您的代码,但您可以使用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("/");
        // ...
    }
}
于 2021-09-06T06:14:25.853 回答
0

您可以将其映射到 /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];
        // ...
       //..
      //.
    }

}
于 2021-09-06T06:34:56.403 回答