Your banner ad here

WestNIC provides reliable web hosting services

25% off cpanel web hosting and reseller hosting deals. Promo: codestyle25off

Site navigation below

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

RSS news feed Get the latest answers in this FAQ

Follow the Code Style Twitter feed for free one-to-one help sessions by instant messenger: MSN, AIM and Yahoo! Messenger. Sessions are held most Saturdays. Join the Twitter feed then check your direct messages for details.

Servlet "how to"

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
Can I catch an exception and give my own error message?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
Can I call the doPost() method from a hyperlink?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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();
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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);
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How do I get the uploaded file name?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
Can I get the client IP and MAC address?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I check what parameters are available in the request?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How do I get parameter values from a form submission?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
The & in the parameter value truncates the string!

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I tell which submit button was activated?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
Which link was followed to request my servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I make the servlet output open in Microsoft Excel?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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:

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I show my HTML markup as plain text?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I fix the Javascript in my servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I include CSS in my servlet?

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

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How do I include CSS in my servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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 ...

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How can I pass user input through my spelling checker?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

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.

Premium Content: Follow this link for subscription information More details available to premium content service subscribers:
How do I send data from an applet to a servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Add this page to your chosen social bookmarking service

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log