Java Servlets generate Web pages
This module discusses how to write servlets.
You have learned what servlets are and how they work, and you have installed and configured all your software.
After completing this module you will be able to:
- Generate HTML from a servlet
- Mix static and generated HTML on the same Web page
- Maintain state in a servlet
- Include the current time on a Web page
- Recognize the HTML that generates a form
- Use form data in a servlet
A servlet can find out much about the server in which it is executing. It can learn the
- listening port, and
- server software.
A servlet can display this information to a client, use it to customize its behavior based on a particular server package, or even use it to explicitly restrict the machines on which the servlet will run.
Getting Information About the Server
There are four methods that a servlet can use to learn about its server:
two that are called using the ServletRequest object passed to the servlet and two that are called from the ServletContext object 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(),
Two that are called using the ServletRequest object passed to the servlet and
public String ServletRequest.getServerName()
public int ServletRequest.getServerPort()
These methods are attributes of ServletRequest because 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 ServletContext provide information about the server software and its attributes:
Two that are called from the ServletContext object in which the servlet is executing.
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 Object or null if 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 Oracle (formerly Sun Microsystems), and com.sun.* was designated by Sun Microsystems. 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();