如何使用jquery和ajax [重复]将数据从jsp发送到servlet

问题描述 投票:0回答:1

我是jquery和ajax的新手。我想检查给定的用户名是否存在于数据库中,如果可用,我想通过传递一条名为“用户名已存在”的消息来发出警报。我正在尝试应用jquery的blur方法,因此在提交表单之前,我可以获取有关该用户名的状态。请帮助我解决这个问题。

This is my JSP page

<body>

    <div class="container registration">
        <fieldset class="border p-2">
            <legend class="w-auto">Registration Form</legend>
            <form action="registration" method="post" id="registrationForm"
                onsubmit="return validation();">
                <div class="row" style="padding-bottom: 20px">
                    <div class="col">
                        <input type="text" class="form-control" name="firstName"
                            placeholder="First name" id="fname"> <span id="firstname"
                            class="text-danger font-weight-bold"></span>
                    </div>
                    <div class="col">
                        <input type="text" class="form-control" name="lastName"
                            placeholder="Last name" id="lname"> <span id="lastname"
                            class="text-danger font-weight-bold"></span>
                    </div>
                </div>

                <div class="row" style="padding-bottom: 20px">
                    <div class="col">
                        <input type="text" class="form-control" name="userName"
                            placeholder="UserName" id="uname"> <span id="username"
                            class="text-danger font-weight-thin"></span>
                    </div>
                    <div id="ajaxGetUserServletResponse"></div>
                </div>
                <!-- below jquery things triggered on onblur event and checks the username availability in the database -->
                <script type="text/javascript">
                    $(document).ready(function() {
                        alert("js is working");
                        $('#uname').blur(function() {
                            alert("blur is working")
                            $.ajax({
                                    type : 'post',
                                    url : 'registration',
                                    data : {
                                                uname : $('#uname').val()
                                            },
                                            success : function(responseText) {
                                                $('#ajaxGetUserServletResponse').text(responseText);
                                            }
                                    });
                            });
                    }); 
                </script>

This is my servlet

@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
    Registration userDetails = Utility.getRegistration();
    // RegistrationService registrationService = Utility.getRegistrationService();
    UserDetailsService userDetailsService = Utility.getUserService();
    JSONArray array = null;
    JSONObject jsonObject;
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String fName = req.getParameter("firstName");
        String lName = req.getParameter("lastName");
        String uName = req.getParameter("userName");
        String email = req.getParameter("email");
        String contactNumber = req.getParameter("contactNumber");
        String password = req.getParameter("password");

        userDetails.setFirstName(fName);
        userDetails.setLastName(lName);
        userDetails.setUserName(uName);
        userDetails.setEmail(email);
        userDetails.setMobile(contactNumber);
        userDetails.setPassword(password);

        try {
            jsonObject = UserDetailsRepository.getOneUserDetails(uName);
            if (jsonObject != null) {
                String msg = "User is already exist";
                resp.setContentType("text/plain");
                resp.getWriter().write(msg);
            //  throw new UserAlreadyExistException("User is already exist");
            } else {
                boolean result = userDetailsService.addUser(userDetails);
                if (result) {
                    req.setAttribute("insert", "Data is added into the table successfully!!!");
                    resp.sendRedirect("index.jsp");
                } else {
                    req.setAttribute("message", "Something went wrong!!!");
                    resp.sendRedirect("error.jsp");
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

jquery ajax jsp servlets
1个回答
0
投票

我知道您想检查用户是否已经存在。您做得差不多。

 $.ajax({
                                type : 'post',
                                url : 'registration',
                                data : {
                                            uname : $('#uname').val()
                                        },
                                        success : function(responseText) {
                                            $('#ajaxGetUserServletResponse').text(responseText);
                                        }
                                });
                        });

您正在ajax中使用名为uname的参数发送数据,但是servlet不会使用该名称获得任何信息。您应该执行以下操作:

String uName= req.getParameter("uname");

并与uName一起检查所需的内容。我不确定这是否如您所愿,因为您的表单也触发了servlet。您应该根据名称来区分通话。当您调用ajax时,除发送的uname以外,其他所有参数都将为null(如果用户键入了某些内容。也许也要先检查吗?)。但是,当发送表单时,来自ajax的uname将为空。

也许像这样:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    if(request.getParameter("userName") != null) {
        formCall(request,response);
    }

    if(request.getParameter("uname") != null) {
        ajaxCall(request,response);
    }
}

private void ajaxCall(HttpServletRequest request, HttpServletResponse response) {
    System.out.println("Ajax call " + request.getParameter("uname"));

}

private void formCall(HttpServletRequest request, HttpServletResponse response) {
    System.out.println("Form call " + request.getParameter("userName"));

}

。blur中的ajax调用跳到一个方法,而表单提交到另一个方法。

错误行为:如果用户加载页面,请单击文本字段,然后单击按钮,这将同时触发.blur和提交。也许您也不想这样做。

© www.soinside.com 2019 - 2024. All rights reserved.