Form processing using Bean


 

Form processing using Bean

In this section, we will create a JSP form using bean ,which will use a class file for processing.

In this section, we will create a JSP form using bean ,which will use a class file for processing.

Form processing using Bean

In this section, we will create a JSP form using bean ,which will use a class file for processing. 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. The html form looks like this :

<HTML>

<BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">

<strong>ENTER INFORMATION :</strong><br>

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 the data entered in form, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge".  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 upper-cased.  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.

beanformprocess.java

package foo;

public class beanformprocess {

String username;

String email;

int age;

public void setUsername( String value )

{

username = value;

}

public void setEmail( String value )

{

email = value;

}

0

public void setAge( int value )

{

1

age = value;

}

2

public String getUsername() { return username; }

public String getEmail() { return email; }

3

public int getAge() { return age; }

}

4

beanformprocess1.jsp

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

<jsp:useBean id="user" class="foo.beanformprocess" scope="session"/>

5

<jsp:setProperty name="user" property="*"/>

<HTML>

<BODY>

6

<A HREF="NextPage.jsp">Continue</A>

</BODY>

</HTML>

7

The "setProperty" tag will automatically collect the input data, match names against the bean method names, and place the data in the bean.

beanformprocess2.jsp

Let us create "beanformprocess2.jsp" to retrieve the data from bean..

8

<jsp:useBean id="user" class="foo.beanformprocess" scope="session"/>

<HTML>

<BODY>

9

You entered<BR>

Name: <%= user.getUsername() %><BR>

Email: <%= user.getEmail() %><BR>

0

Age: <%= user.getAge() %><BR>

</BODY>

</HTML>

1

OUTPUT :

After submitting value the next page appears  like this:

2

Download Source Code

Ads