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.
you could have the form's method set to POST and then implement a doPost() method in your servlet. the doGet() will get called to display the form and the doPost() will get called to process the form submission.
alternatively you could have the doGet() method test for the presence of any parameters. if there aren't any then just display the form. if there are then process the submission...
来源:https://stackoverflow.com/questions/2292260/how-to-get-a-form-parameter-in-servlet-request-getattribute-does-not-work