There are four methods that a servlet can
There are four methods that a servlet can use to learn about its server: two that are called using the ServletRequestobject passed to the servlet and two that are called from the ServletContextobject in which the servlet is executing. A servlet can get the name of the server and the port number for a particular request with getServerName()and getServerPort(), respectively: public String ServletRequest.getServerName() public int ServletRequest.getServerPort() These methods are attributes of ServletRequestbecause the values can change for different requests if the server has more than one name (a technique called virtual hosting). The returned name might be something like www.servlets.com” while the returned port might be something like 8080 . The getServerInfo()and getAttribute()methods of ServletContextprovide information about the server software and its attributes: public String ServletContext.getServerInfo() public Object ServletContext.getAttribute(String name) getServerInfo()returns the name and version of the server software, separated by a slash. The string returned might be something like JavaWebServer/1.1.1 . getAttribute()returns the value of the named server attribute as an Objector nullif the attribute does not exist. The attributes are server- dependent. You can think of this method as a back door through which a servlet can get extra information about its server. Attribute names should follow the same convention as package names. The package names java.* and javax.*are reserved for use by the Java Software division of Sun Microsystems (formerly known as JavaSoft), and com.sun.*is reserved for use by Sun Microsystems. See your server’s documentation for a list of its attributes. Because these methods are attributes of ServletContextin 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. Example 4-3. Snooping the server import java.io.*; import java.util.*; import javax.servlet.*; public class ServerSnoop extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); out.println( req.getServerName(): + req.getServerName()); out.println( req.getServerPort(): + req.getServerPort()); out.println( getServletContext().getServerInfo(): + getServletContext().getServerInfo()); out.println( getServerInfo() name: + getServerInfoName(getServletContext().getServerInfo())); out.println( getServerInfo() version: + getServerInfoVersion(getServletContext().getServerInfo())); out.println( getServletContext().getAttribute( attribute ): +
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services