Action代码如下:
package org.crazyit.app.action;
import com.opensymphony.xwork2.Action;
import java.io.*;
public class LoginAction
implements Action
{
//封装请求参数的两个属性
private String user;
private String pass;
//封装输出结果的二进制流
private InputStream inputStream;
//user属性的setter和getter方法
public void setUser(String user)
{
this.user = user;
}
public String getUser()
{
return this.user;
}
//pass属性的setter和getter方法
public void setPass(String pass)
{
this.pass = pass;
}
public String getPass()
{
return this.pass;
}
public InputStream getResult()
{
return inputStream;
}
public String execute()
throws Exception
{
//判断用户名、密码,生成对应的响应
inputStream = user.equals("crazyit.org") && pass.equals("leegang")
? new ByteArrayInputStream("恭喜你,登录成功!"
.getBytes("UTF-8"))
: new ByteArrayInputStream("对不起,用户名、密码不匹配!"
.getBytes("UTF-8"));
return SUCCESS;
}
}
struts.xml配置
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"/>
<package name="lee" extends="struts-default">
<action name="loginPro" class="org.crazyit.app.action.LoginAction">
<result name="success" type="stream">
<!-- 指定下载文件的文件类型 -->
<param name="contentType">text/html</param>
<!-- 指定由getResult()方法返回输出结果的InputStream -->
<param name="inputName">result</param>
</result>
<!-- 定义一个名为login的结果 -->
<result name="login">/WEB-INF/content/login.jsp</result>
</action>
<action name="*">
<result>/WEB-INF/content/{1}.jsp</result>
</action>
</package>
</struts>
login.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>使用JSON插件</title>
<script src="${pageContext.request.contextPath}/jquery-1.4.4.min.js"
type="text/javascript">
</script>
</head>
<body>
<s:form id="loginForm">
<s:textfield name="user" label="用户名"/>
<s:textfield name="pass" label="密码"/>
<tr><td colspan="2">
<input id="loginBn" type="button" value="提交"/>
</td></tr>
</s:form>
<div id="show" style="display:none;">
</div>
<script type="text/javascript">
//为id为loginBn的按钮绑定事件处理函数
$("#loginBn").click(function()
{
//指定向loginPro发送请求,以id为loginForm表单里各表单控件作为请求参数
$.get("loginPro" , $("#loginForm").serializeArray() ,
//指定回调函数
function(data , statusText)
{
$("#show").height(80)
.width(300)
.css("border" , "1px solid black")
.css("background-color" , "#efef99")
.css("color" , "#ff0000")
.css("padding" , "20px")
.empty();
$("#show").append("登录结果:" + data + "<br />");
$("#show").show(2000);
},
//指定服务器响应为html
"html");
});
</script>
</body>
</html>
注意要导入jquery-1.4.4.min.js到项目中