CSS font stacks & developer FAQs with Web standards

WestNIC provides reliable web hosting services

Fastwebhost offers cheap web hosting & reseller hosting services

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.

What if you were One Percent Better? Java ebooks for iPad, Kindle, Nook and Sony Reader

General servlet "how to" questions

Q: Can I catch an exception and give my own error message?

A: Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place.

… full answer hidden, click for full answers

Premium members click below for full answer
Can I catch an exception and give my own error message?

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.

… full answer hidden, click for full answers

Premium members click below for full answer
Can I call the doPost() method from a hyperlink?

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 method getProperty(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: How can I feed a CAPTCHA image into the servlet page output?

A: The difficulty you are facing is that Web browsers see your servlet output as a single HTTP response stream, which is either an HTML document or an image or some other content item. It is not possible to encode the CAPTCHA image content inline into the HTML markup, the HTML img element requires a reference to an image at a separate URL source. The typical request sequence for a CAPTCHA form page would be:

  1. Request CAPTCHA form page (servlet)
  2. Download CAPTCHA form page HTML with image reference
  3. Request CAPTCHA image (servlet)
  4. Download CAPTCHA image as part of the main page load
  5. Submit CAPTCHA form with image reference and human input (servlet)
  6. Servlet checks CAPTCHA image content with human input and sends response
  7. Download HTML success or error page output accordingly

It is critical the HTML page, form and image reference must not indicate the “decoded” contents of the CAPTCHA image. But the servlet that checks the CAPTCHA must know the decoded contents and the human input. To link the separate CAPTCHA form, image and form submission requests, add a server-side session variable to carry the decoded value. When the CAPTCHA image servlet generates the “encoded” text it should store the decoded value in the session variable so the CAPTCHA check servlet can read the session and know what the value should be.

Q: Should I use a static variable or Hashtable 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. A Vector is a List type and its implementation is synchronized.

private static final List stringList = new Vector();
      

Using request information

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 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: How do I get the uploaded file name?

A: As with many things to do with Java I/O, the commons file upload library treats HTTP file upload as a byte stream, not necessarily as a file. The file upload API represents each uploaded file as a FileItem object, but this is not related to a standard Java File object. However, you can request a DiskFileItem subclass, which may physically store the uploaded content as a temporary file on the server.

Each FileItem has a getName() method that returns the original file name on the user's file system, and a write(File) method to store the contents via a standard Java File object. Various factory configuration options let you set the maximum file size for the upload, the temporary file directory and other settings, as in the profile avatar upload example below.

… full answer hidden, click for full answers

Premium members click below for full answer
How do I get the uploaded file name?

Q: How do I upload and process a file then email it?

A: The Java Mail API provides an interface with the Simple Mail Transport Protocol (SMTP), POP3 and other email services and is included with the Apache Tomcat servlet container and others. The Java Mail API enables you to develop sophisticated email enabled applications, but it operates as a client or intermediary to existing system email services, not as an email server in its own right.

Q: Can I get the client IP and MAC address?

A: The ServletRequest type has a getRemoteAddr() method that returns the Internet Protocol (IP) address of the client that made the request. The address is returned as a String, so must be parsed further if you want to extract numeric references from it. In JSP you can access this method it directly through the request variable, as below.

… full answer hidden, click for full answers

Premium members click below for full answer
Can I get the client IP and MAC address?

Q: How do I get the server port number for redirected requests?

A: If your servlet container is listening on port 8080 then the HttpServletRequest getServerPort() method will return the int 8080.

Process parameters

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.

… full answer hidden, click for full answers

Premium members click below for full answer
How can I check what parameters are available in the request?

Q: How do I get parameter values from a form submission?

A: The simple form below invites people to input their name.

<form
  action="http://www.codestyle.org/servlets/EchoRequest">
  <input
    type="text"
    name="name" />
  <input
    type="submit" />
</form>
      

To handle this submission, extend HttpServlet and provide a doPost(HttpServletRequest, HttpServletResponse) method, as below.

… full answer hidden, click for full answers

Premium members click below for full answer
How do I get parameter values from a form submission?

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.

… full answer hidden, click for full answers

Premium members click below for full answer
The & in the parameter value truncates the string!

Q: How can I tell which submit button was activated?

A: In design terms, it is not a good idea for your application to have different outcomes from equivalent actions unless the consequences are quite clear to the person using the form. This is especially important for people with impaired vision, or those using screen readers. Nontheless, the example below shows how to markup your submit buttons to distinguish which was activated.

… full answer hidden, click for full answers

Premium members click below for full answer
How can I tell which submit button was activated?

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.

… full answer hidden, click for full answers

Premium members click below for full answer
Which link was followed to request my servlet?

Integration methods

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.

… full answer hidden, click for full answers

Premium members click below for full answer
How can I make the servlet output open in Microsoft Excel?

Q: How can I show my HTML markup as plain text?

A: To display HTML output in plain text format, you must set the HTTP Content-Type header to text/plain, as below:

… full answer hidden, click for full answers

Premium members click below for full answer
How can I show my HTML markup as plain text?

Q: How can I fix the Javascript in my servlet?

A: It can be very tricky inserting inline Javascript in servlet output because of the level of quoted output escaping that can be necessary. If you miss or fail to correctly escape a literal quote, your Javascript will not parse correctly. For simplicity, it would be preferable to use an external Javascript file.

… full answer hidden, click for full answers

Premium members click below for full answer
How can I fix the Javascript in my servlet?

Q: How do I include CSS in my servlet?

A: It is best to use an external style sheet reference, so that you can edit your servlet and CSS rules independently.

… full answer hidden, click for full answers

Premium members click below for full answer
How do I include CSS in my servlet?

Q: How can I pass user input through my spelling checker?

A: create an instance of your SpellChecker class in the doGet() or doPost() method of your servlet and pass the relevant parameter to it as a string, as in the code sample below ...

… full answer hidden, click for full answers

Premium members click below for full answer
How can I pass user input through my spelling checker?

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.

… full answer hidden, click for full answers

Premium members click below for full answer
How do I send data from an applet to a servlet?

Home · Web fonts · Font stacks · FAQs · Java · CSS · Javascript · HTML · Site manager