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.

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. public class AddLeagueServlet extends HttpServlet {
  10. @Override
  11. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. List errorMsgs = new LinkedList();

 

Design View Component Part-2

 

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.

  1. try {
  2. // Retrieve form parameters
  3. String yearStr = request.getParameter(“year”).trim();
  4. String season = request.getParameter(“season”).trim();
  5. String title = request.getParameter(“title”).trim();
  6. // Perform data cob=nversion
  7. int year = -1;
  8. try {

year = Integer.parseInt(yearStr);

  1. } catch (NumberFormatException nfe) {

errorMsgs.add(“the year field must be positive integer.”);

  1. }

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.
  1. // varify form parameter
  2. if ((year != -1) && (year < 2000) && (year > 2014))
  3. {

errorMsgs.add(“the year field must within 2000 to 2014.”);

  1. }
  2. if (season.equals(“UNKNOWN”))
  3. {

errorMsgs.add(“Please select a league season”);

  1. }
  2. if (title.length() == 0)
  3. {

errorMsgs.add(“Please enter the title of the league.”);

  1. }
  2. // send the error page view if there were errors
  3. if (!errorMsgs.isEmpty())
  4. {

// dispatch to the error page

PrintWriter printWriter = response.getWriter();

printWriter.println(“Error Page”);

return;

  1. }

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.

  1. // perform business logic
  2. League league = new League(year, season, title);
  3. // send the success view
  4. PrintWriter printWriter = response.getWriter();
  5. println(“SUCCESS”);
  6. 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.

  1. // handle any unexpected exceptions
  2. } catch (RuntimeException re) {
  3. add(re.getMessage());
  4. // dispatch to the error page
  5. PrintWriter printWriter = response.getWriter();
  6. println(“Error Page!”);
  7. // Log stack trace
  8. printStackTrace(System.err);
  9. }
  10. }
  11. }
  12. }

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.

Written by Sourabh Bhunje

Sourabh Bhunje, B.E. IT from Pune University. Currently Working at Techliebe. Professional Skills: Programming - Software & Mobile, Web & Graphic Design, Localization, Content Writing, Sub-Titling etc. http://techliebe.com/about-us

Leave a Comment