Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a the host name (with port) that a servlet is at

I thought ServletContext might provide a method. Does the getAttribute() method of ServletContext provide any help i.e. is there an attribute name (maybe "host", "port") that will be of help.

The reason for this is I want my application to run wherever it is deployed, and at one point I have to allow a user to click a link that points to a location on the file server. Hence I need to reference by the host and port and cannot use an internal reference.

like image 332
Ankur Avatar asked Apr 07 '10 09:04

Ankur


People also ask

How do we get the server information in servlets?

Because these methods are attributes of ServletContext in which the servlet is executing, you have to call them through that object: String serverInfo = getServletContext(). getServerInfo(); The most straightforward use of information about the server is an “About This Server” servlet, as shown in Example 4.3.

How can I get servlet name?

if (((HttpServletRequest)request). getServletPath(). equals("/Test")){ String IP = request. getRemoteAddr(); System.

What is the request object which can be used to retrieve the host name?

You can use HttpServletRequest. getRequestURL and HttpServletRequest.

How many ways servlet can be created?

The servlet example can be created by three ways: By implementing Servlet interface, By inheriting GenericServlet class, (or) By inheriting HttpServlet class.


2 Answers

ServletRequest.getServerName(...) ServletRequest.getServerPort(...) 
like image 123
Everyone Avatar answered Oct 05 '22 22:10

Everyone


The ServletRequest object that has been passed to your doGet, or doPost method has getServerName and getServerPort methods that provide this information.

eg

public void doGet(ServletRequest request, ServletResponse response) {     System.out.println("Host = " + request.getServerName());     System.out.println("Port = " + request.getServerPort()); } 
like image 34
Tom Jefferys Avatar answered Oct 05 '22 23:10

Tom Jefferys