I have a servlet which works on organizations
address (@WebServlet("/organizations")
). This way using GET or POST method on address .../organizations
leads to calling of this servlet. When I need to work with a current organization (for example, 12th), I should call .../organizations/12
. This way I can write @WebServlet("/organizations/*")
, but how to read this number (12 in this case)? Or can I replace it with a variable somehow like @WebServlet("/organizations/{orgNumber}")
(this variant didn't work)?
Asked
Active
Viewed 475 times
0

BalusC
- 1,082,665
- 372
- 3,610
- 3,555

coder-coder
- 323
- 4
- 13
-
1Easy to do with Spring's @PathVariable: https://www.baeldung.com/spring-pathvariable – duffymo Sep 05 '21 at 23:18
-
Can I do it without using Spring? – coder-coder Sep 06 '21 at 03:08
-
Of course. Good luck. – duffymo Sep 06 '21 at 11:45
2 Answers
1
You did not give us your code, but you can use the request
object and string operations to find the part of the request URI you are looking for.
@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("/");
// ...
}
}

Datz
- 3,156
- 3
- 22
- 50
0
You could map it on /organizations/* and extract information from 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];
// ...
//..
//.
}
}

Akash R
- 129
- 7