Programming Tutorials

Form processing in JSP

By: aathishankaran in JSP Tutorials on 2007-02-13  

Forms are a very common method of interactions in web sites. JSP makes forms processing especially easy.

The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. You just need to define a class that has a field corresponding to each field in the form. The class fields must have "setters" that match the names of the form fields.

create GetName.html as below

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is just a method that starts with "set" followed by the name of the field. The first character of the field name is uppercased. So if the field is "email", its "setter" method will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public.

package user;
public class UserData {
    String username;
    String email;
    int age;
     public void setUsername( String value )
    {
        username = value;
    }
     public void setEmail( String value )
    {
        email = value;
    }
     public void setAge( int value )
    {
        age = value;
    }
     public String getUsername() { return username; }

     public String getEmail() { return email; }

     public int getAge() { return age; }
}

The method names must be exactly as shown. Once you have defined the class, compile it and make sure it is available in the web-server's classpath. The server may also define special folders where you can place bean classes, e.g. with Blazix you can place them in the "classes" folder. If you have to change the classpath, the web-server would need to be stopped and restarted if it is already running.

Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named user under the classpath entry.

Now let us create "SaveName.jsp" to use a bean to collect the data.

<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JSP )

Latest Articles (in JSP)