gpt4 book ai didi

java - 如何写入 HttpServletResponse 响应对象?

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:44 24 4
gpt4 key购买 nike

我有这个 Action 类,这个类负责我的响应

Update 现在传递来自 DownloadStatus 类的响应,但看起来它是 null

public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware
{
static Logger logger = Logger.getLogger(DownloadStatus.class);
private HttpServletRequest request;
private HttpServletResponse response;
private File cfile;
private String cfileFileName;

@Override
public String execute()
{

logger.debug("Inside DownloadStatus.execute method")

try {
ChainsInvoker invoker = new ChainsInvoker()
def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName)
if(executionResponse == null || ErrorHandler.checkIfError(executionResponse))
{
return ERROR
}
response.setContentType("APPLICATION/xml")

logger.debug("filename: $cfileFileName")

response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"")
response.getWriter().print(executionResponse)
logger.debug("executionResponse :" + executionResponse)
invoker.invoke(MYChains.clean)
}catch (Exception exp) {

logger.error("Exception while Creating Status ")
logger.error(exp.printStackTrace())

}
return NONE
}

@Override
public void setServletRequest(HttpServletRequest request) { this.request = request; }

@Override
public void setServletResponse(HttpServletResponse response) { this.response = response; }

public File getcfile() { cfile }

public void setcfile(File cfile) { this.cfile = cfile }

public String getcfileFileName() { cfileFileName }

public void setcfileFileName(String cfileFileName){ this.cfileFileName = cfileFileName }
}

和下面的类将流写入响应

class DownloadStatusResponse implements Command {   

static Logger logger = Logger.getLogger(DownloadStatusResponse.class);
@Override
public boolean execute(Context ctx) throws Exception
{
logger.debug("Inside DownloadStatusResponse.execute() method")
OutputStream response = null;

if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0 )
{
HttpServletResponse resp = ctx.get(ContextParams.response)
/*I am trying to get Response here*/

response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp)
}

logger.debug("Response: " + response)
ctx.put(ContextParams.response,response); /*ContextParams is a enum of keywords, having response*/
return false;
}

private OutputStream downloadStatusFile(String filename,HttpServletResponse resp)
{
logger.info("Inside downloadStatusFile() method")

File fname = new File(filename)
if(!fname.exists())
{
logger.info("$filename does not exists")
return null
}
else
{

resp.setContentType("APPLICATION/xml")
/*Exception: cannot setContentType on null object*/

resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"")

FileInputStream istr = new FileInputStream(fname)
OutputStream ostr = resp.getOutputStream()
/*I need to use resp.getOutputStream() for ostr*/

int curByte=-1;

while( (curByte=istr.read()) !=-1)
ostr.write(curByte)

ostr.flush();
}
return ostr
}

}

我的问题是ostr如何返回到DownloadStatus类中的response

更新(工作测试 servlet)

我在下面有一个 servlet,它负责将文件内容放入流中并将其返回给 HttpServletResponse,但我想在上面的代码中使用它

    public class DownloadServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

String fileName = req.getParameter("zipFile");

if(fileName == null) return;

File fname = new File(fileName);
System.out.println("filename");
if(!fname.exists()) {System.out.println("Does not exists"); return;}

FileInputStream istr = null;
OutputStream ostr = null;
//resp.setContentType("application/x-download");
resp.setContentType("APPLICATION/ZIP");
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"");
System.out.println(fname.getName());
try {
istr = new FileInputStream(fname);
ostr = resp.getOutputStream();
int curByte=-1;

while( (curByte=istr.read()) !=-1)
ostr.write(curByte);

ostr.flush();
} catch(Exception ex){
ex.printStackTrace(System.out);
} finally{
try {
if(istr!=null) istr.close();
if(ostr!=null) ostr.close();
} catch(Exception ex){

ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
try {
resp.flushBuffer();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}

最佳答案

据我了解,您需要的只是如何使用 Struts2 下载文件。

你需要这样的东西是你的 struts.xml 文件

<action name="downloadfile" class="DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="document.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>

代码:

public class DownloadAction extends ActionSupport {

private InputStream inputStream;

public InputStream getInputStream() {
return inputStream;
}

public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}

public String execute() throws FileNotFoundException {
String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
File f = new File(filePath + "/nn.pdf");
System.out.println(f.exists());
inputStream = new FileInputStream(f);
return SUCCESS;
}
}

关于java - 如何写入 HttpServletResponse 响应对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com