2010-06-09
4. Retrieving Information
4.1 The Servlet
Getting a Servlet Init Parameter
public String ServletConfig.getInitParameter(String name)
l return the value of the named init parameter or null if it does not exist.
l The GenericServlet class implements the ServletConfig interface and thus provides direct access to the getInitParameter() method.
l the method can be called like this:String greeting = getInitParameter(“greeting”);
l A Servlet that needs to establish a connection to a database can use its init parameters to define the detail of the connection.
Getting Servlet Init Parameter Names
public Enumeration ServletConfig.getInitParameterNames()
l return the names of all the servlet’s init parameters as an Enumeration of String objects or an empty Enumeration if no parameters exist.
l It’s most often used for debugging.
Getting a servlet name:
public String ServletConfig.getServletName()
l returns the servlet’s registered name.
l This method proves useful when writing to logs and when storing a servlet instance’s state information into a shared resource such as a database or the servlet’s SessiongContext
4.2 The Server
Getting Information About the Server
l Since API 2.2 the ServletContext has become areference to the web application,not a reference to the server.
l There are five methods that servlet can use to learn about its server: two that are called using the ServletRequest object passed to the servlet passed to the servlet and three that three that are called from the ServletContext object in which the servlet is executing.
l get the name of the server and the the port number for aparticular request:
n public String ServletRequest.getServerName()
n public int ServletRequest.getServerPort()
l get information about the server software and its attributes:
n public String ServletContext.getServerInfo()
returns the name and version of the server software, separated by a slash
like Tomcat Web Server / 3.2
Some servers add extra information at the end describing the server operating environment
n public Object ServletContext.getAttribute(String name)
returns the value of the named server attribute as an Object or null
l Servlets can also add their own attributes to the context using the setAttribute() method.
public Enumeration ServletContext.getAttributeNames()
Writing to a Temporary File
l The javax.servlet.context.tempdir attribute maps to atemporary directory where short-lived working files can be stored. Each context receives a different temporary directory.
File dir = (File) getServletContext().getAttribute(“javax.servlet.context.tempdir”);
File f = File.createTempFile(“xxx”, “.tmp”, dir);
FileOutputStream fout = new FileOutputStream(f);