你需要这样做(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>