如何在Servlet中获取表单参数? request.getAttribute不起作用 [英] How to get a form parameter in servlet? request.getAttribute does not work

查看:412
本文介绍了如何在Servlet中获取表单参数? request.getAttribute不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让相同的servlet执行验证?看来这里可能必须利用某种递归,但是当我在电子邮件框中键入某些内容并单击提交时,电子邮件参数仍然为空. 单击提交后,URL更改为:http://localhost/servlet/EmailServlet?Email=test

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

页面显示Email: null和文本框,但是我希望它能够通过验证功能(即不为null).是否有可能实现这种递归行为?

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();        
    }
}

更新:正如公认的答案所指出,代码中有错误.将getAttribute更改为getParameter可解决问题" :).

Update: as the accepted answer pointed out, there was an error in the code. Changing the getAttribute to getParameter fixes the "problem" :).

字符串电子邮件= (字符串)请求. getAttribute getParameter("Email");

String email = (String) request.getAttributegetParameter("Email");

推荐答案

要在servlet中获取表单参数,请使用:

To get a form parameter in a servlet you use:

  request.getParameter("Email");

是的,您可以使用相同的servlet,但是使用两个不同的servlet来做到这一点会容易得多.

And yes you can use the same servlet but it would be way easier to use two different servlets to do this.

这篇关于如何在Servlet中获取表单参数? request.getAttribute不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆