import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { int port = request.getServerPort(); PrintWriter out = response.getWriter(); out.println("The server is running on port " + port); } }
import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { int port = request.getServerPort(); String url = "http://localhost:" + port + "/myapp"; PrintWriter out = response.getWriter(); out.println("The application is running at " + url); } }In this example, a servlet is using the server port to construct a URL and printing it in the response. This can be useful in cases where the port is not known in advance. The HttpServletRequest is part of the javax.servlet.http package library.