struts2 和 ajax的交互

struts2的配置

<action name="getyzm" class="com.pwq.GetYZM">
 	<result name="success" type="stream">
 		<param name="contentType">text/html</param>
 		<param name="inputName">textStream</param>
 		<param name="bufferSize">1024</param>
 	</result>
 </action>

jsp的代碼如下,定義了一個流type="stream",返回的是文件,textStream

<script type="text/javascript">
	function captcha() {
		var xmlhttp;
		if(window.XMLHttpRequest){
			xmlhttp = new XMLHttpRequest();
		}
		else {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		if(xmlhttp != null) {
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState==4 && xmlhttp.status==200){
					document.getElementById('testText').innerHTML = xmlhttp.responseText;
				}
			}
			xmlhttp.open("POST", "getyzm.action", true);
			xmlhttp.send();
		} else alert("XMLHTTPREQUEST 創建失敗!");
	}
</script>


package com.ssh.pwq.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;  
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class GetYZM extends ActionSupport{  
    private InputStream textStream;  

	public InputStream getTextStream() {
		return textStream;
	}

	public void setTextStream(InputStream textStream) {
		this.textStream = textStream;
	}

	public String execute() throws Exception {
		HttpServletRequest request = null;
		request = ServletActionContext.getRequest();
		String name = (String)request.getSession().getAttribute("code");
		System.out.println("name=>" + name);
		textStream = new ByteArrayInputStream(name.getBytes("UTF-8"));   
       		return SUCCESS;  
   	}
}  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章