表单提交两次,空值,并给我500错误

时间:2017-10-03 04:55:21

标签: java jquery ajax jsp servlets

我创建了一个登录表单,因为我想从JQUERY练习ajax。不幸的是,这个程序给了我意想不到的错误。

  • ISSUE 浏览器给我500错误:NullPointerException 所以我打印了用户名和密码。然后我看到一个按钮单击用户名和密码打印两次,第一次它是我输入的相同值,第二次用户名是Null密码类似于输入值。另一件事是虽然我注释掉了Ajax部分第二种情况正在发生(空用户名和输入密码打印)

JSP:

<form action="" style="border:1px solid #ccc" method="post">
<div class="container">
  <h2>LogIn Form</h2>
    <label><b>Email</b></label>
    <input type="text" placeholder="Enter Email" name="email" id="uName" required>

    <label><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" id="psw" required>

    <div class="clearfix">
      <button type="button" class="cancelbtn">Cancel</button>
      <button type="submit" class="signupbtn" id="login">LogIn</button>
    </div>
  </div>
</form>
  • JQUERY

    <script type="text/javascript">
        $(document).ready(function() {
            alert("qwqw");
            $('#login').click(function(){
                $.post('userRegistrationServlet',{
                    uName : $('#uName').val(),
                    psw : $('#psw').val()},
                    function(responseText) {
                        alert(uName);
                        alert("Login Successfully..!");
                    });
            });
        });
    </script>
    
  • 的Servlet

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");  
        //PrintWriter out = response.getWriter();
    
        String userName = request.getParameter("uName");
        System.out.println(userName+"uName");
        String psw = request.getParameter("psw");
        System.out.println(psw+"psw");
        RequestDispatcher rd;
        if(!userName.isEmpty()| userName != null){
        rd = request.getRequestDispatcher("/Header.html");
            rd.forward(request, response);
        }else{
            rd = request.getRequestDispatcher("/SignUp.jsp");
            rd.forward(request, response);
        }
    
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException{
        request.getRequestDispatcher("UserRegistration.jsp").forward(request,response);
    }
    

请帮我解决这个问题。谢谢你......!

2 个答案:

答案 0 :(得分:1)

我宁愿在表单的“submit”事件上放置一个事件处理程序,然后在事件上调用preventDefault()stopPropagation()

$("#myform").on("submit", function(e) {
    e.preventDefault();
    e.stopPropagation();
    $.post('userRegistrationServlet',{
            uName : $('#uName').val(),
            psw : $('#psw').val()},
            function(responseText) {
                alert(uName);
                alert("Login Successfully..!");
            });
});

答案 1 :(得分:0)

此按钮类型为“提交”,因此当您点击它时,您的表单将连贯地提交,但没有网址路径 登录