0

我的 jsp 文件中有一个登录表单,它引用了一个使用 onclick 函数的 javascript 函数,

javascript函数应该调用一个动作方法来进行授权过程并返回结果。

结果可以是错误消息(用户名错误)或(用户名或密码错误)或成功消息(返回“SUCCESS”)以进入新页面,

每当它调用该操作时,alert(xmlHttp.status) 都会显示它收到“未定义”,它正在调用正确的操作,但它的问题在于接收响应。

我应该如何定义struts.xml?也许问题是由它引起的。

<s:submit onclick="auth(this.form)" />

xmlhttp.open("get","Login.action?usrname="+usr+"&pass="+psw,false);
xmlhttp.send();
4

1 回答 1

1

你需要这样做(Struts2、JSON、Ajax)

struts.xml

<package name="default"  extends="json-default">
        <action name="ValidateUserName" class="com.controller.JSONUserAction">          
            <result type="json"></result>
        </action>
</package>

控制器类代码 JSONUserAction.java(在您的情况下为 Login.java)

package com.controller;

import com.opensymphony.xwork2.ActionSupport;

public class JSONUserAction extends ActionSupport {

    private String username;
    private String result;  

    // all struts logic here
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

    public String execute() {
        if(username.equalsIgnoreCase("admin")) {
            result = "VALID";
        } else {
            result = "INVALID";
        }
        System.out.println("username :  " + username + "======== result :" + result);
        return ActionSupport.SUCCESS; 
    }

}

login.jsp 代码

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script type="text/javascript">

    var http;
    if(window.XMLHttpRequest) {
        http = new XMLHttpRequest();
    } else {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }

    function AuthenticateUser() {               
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;

        http.open("POST", "ValidateUserName.action", true);
        http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        http.onreadystatechange = ValidUser;
        http.send("username="+username +"&password="+password);
    }

    function ValidUser() {      
        if(http.readyState == 4 && http.status == 200) {
            var jsonOP  = eval ("(" + http.responseText + ")");         
            var result = jsonOP.result;         
            document.getElementById("message").innerHTML = result;
            if(result == "VALID") {
                //redirect to welcome page                              
            } 
        }
    }

</script>
</head>

<body>

<s:form action="Welcome">
    <div id="message"></div>
    <s:textfield name="username" label="Username" id="username" />
    <s:password name="password" label="Password" id="password"/>
    <s:submit id="login" onClick="AuthenticateUser();"/>
</s:form>

</body>
</html>
于 2012-09-20T10:01:24.717 回答