5. Putting the code to test:
So, let try to put a small test case for our application.
Test Case 1:
- Access URL http://localhost:8080/simple-webapp/MyFirstPage.html
- Enter First name and last name in the text field and hit the submit button
Expected Result: The following should be displayed
Name: <first name> <last name>
Test Case 2:
- Access URL http://localhost:8080/simple-webapp/MyFirstPage.html
- Leave either first name or last name or both blank, and hit the submit button
Expected Result: The page should submit and reload the same page with a error message
Test Case 1 Execution:
Boooom!
Actual Result: The same page is reloading.... (failed)
Lets try to resolve this issue.
First lets see, if the servlet is getting called.
Our mapping in the web.xml is <url-pattern>/servlet/*</url-pattern>
So, lets see if the form is submitting to the current URL.
<form name="form" action="">
There we are! The action is submitting no where. Lets correct this line to
<form name="form" action="servlet/MyFirstServlet">
Now then, lets retest case #1.
Thats great! We get the result as expected.
Test Case 2 Execution:
So, for testing this case, let us leave either First Name or Last Name blank and submit. It comes back to the same page..... but looks like the error message is missing.... isn't it? Yes, right. But, why so? The servlet is setting the error message and sending back to the HTML page.Well, our HTML is static and does not have the ability to get dynamic information. We need the ability to read from 'request' and display in the page dynamically.
No prizes for guessing... but, we need JSPs for this. The JSP will be HTML with extra Java code embedded for reading the error message from request and displaying.
Below is our new MyFirstJspPage.jsp created from MyFirstPage.html:
<html>
<head>
<title>First JSP</title>
</head>
<body>
<div id="error" style="display:block;"><font color="red">
<%if(request.getAttribute("errMsg")!=null) { out.println(request.getAttribute("errMsg"));} %>
</font></div>
<form name="form" action="">
First Name: <input type="text" name="firstName" ><br>
Last Name: <input type="text" name="lastName" ><br><br>
<input type="submit" name="submit" value="Submit" >
</form>
</body>
</html>
Are we good to retest case #2? Hey wait! Our servlet is forwarding the request back to HTML. We need to correct that right?
Right... We need to correct this in our servlet MyFirstServlet.
Modify the below line:
request.getRequestDispatcher("../MyFirstPage.html").forward(request, response);
to
request.getRequestDispatcher("../MyFirstJspPage.jsp").forward(request, response);
After making the correction, in MyFirstServlet.java, we need to compile the class file.
Now, we are ready to retest case #2.
Now, if either first name or last name is left empty, the same page loads with appropriate error message.
Finally, both the test cases have been executed successfully!
Welcome to Web application development!!