最近在看Struts和Ajax的书于是试着将Ajax与Struts整合在一起试下,发现没有想象中复杂.
使用Eclipse和Struts1.2
1.input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>input product</title>
</head>
<script type="text/javascript" src="ajax.js" ></script>
<body>
<input type="text" id="checkdate" />
<input type="button" value="send" onclick="javascript:validate()" />
<br>
<label id="messagelable"></label>
</body>
</html>
2.js文件
var xmlHttp;
//创建XMLHttp对象实例
function createXMLHttpRequest(){
if(window.ActiveXObject){//如果是IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
function validate(){
createXMLHttpRequest();
var date=document.getElementById("checkdate");
var url="checkdate.do?pro="+date.value;
xmlHttp.open("GET",url,true);//建立对Server调用
xmlHttp.onreadystatechange=callback;//回调callback函数
xmlHttp.send(null);//向Server发送请求
}
function callback(){
if(xmlHttp.readyState==4){//判断请求的状态(0=未初始化,1=正在加载,2=已经加载,3=交互,4=完成)
if(xmlHttp.status==200){//判断Server的Http状态码(200对应 ok , 404对应Not Found等)
var mes=xmlHttp.responseText;//Server响应,表示为一个串
setMessage(mes);
}
}
}
function setMessage(msg){
var msgobj=document.getElementById("messagelable");
msgobj.innerHTML="<font color=red >"+msg+"</font>";
}
3.Struts Action
package cxm.ajax;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.Action;
public class checkdate extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String checkstr = request.getParameter("pro");
PrintWriter out=response.getWriter();//对response对象写数据
if (checkstr.equals("cxm")) {
out.println("welcome cxm");
} else {
out.println("bad");
}
out.flush();
out.close();
return null;
}
}
4struts-config.xml
只要配置<action path="/checkdate" type="cxm.ajax.checkdate" />即可
本文介绍了一个简单的Struts与Ajax整合案例,通过输入日期验证的方式演示了如何使用Ajax进行异步请求,并通过Struts Action返回响应结果。
1884

被折叠的 条评论
为什么被折叠?



