How to get a form parameter in servlet? request.getAttribute does not work

有些话、适合烂在心里 提交于 2019-12-04 14:00:05

问题


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");


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!