Is it possible to have the same servlet perform validation? It seems that one might have to utilize some sort of recursion here, but when I type in something in the e-mail box and click submit the e-mail parameter is still blank.
After I click submit, the URL changes to: http://localhost/servlet/EmailServlet?Email=test
The page shows Email: null
and the text box, but I was expecting it to go through the validation function (i.e. not be null). Is it possible to achieve this type of recursive behavior?
public class EmailServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String theForm =
"<FORM METHOD=\"GET\" ACTION=\"EmailServlet\">\n<INPUT TYPE=\"TEXT\" NAME=\"Email\"><P>\n"
+ "<INPUT TYPE=\"SUBMIT\">\n</FORM>";
String email = (String) request.getAttribute("Email");
// Bogus email validation...
if( email == null )
{
out.println("Email: " + email + "\n" + theForm);
}
else if(emailAddressNotBogous(email))
{
out.println("Thank you!");
}
else
{
out.println("“Invalid input. Please try again:\n" + theForm);
}
out.flush();
}
}
Update: as the accepted answer pointed out, there was an error in the code. Changing the getAttribute to getParameter fixes the "problem" :).
String email = (String) request.getAttributegetParameter("Email");
To get a form parameter in a servlet you use:
request.getParameter("Email");
And yes you can use the same servlet but it would be way easier to use two different servlets to do this.