Developing a Controller Component : Part-2
In the Part-1 of Developing a controller component, we have studied information about controller types and creating HTML form etc. Now in this article we will study information related to controller servlet.
Developing a Controller Servlet:
Form processing (controller) servlets usually perform the following tasks:
- Retrieve form parameters from the HTTP request
- Perform any data conversation on the form parameters.
- Verify the form parameters.
- Execute the business logic.
- Dispatch to the next view components based on the results of the previous steps.
In this, we will see how to develop a controller servlet to handle Step 1 through 4.
Servlet API to Retrieve Form Parameters:
- The AddLeagueServlet is the controller aspect of the AddLeague Analysis model component. This servlet must be able to access the form data from the request object.
- Therefore, the ServletRequest interface includes the necessary APIs to access that data.
- The getParameter method takes a string argument, which is the name of the form field, and returns a string, which is the value of the form data that was entered by the user.
- So, if the user entered 2009 in the textfield, there the method call getParameter(“year”) would return the value 2009.
- The getParameters method is used for form components that might return more than one value.
- Checkbox and multiple selection list box components might return multiple values. This method does return an array of strings.
- The getParameterNames method returns a java.util.Enumeration object that lets you iterate over every field name in the form data sent in the HTTP request.
Developing the AddLeagueServlet Servlet:
In this, we will see how to develop a controller servlet. In stage 1, the AddLeagueServlet performs the following tasks:
- Retrieve form parameters from the HTTP request.
- Perform any data conversation on the form parameters.
- Verify the form parameters.
- Execute the business logic.
Code given below shows the declaration of the AddLeagueServlet class. This class extends the HTTPServlet class. However, notice that this class does implement the doPost method rather than doGet method. This is because the Add a New League form uses the POST HTTP method.
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.LinkedList;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class AddLeagueServlet extends HttpServlet {
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- List errorMsgs = new LinkedList();
Also, on line 12, a List object is being created called errorMsgs. This list contains a collection of strings, which are the error messages to be displayed back to the user. The first task of a form processing controller is to retrieve the form data parameters. This is accomplished using the getParameter method on the request object.
The second task is to perform data conversion of the form parameters to the proper data type required by the application. Recall that all form data is sent in the HTTP request as strings. For example, the year datum must be an integer. Therefore, the yearStr variable must be converted from a String to int. this is done in line 20 through 22. The parseInt static method on the Integer class performs this conversion. It throws a checked exception (NumberFormatException) if the input string is not an integer. Using the try-catch block lets you capture this data conversion error and an error message to our errorMsgs collection.
- try {
- // Retrieve form parameters
- String yearStr = request.getParameter(“year”).trim();
- String season = request.getParameter(“season”).trim();
- String title = request.getParameter(“title”).trim();
- // Perform data cob=nversion
- int year = -1;
- try {
year = Integer.parseInt(yearStr);
- } catch (NumberFormatException nfe) {
errorMsgs.add(“the year field must be positive integer.”);
- }
Also, notice that all of the control logic is wrapped in a try-catch block, which does start on line 14. Using a try-catch block in this way, you can catch any unexpected exceptions (such as NullPointerException) in your control logic. It is the best to handle these exceptions rather than forcing the web container to capture the exception. The web container issues an HTTP error 500 if a servlet throws a runtime exception. The third task of a controller is to perform form data verification.
- The year field must not be empty. The datum must be an integer. Both of these checks are performed during the data conversion step.
- The year field must be integer between 2000 to 2014.
- The season must be selected.
- The title field must not be empty.
- // varify form parameter
- if ((year != -1) && (year < 2000) && (year > 2014))
- {
errorMsgs.add(“the year field must within 2000 to 2014.”);
- }
- if (season.equals(“UNKNOWN”))
- {
errorMsgs.add(“Please select a league season”);
- }
- if (title.length() == 0)
- {
errorMsgs.add(“Please enter the title of the league.”);
- }
- // send the error page view if there were errors
- if (!errorMsgs.isEmpty())
- {
// dispatch to the error page
PrintWriter printWriter = response.getWriter();
printWriter.println(“Error Page”);
return;
- }
If any errors discovered in the data conversion or form verification steps, then the controller must not execute the business logic. Therefore, the code in lines 34 through 36 tests to see if any error messages were added to the errorMsgs list. If this test is true, then the controller servlet generates a simple text response and return.
The last task of the controller is to perform the business logic required to process the Add a New League form, the busness logic is the only executed if there were no data conversion or form verification errors. Therefore, the controller can assume that the data is valid for the operation. After the business logic is performed the controller servlet dispatches to the Success view.
- // perform business logic
- League league = new League(year, season, title);
- // send the success view
- PrintWriter printWriter = response.getWriter();
- println(“SUCCESS”);
- return;
Finally, all of the control logic code was wrapped in a try-catch block to catch any unexpected errors. Therefore, the doPost method does end in a catch block to capture any RunTimeExceptions. The text message of that exception is stored in the errorMsgs list and the ErrorPage view is displayed. Line 50 also sends the stack trace to the standard error stream, so you can debug your servlet.
- // handle any unexpected exceptions
- } catch (RuntimeException re) {
- add(re.getMessage());
- // dispatch to the error page
- PrintWriter printWriter = response.getWriter();
- println(“Error Page!”);
- // Log stack trace
- printStackTrace(System.err);
- }
- }
- }
- }
For more reading about technology news in singapore or from all over the world in all aspect from seo to online marketing do view more about other pages.