Reputation: 571
I have a login form in my jsp file that is referring to a javascript function using onclick function,
The javascript function is supposed to to call an action method to do the authorization process and return the results.
Result can be a message of error (user name is wrong) or (username or password is wrong) or a success message (return "SUCCESS") to get to new page,
any time that it calls the action the alert(xmlHttp.status) shows that it receives "undefined" it is calling a correct action but its problem is on receiving the response.
how should I define the struts.xml? maybe the problem is caused by it.
<s:submit onclick="auth(this.form)" />
xmlhttp.open("get","Login.action?usrname="+usr+"&pass="+psw,false);
xmlhttp.send();
Upvotes: 0
Views: 2465
Reputation: 8971
You need to do like this (Struts2, JSON, Ajax)
struts.xml
<package name="default" extends="json-default">
<action name="ValidateUserName" class="com.controller.JSONUserAction">
<result type="json"></result>
</action>
</package>
Controller Class Code JSONUserAction.java (in your case 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 code
<%@ 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>
Upvotes: 1