Q: How do I include files in my servlet?
A: To achieve an include scheme in a servlet, use javax.servlet.RequestDispatcher, which takes the path of the target document in its constructor. A RequestDispatcher can be obtained from the ServletContext object (via ServletConfig) in your servlet's init method, or from ServletRequest or HttpServletRequest in doGet or doPost.
Q: Can I call the doPost() method from a hyperlink?
A: Following a hyperlink in a Web document normally creates an HTTP GET request to the given URL, not a POST request. Post requests are normally produced by the submission of an HTML form whose method attribute is post. In this case any values given in the form's input elements are passed as request parameters to the URL specified in the form's action attribute.
- Q: How can I display system properties in a servlet?
-
A: You can obtain the operating system, operating system version and Java version for a servlet container through standard Java system properties. There is a wide range of standard properties that can be obtained from the static
System
class methodgetProperty(String)
, using the following keys:String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String javaVersion = System.getProperty("java.version");
These system properties are common to all Java runtime systems including servlets.
- Q: Should I use a
static
variable orHashtable
to store a list of strings? -
A: The
static
modifier for a variable is different from the object type of the variable. If you want all servlet instances to be able to read and write data to a field, it should be static. Depending on the nature of the application, it may also be necessary to synchronize access to the variable.If you want to store a simple list of strings, a
java.util.List
type variable would be most appropriate. AVector
is aList
type and its implementation is synchronized.private static final List stringList = new Vector();
- Q: How can I enable users to upload a file?
-
A: A file upload servlet should control what type of files are permitted, to process the byte stream and decide where the the content is stored. As you can imagine, allowing anybody to upload any file to your Web server is a significant security hazard, so you must be very careful to ensure that you restrict who has access, what they upload, and that the public do not have arbitrary access to the file via the Internet.
The Apache commons file upload package would be a good place to start.
- Q: How do I limit the file upload size?
-
A: This example code is for the Apache commons file upload package.
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
- Q: Can I get the client IP and MAC address?
-
A: The
ServletRequest
type has agetRemoteAddr()
method that returns the Internet Protocol (IP) address of the client that made the request. The address is returned as aString
, so must be parsed further if you want to extract numeric references from it. In JSP you can access this method it directly through therequest
variable, as below.
- Q: How do I send data from an applet to a servlet?
-
A: The applet sandbox security environment only permits connections with the host from which the applet was loaded. If you attempt a connection with a different host, the applet will throw a
SecurityException
and fail. This can also cause problems when you are testing an applet loaded from the local file system, which has no host.
- Q: How can I pass user input through my spelling checker?
-
A: create an instance of your
SpellChecker
class in thedoGet()
ordoPost()
method of your servlet and pass the relevant parameter to it as a string, as in the code sample below ...
- Q: How can I make the servlet output open in Microsoft Excel?
-
A: The binary file format of Microsoft Excel documents is extremely complex. If you want to reproduce this format in detail and with precision you should read OpenOffice.org's Documentation of the Microsoft Excel File Format.
- Q: Which link was followed to request my servlet?
-
A: You should not rely upon the HTTP
referer
(sic) header to be sent to your servlet because some Web browsers (and other client types) do not send them for privacy reasons.
- Q: The & in the parameter value truncates the string!
-
A: To pass non-ASCII characters in servlet parameters without them being interpreted as part of the URL structure, you must encode the characters as hexadecimal (base 16) values prefixed by the percent symbol,
%
. This is known as URL-encoding and is normally done automatically by Web browsers when you submit a form. For instance, ampersand is ASCII character number 38, which is %26 expressed as a hexadecimal. See the table below for other conversion values.
- Q: How do I get parameter values from a form submission?
-
A: The simple form below invites people to input their name.
action="http://www.codestyle.org/servlets/EchoRequest">
type="text"
name="name" />
type="submit" />
To handle this submission, extend
HttpServlet
and provide adoPost(HttpServletRequest, HttpServletResponse)
method, as below.
- Q: How can I check what parameters are available in the request?
-
A: There are two main approaches to checking request parameters: either look up named parameters you expect to be present, or iterate through all parameters. It is always possible there is more than one value for each named parameter, so look up values using the
getParameterValues(String)
method, which takes the name of the parameter as an argument and returns a string array. You need to decide what should happen if there is more than one value, this example takes the first value in the array.