Knowledgebase: Java/JSP Hosting Plans
Implementing a Form in a JSP Page
Posted by Customer Service on 25 May 2005 12:55 AM
There are many different strategies for implementing a form. Some strategies involve a JSP page that shows the form and another to show field validation errors. This example combines both pages in one since in most cases, the page that shows validation errors looks like the original page except for error messages next to the fields with errors.

When the page is first shown, no validation is done. When the form is submitted, the new values are submitted to the same page except that this time, the page will validate the values. If the values are all valid, the form is processed and the browser is redirected to a success page.

The above behavior is implemented using a request parameter called process. If set to "true", the page will validate the values and possibly process the form; otherwise, the page simply shows a blank form. The request parameter is added when the user submits the form.

It is good practice to avoid placing the form validation code in the JSP page. The example encapsulates the validation and form processing code in a bean called com.mycompany.MyForm. When the form is submitted, an instance of this bean is instantiated and loaded with the submitted values for validation and processing.

It is also considered good practice not to place error messages in business objects such as in the MyForm class. The strategy used in this example is to create and store a map of error messages in the page instance and supply this map to every new MyForm instance to use. In this way, all presentation related information is contained in one JSP file. This makes it easier to maintain and potentially localize the page. Another strategy is to use resource bundles. However, unless all content on the page is moved in the resource bundle, it may be simpler to keep the error messages in the page to avoid having to manage two sources of content.
(499 vote(s))
Not helpful

Comments (0)