如何从struts动作类返回对ajax的多个响应?

时间:2013-12-24 06:49:18

标签: java jquery ajax jsp struts-1

我需要从struts(1.3.10)动作类返回对ajax的响应。 我正在使用PrintWriter类将响应返回给客户端(浏览器)。它有时只工作但有时候会在jsp页面显示响应。

这是我的jsp和ajax函数:

<html:submit property="" styleClass="btn btn-success" onclick="doChangePassword()">Ok</html:submit>

 <script type="text/javascript">
        function doChangePassword(){
            //get the form values
            var oldPassword = $('#oldPassword').val();
            var newPassword = $('#newPassword').val();
            var confirmPassword = $('#confirmPassword').val();
            //                alert(customerName+" "+imeiNo+" "+targetName+" "+simNo+" "+duedate+" "+remark);

            $.ajax({
                type: "POST",
                url: "/GPS-VTS/change_account_password.do",
                data: "oldpassword="+oldPassword+"&newpassword="+newPassword+"&confirmpassword="+confirmPassword,
                dateType: "string",
                success: function(response){
                                                            alert(response);
                    var result = $.trim(response);
                    //                                                alert(result);
                    if(result === "oldPassword")
                    {

                            //  Example.show("Hello world callback");
                            alert("Please provide valid entries for Old Password field.");
                            $('#oldPassword').val("");
                        //alert('Product sold successfully.');


                    }
                    else if(result === "newPasswordEmpty"){
                        alert("Please provide valid entries for New Password field.");
                    }
                    else if(result === "newPassword")
                    {
                            alert("Please provide valid entries for New or Confirm Password fields.");
                            $('#newPassword').val("");
                            $('#confirmPassword').val(""); 
                    }else if(result === "success")
                    {
                            alert("Password Successfully Changed.");
                            $('#oldPassword').val("");
                            $('#newPassword').val("");
                            $('#confirmPassword').val("");    

                    }
                },
                error: function(e){
                    alert('Error :'+e);
                }

            });
        }
    </script>

这是我的动作类(account_password_action.java):

public class account_password_action extends org.apache.struts.action.Action {

/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
private long account_id;
private String encrypted_password = new String();
private String account_name = new String();
private String account_password = new String();

/**
 * This is the action called from the Struts framework.
 *
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 * @throws java.lang.Exception
 * @return
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {




    /*Get Session Value*/
    String acc_name = request.getSession().getAttribute("login_name").toString();

    /*Create Session Factory Object*/
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();

    Transaction t = session.beginTransaction();

    /*Extract user data from Bean class -> account_bean.java*/
    account_password_bean fromBean = (account_password_bean) form;
    String old_password = fromBean.getOldpassword();

    /*get encrypted password from database*/
    Query enc_password = session.createQuery("from account_dao where name=?");
    enc_password.setString(0, acc_name);
    List list = enc_password.list();
    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
        account_dao account = (account_dao) iterator.next();
        account_id = account.getId();
        account_name = account.getName();
        encrypted_password = account.getPassword();
    }

    /*Decrypt the password using AES algorithm*/
    account_password = AESencrp.decrypt(encrypted_password.toString().trim());

    if (!old_password.equals(account_password)) {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("oldPassword");
        out.write("oldPassword");
        out.flush();
        return null;
    }
     else if(fromBean.getNewpassword().equals("") || fromBean.getNewpassword() == null)
    {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("newPasswordEmpty");
        out.write("newPasswordEmpty");
        out.flush();
        return null;
    } 
    else if (fromBean.getNewpassword().equals(fromBean.getConfirmpassword())) {
        String new_password = fromBean.getNewpassword();
        String new_enc_password = AESencrp.encrypt(new_password.toString().trim());
        Query update_query = session.createQuery("update account_dao set password = :newPassword" + " where id = :Id");
        update_query.setParameter("newPassword", new_enc_password);
        update_query.setParameter("Id", account_id);
        int update_status = update_query.executeUpdate();
        t.commit();
    } 
    else {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("newPassword");
        out.write("newPassword");
        out.flush();
        return null;
    }


    PrintWriter out = response.getWriter();
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("cache-control", "no-cache");
    out.write("success");
    out.flush();
    return null;
    //return mapping.findForward(SUCCESS);

}

}

这是我在Chrome浏览器中的输出:

enter image description here enter image description here

firefox浏览器:

enter image description here

有时它会在警告框中显示正确的输出:

enter image description here enter image description here

大家好,请帮我看看每次在警报框中显示回应。 我能做什么?什么问题?我怎么解决呢?任何浏览器版本问题?

请帮助我们.........

先谢谢。

1 个答案:

答案 0 :(得分:2)

在您的ajax调用中,提供其他参数async : false

   $.ajax({
                    type: "POST",
                    url: "/GPS-VTS/change_account_password.do",
                    async: false,
                    data: "oldpassword="+oldPassword+"&newpassword="+newPassword+"&confirmpassword="+confirmPassword,
                    dateType: "string",
                    success: function(response){
                     .....

           }

请参阅 this ,详细了解ajax中的同步和异步调用。
有关ajax调用的详情,请参阅 this

相关问题