Home

JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies


Capturing User Input with Forms

Working with forms in JSP is pretty straightforward, but does require a lot of hands-on code weaving. By this I mean that the individual form fields each need extra attention after the post for your application in order to capture and store data. There are some more advanced ways of dealing with handling the data after the post, which will be detailed after this basic example, that reduce the amount of work that needs to be done to handle the transactions.

When we are taking a basic approach to form handling we can use the following methods from the request object to grab each element from the form that was submitted.

getParameter
getParameter allows you to directly access a parameter from the request if you know the name of the parameter. An example that would retrieve the value for a form variable called “username” would be written as follows:

String sUserName = request.getParameter(“username”);

getParameterNames
getParameterNames returns a collection of each parameter name as a string. This is a good tool to use when attempting to debug a form when you are not entirely sure what is being sent to the target page. The following code sample will return a listing of all of the different form items with the parameter names (key) and values (value).

<%@ page contentType=”text/html” %>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core_rt” %>
<c:forEach var=’parameter’ items=’${paramValues}’>
<c:out value=’${parameter.key}’/> :
<c:forEach var=’value’ items=’${parameter.value}’>
<c:out value=’${value}’/>
</c:forEach>
<hr>
</c:forEach>

The following modified sample from the reference application uses a very basic, manually handled request process to complete the action of adding a customer account. The form is just simple HTML and contains form data that will be posted to “CustomerAddCommit-Scriptlet.jsp”.

CustomerAdd-Scriptlet.jsp

<%@page import=”java.sql.*” %>

<html>
<head>
<title>JSP and Beyond - Add Customer - Scriptlet Example</title>
</head>
<body>

<h1>Add Customer - Scriptlet Example</h1>
<form method=”post” action=”CustomerAddCommit-Scriptlet.jsp”>
Add Customer
<input type=”text” name=”Customer”>
<input type=”hidden” name=”CustomerID” value=”<%= request.getParameter(”CustomerID”) %>”>
<input type=”hidden” name=”action” value=”add”>
<br><br>
<input type=”submit” value=”Add Note”>
</form>
</body>
</html>

The following code block will then take all of the form data (post data) from the example above and store it in your database.

CustomerAddCommit-Scriptlet.jsp

<%@page import=”java.sql.*” %>

<html>
<head>
<title>JSP and Beyond - Add Customer - Scriptlet Example</title>
</head>
<body>
<%
if (request.getParameter(”CustomerName”) != null)
{
try {
Connection conn = null;

// Reference the JDBC driver
Class.forName(”com.mysql.jdbc.Driver”).newInstance();
conn = DriverManager.getConnection(”jdbc:mysql:///PortletCRM”,”root”, “ax355b”);
Statement stmt = conn.createStatement();

String sCustomerName = request.getParameter(”CustomerName”).toString();

stmt.executeUpdate(”INSERT INTO tblCustomer (CustomerName) VALUES (’” + sCustomerName + “‘)”);

// Close any connectivity that we had to the database to free resources
stmt.close();
conn.close();
}
catch (Exception ex)
{
out.println(”An Error has Occured: ” + ex.toString());
}
%>
<h1>Add Customer - Customer Added</h1>
<br>
<a href=”CustomerList-Scriptlet.jsp”>Main Menu</a>
<%
}
else
{
%>
<h1>Add Customer - Customer Name Empty</h1>
<br>
<a href=”CustomerAdd-Scriptlet.jsp”>Go back and try again</a>
<%
}
%>

</body>
</html>

Following is the complete example from the reference application where all of the code that allows a customer to be added is included. This is a slightly different approach that helps you reduce the number of JSPs required to create an application. You can see that the form posts to request.getRequestURI(), which is itself! Within the page code, the JSP will then decide whether it must display a data entry screen (if (request.getParameter(”action”) == null)) or if it will store the data from the form post back to itself (else if (request.getParameter(”action”).equals(”add”))).

CustomerAdd-Scriptlet.jsp

<%@page import=”java.sql.*” %>

<html>
<head>
<title>JSP and Beyond - Add Customer - JSTL Example</title>
</head>
<body>

<h1>Add Customer - JSTL Example</h1>

<% if (request.getParameter(”action”) == null)
{
%>
<h1>Add Customer - Scriptlet Example</h1>
<form method=”post” action=”<%= request.getRequestURI() %>”>
Add Customer
<input type=”text” name=”Customer”>
<input type=”hidden” name=”CustomerID” value=”<%= request.getParameter(”CustomerID”) %>”>
<input type=”hidden” name=”action” value=”add”>
<br><br>
<input type=”submit” value=”Add Note”>
</form>
<%
}
else if (request.getParameter(”action”).equals(”add”))
{
Connection conn = null;

// Reference the JDBC driver
Class.forName(”com.mysql.jdbc.Driver”).newInstance();
conn = DriverManager.getConnection(”jdbc:mysql:///PortletCRM”,”root”, “ax355b”);
Statement stmt = conn.createStatement();

//String sNote = request.getParameter(”Note”).toString();
String sCustomerName = request.getParameter(”CustomerName”);

stmt.executeUpdate(”INSERT INTO tblCustomer (CustomerName) VALUES (’” + sCustomerName + “‘)”);

// Close any connectivity that we had to the database to free resources
stmt.close();
conn.close();
%>
<h1>Customer Add - Customer Added</h1>
<br>
<a href=”CustomerList-Scriptlet.jsp”>Return to Main Menu</a>
<%
}
%>
</body>
</html>

One of the nice things about JavaBeans is the ability to leverage them for data storage from forms. The examples below highlight using a bean.to collect the data from a form post. This is done by using the following block of code in the FormToStore.jsp shown after the FormToBean.jsp below. It is interesting to note that in this sample code setting, the “property” attribute of the bean to a “*”, the bean will automatically map the input of form fields to attributes with the same names within the bean. It is a huge time saver.

<jsp:setProperty name=”FormBean” property=”*”/>

FormToBean.jsp

<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8″%>

<html>
<head>
<title>Account Signup</title>
</head>
<body>

<h1>Signup for Your Account</h1>

<form action=”FormToBeanStore.jsp” method=post>
Username <input type=”text” name=”username”><br>
Email <input type=”text” name=”email”><br>
<input type=”submit” value=”Submit”>
</form>

</body>
</html>

FormToStore.jsp

<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8″%>

<html>
<head>
<title>Account Signup</title>
</head>
<body>

<h1>Thanks!</h1>

<jsp:useBean id=”FormBean” class=”JSPBeyond.FormBeanSample” scope=”request”>
<jsp:setProperty name=”FormBean” property=”*”/>
</jsp:useBean>

This is what you submitted!<br>
Username <jsp:getProperty name=”FormBean” property=”username” /> <br>
Email <jsp:getProperty name=”FormBean” property=”email” />

</body>
</html>

Toward the end of this book I will review a very basic MVC framework that makes dealing with forms a bit easier, since you are able to handle the processing in a Java class.