Get all Server Related Parameters : Introduction « Servlet « Java Tutorial






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class MyServlet extends HttpServlet {
  public void service(ServletRequest req, ServletResponse res)       
                             throws ServletException, IOException {  
    res.setContentType("text/plain");                                
    PrintWriter out = res.getWriter();                               

    ServletContext context = getServletContext();
    out.println("req.getServerName(): " + req.getServerName());      
    out.println("req.getServerPort(): " + req.getServerPort());      
    out.println("context.getServerInfo(): " + context.getServerInfo());
    out.println("getServerInfo() name: " +                           
                 getServerInfoName(context.getServerInfo()));
    out.println("getServerInfo() version: " +                        
                 getServerInfoVersion(context.getServerInfo()));
    out.println("context.getAttributeNames():");
    Enumeration e = context.getAttributeNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println("  context.getAttribute(\"" + name + "\"): " +
                     context.getAttribute(name));
    }
  }

  private String getServerInfoName(String serverInfo) {
    int slash = serverInfo.indexOf('/');
    if (slash == -1) return serverInfo;
    else return serverInfo.substring(0, slash);
  }

  private String getServerInfoVersion(String serverInfo) {
    // Version info is everything between the slash and the space
    int slash = serverInfo.indexOf('/');
    if (slash == -1) return null;
    int space = serverInfo.indexOf(' ', slash);
    if (space == -1) space = serverInfo.length();
    return serverInfo.substring(slash + 1, space);
  }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>

             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletGetAllServerRelatedParameters.zip( 89 k)








25.1.Introduction
25.1.1.Your First Servlet
25.1.2.Setup Servlet Environment
25.1.3.Servlet Converter from Kilometers to Miles
25.1.4.List All Init Parameters in Servlet
25.1.5.Get all Server Related Parameters