如何从HTML表单调用servlet

时间:2015-07-14 14:46:09

标签: java html forms servlets

我在Web应用程序中将html表单连接到Servlet时遇到问题。这是html文件:



<form method="post" class="/Login" action="/Login">
		<fieldset class="textbox">
						
                      <label class="textbox_field">
                        <span>Username or Email</span>
                        <input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
                      </label>

                      <label class="textbox_field">
                        <span>Password</span>
                        <input id="password" name="password" value="" type="password" placeholder="Password">
                      </label>

                      <button class="submit_button" type="submit">Sign-In</button>
                </fieldset>
</form>
&#13;
&#13;
&#13;

这是servlet,名为Login:

 @WebServlet("/Login")
    public class Login extends HttpServlet {
        private static final long serialVersionUID = 1L;

    public Login() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("in doPost...");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String pass = request.getParameter("password");

        if(Validate.checkUser(username, pass))
        {
            RequestDispatcher rs = request.getRequestDispatcher("Welcome");
            rs.forward(request, response);
        }
        else
        {
           out.println("Username or Password incorrect");
           RequestDispatcher rs = request.getRequestDispatcher("index.html");
           rs.include(request, response);
        }
    }

}

我没有编辑web.xml文件,因为使用&#34; Servlet 3.0,servlet可以通过类上的@WebServlet注释进行配置,而无需web.xml &#34 ;.如果我误解了这句话,显然会纠正我。

最后,这是Project Explorer的一个片段,请注意home.jsp是表单所在的文件:

enter image description here

注意:遗憾的是,stackoverflow上其他类似问题中提供的解决方案在我的案例中不起作用。

1 个答案:

答案 0 :(得分:2)

您需要使用提交替换输入类型按钮。

<input type="submit" value="Submit"/>