在struts中关于下载实例如下:
public class FirstAjaxAction {
public void ajaxTest() throws IOException{
// ServletActionContext.getRequest();
// ServletActionContext.getRequest().getSession();
// ServletActionContext.getServletContext();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
out.write("ceshi ajax!!!");
out.flush();
out.close();
}
}
public class SecondAjaxAction { //必须掌握
private InputStream inputStream;
public String ajaxTest() throws IOException{
inputStream = new ByteArrayInputStream("你好ajax!!!".getBytes("utf-8"));
return "ajaxTest";
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
/*
* 步骤:
* 1:copy jar 包 struts2-json-plugin-2.2.1.1.jar
*/
public class ThirdAjaxAction {
private String name;
private List<Person> personList;
public String ajaxTest(){
Person p1 = new Person(1,"张三");
Person p2 = new Person(2,"李四");
personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);
return "ajaxTest";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Person> getPersonList() {
return personList;
}
public void setPersonList(List<Person> personList) {
this.personList = personList;
}
}
public class DownLoadAction { //必须掌握 jsp 页面有个<a id="a2" href="downLoadAction">测试 下载</a>就可以咯
private InputStream inputStream;
private String fileName;
public String downLoadFile() throws FileNotFoundException{
fileName ="1511学生信息表.xlsx";
String realPath = ServletActionContext.getServletContext().getRealPath("resources/1511学生信息表.xlsx");
inputStream = new FileInputStream(realPath);
return "download";
}
public String getFileName() throws UnsupportedEncodingException {
return new String(fileName.getBytes("utf-8"),"iso-8859-1");
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
struts-xml的配置信息:
<struts>
<package name="default" namespace="/" extends="json-default">
<action name="firstAjaxAction" class="com.chdsxt.s2.action.FirstAjaxAction" />
<action name="secondAjaxAction" class="com.chdsxt.s2.action.SecondAjaxAction" >
<result name="ajaxTest" type="stream">
<!-- 此param匹配action内InputStream 类型的属性名,如果名字就是inputStream 则此元素可以省略<param name="inputName">inputStream</param>
-->
</result>
</action>
<action name="thirdAjaxAction" class="com.chdsxt.s2.action.ThirdAjaxAction" >
<result name="ajaxTest" type="json"></result>
</action>
<action name="downLoadAction" class="com.chdsxt.s2.action.DownLoadAction" method="downLoadFile" >
<result name="download" type="stream" >
<param name="contentDisposition">attachment; filename=${fileName}</param>
</result>
</action>
</package>
</struts>