关键代码:
package com.action; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import javax.servlet.http.HttpServletResponse; import com.entity.UserInfo; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.OgnlValueStack; import com.sun.xml.internal.ws.util.StringUtils; @SuppressWarnings("serial") public class LoginAction extends ActionSupport { private UserInfo user; private String jsonStr; private String msg; private ArrayList<UserInfo> userList = new ArrayList<UserInfo>(); @Override public String execute() { msg = "欢迎您 " + user.getUserName() + " 登陆 " + "您的密码是: " + user.getPassword(); userList.add(user); return SUCCESS; } public String downloadLocal() throws FileNotFoundException, UnsupportedEncodingException { HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); // 下载本地文件 String fileName = URLEncoder.encode("新建 文本文档.txt", "UTF-8"); // 文件的默认保存名 解决中文乱码问题 fileName = fileName.replace("+", "%20"); //当文件名中包含空格时 // 读到流中 InputStream inStream = new FileInputStream("c:/新建 文本文档.txt");// 文件的存放路径 // 设置输出的格式 response.reset(); response.setContentType("bin"); response.setCharacterEncoding("UTF-8"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // 循环取出流中的数据 byte[] b = new byte[1024]; int len; try { while ((len = inStream.read(b)) > 0) response.getOutputStream().write(b, 0, len); inStream.close(); } catch (IOException e) { e.printStackTrace(); } return SUCCESS; } public String getMsg() { return msg; } public UserInfo getUser() { return user; } public void setUser(UserInfo user) { this.user = user; } public String getJsonStr() { return jsonStr; } public void setJsonStr(String jsonStr) { this.jsonStr = jsonStr; } public void setMsg(String msg) { this.msg = msg; } public ArrayList<UserInfo> getUserList() { return userList; } public void setUserList(ArrayList<UserInfo> userList) { this.userList = userList; } }
效果图

、
