Junior — Middle
How can routes be implemented in a web application in Java?
sobes.tech AI
Answer from AI
In a Java web application, routes are typically implemented using servlets or frameworks such as Spring MVC or JAX-RS.
Example using annotations in Spring MVC:
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/users")
public List<User> getUsers() {
// logic to get users
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// logic to create a user
}
}
Here, @RequestMapping and @GetMapping define the routes that will handle HTTP requests.
If using the standard Java EE approach, routes are defined in the deployment descriptor (web.xml) or via @WebServlet annotations:
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().write("Hello World");
}
}
Thus, routes are implemented either declaratively via annotations or through configuration in XML.