最近做毕设发现Ajax提交到Struts后在Action里不需要out.write来构造html或xml了。因为可以就当没有Ajax存在一样去写Action,XMLHttpRequest就能获得Action所转发到的jsp生成的html。说起来很抽象,还是看代码:
login.jsp:
<%@ page language="java" pageEncoding="gbk"%>
<html>
<head>
<title>JSP for LoginForm form</title>
<script type="text/javascript">
function GE(a){return document.getElementById(a);}
function createXMLHttpRequest() {
var xmlhttp;
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function login(){
var xmlhttp = createXMLHttpRequest();
if(xmlhttp)
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
GE('msg').innerHTML=xmlhttp.responseText;
//alert(xmlhttp.responseText);
}else{
GE('msg').innerHTML=xmlhttp.statusText;
//alert(xmlhttp.statusText);
}
}else{GE('msg').innerHTML="正在提交数据...";}
};
xmlhttp.open('POST','login.do?name='+GE('name').value+'&password='+GE('password').value,true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<h2 align="center">Ajax应用实例: 登录模块</h2>
<form action="login.do" method="post">
帐号 : <input type="text" id="name" name="name"/><br>
密码 : <input type="password" id="password" name="password"/>
<br><input type="button" οnclick="login()" value="Ajax提交"><br><br>
<input type="submit" value="普通提交">
</form>
<div id="Layer1">
<div id="msg"></div>
</div>
</body>
</html>
struts-config.xml:
<action-mappings >
<action
attribute="loginForm"
input="/login.jsp"
name="loginForm"
path="/login"
scope="request"
type="com.neusoft.struts.action.LoginAction">
<forward name="loginSuccess" path="/loginSuccess.jsp" />
</action>
LoginAction.java:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
//LoginForm loginForm = (LoginForm) form;
String name = request.getParameter("name");
request.setAttribute("name", name);
System.out.println(name);
return mapping.findForward("loginSuccess");
}
loginSuccess.jsp
<body>
<h2 align="center" style="font-size: 20px;color: blue;">
登录成功!</h2><br>
getParameter:<%=request.getParameter("name") %>
getAttribute:<%=request.getAttribute("name") %>
</body>
就这样,login.jsp中的xmlhttp.responseText得到的字符串就是loginSuccess.jsp所生成的页面的源代码。
于是在Action里根本不需要构造html或xml或json了,只需把得到数据放到request里,然后转发到jsp(loginSuccess.jsp),在jsp里取出数据,显示;但这个jsp将自身源码以字符串形式传给Ajax页面(login.jsp)。多个jsp,但不需要手工构造 html或xml或json等了。
不知道这是不是个传递数据的捷径呢?