struts2本身对ajax技术提供了强有力的支持,用户只需一些简单的配置,就完成了异步交互。代码如下:
首先,任意的一个jsp页面,用于提交表单:
<s:form action="login" method="post">
<div id="show"></div>
<s:textfield name="name" label="用户名" id="name"></s:textfield>
<s:textfield name="password" label="密码" id="password"></s:textfield>
<input id="loginbt" type="button" value="提交"/>
</s:form>
接下来在项目web-root下新建js文件夹,加入:jquery.js文件,再新建ajax.js文件。代码如下:
$(document).ready(function()
{
$("#password").blur(function()
{
var name=$("#name").val();
var password=$("#password").val();
$.post("login.action", { name: name, password: password },
function(data){
$("#show").html(data);
});
});
});
Action类,代码:
package com.guang.action;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private String name;
private String password;
private InputStream inputStream;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public InputStream getResult(){
return inputStream;
}
@Override
public String execute() throws Exception {
System.out.println(name+password);
inputStream =name.equals("guangge") && password.equals("123456")
? new ByteArrayInputStream("恭喜你登录成功!".getBytes("UTF-8"))
: new ByteArrayInputStream("对不起用户名和密码不匹配!".getBytes("UTF-8"));
return SUCCESS;
}
}
上面的代码,与其他的action类不一样的,是
private InputStream inputStream;
public InputStream getResult(){
return inputStream;
}
其他的都差不多。
配置文件:struts.xml文件:
<package name="login" extends="struts-default">
<action name="login" class="com.guang.action.LoginAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">result</param>
</result>
<result name="login">/index.jsp</result>
</action>
</package>
现在,一起都OK了/希望对你有帮助。