gpt4 book ai didi

java - 在 Struts2 中提交响应后无法调用 sendRedirect()

转载 作者:行者123 更新时间:2023-11-30 08:11:56 25 4
gpt4 key购买 nike

我在一个小型 Web 应用程序中使用 struts2 和 jasper 报告。当我尝试导出报告时,出现以下错误。报告导出成功,但日志中打印错误,并且执行操作后 struts 也无法重定向到成功页面。

我已经通过互联网搜索了这一点,但我无法澄清这一点。有人可以帮我澄清这一点吗?

    ERROR Dispatcher - Exception occurred during processing request: Cannot call sendRedirect() after the response has been committed
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:482)
at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(HttpServletResponseWrapper.java:137)
at org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper.sendRedirect (SaveContextOnUpdateOrErrorResponseWrapper.java:74)
at org.apache.struts2.dispatcher.ServletRedirectResult.sendRedirect(ServletRedirectResult.java:243)
at org.apache.struts2.dispatcher.ServletRedirectResult.doExecute(ServletRedirectResult.java:226)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at org.apache.struts2.dispatcher.ServletRedirectResult.execute(ServletRedirectResult.java:161)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:367)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:271)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept (AnnotationValidationInterceptor.java:68)


<struts>

<package name="user" namespace="/" extends="struts-default">

<action name="testJPReport" class="testUserSupport" method="exportReportAsPdf">
<result name="success">report.jsp</result>
</action>
</package>
</struts>


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<bean id="testUserSupport"
class="net.lavanya.app.lav.report.web.TestUserAction">
</bean>

public class TestUserAction  extends ExportSupport{

public String exportReportAsPdf() {
Map<String, Object> param = new HashMap<>();
try {
DataBeanMaker dataBeanMaker = new DataBeanMaker();
ArrayList<Test> dataBeanList = dataBeanMaker.getTestDataBeanList();
processReport(ReportTypeEnum.PDF, dataBeanList, "test", param);

} catch (Exception exception) {
exception.printStackTrace();
}
return SUCCESS;
}

}

package net.test.app.report.web;


import com.opensymphony.xwork2.ActionSupport;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class ExportSupport extends ActionSupport implements ServletResponseAware, ServletRequestAware {

private HttpServletResponse httpServletResponse;
private HttpServletRequest httpServletRequest;
private String contentType = "APPLICATION/OCTET-STREAM";


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

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

public void processReport(ReportTypeEnum reportTypeEnum, List<?> beansList, String reportName, Map<String, Object> parameters) throws Exception {
switch (reportTypeEnum) {
case PDF:
processReportAsPDF(beansList, reportName, parameters);
break;
default:
throw new RuntimeException("Un supported report type");
}
}

private void processReportAsPDF(List<?> beansList, String reportName, Map<String, Object> parameters) throws Exception {
System.out.println(">>>>>>>Start processing of pdf report!");

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(beansList);
JasperDesign jasperDesign = JRXmlLoader.load(getJasperFilePath(reportName));
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
setResponseHeaderData(reportName, ReportTypeEnum.PDF);
ServletOutputStream sos = httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, sos);
sos.flush();
sos.close();
httpServletResponse.getOutputStream().flush();
httpServletResponse.getOutputStream().close();

System.out.println(">>>>>>>End processing of pdf report!");
return;

}

private InputStream getJasperFilePath(String reportName) throws FileNotFoundException {
System.out.println(">>>>>>> Path : " + httpServletRequest.getSession().getServletContext().getRealPath("/reports/" + reportName + ".jrxml"));
return new FileInputStream(httpServletRequest.getSession().getServletContext().getRealPath("/reports/" + reportName + ".jrxml"));
}

private void setResponseHeaderData(String reportName, ReportTypeEnum reportTypeEnum) {
httpServletResponse.setContentType(contentType);
StringBuilder headerBuilder = new StringBuilder();
headerBuilder.append("Attachment;Filename=").append("\"").append(reportName).append(".").
append(reportTypeEnum.getReportType()).append("\"");

httpServletResponse.setHeader("Content-Disposition", headerBuilder.toString());
System.out.println(">>>>>>>End of setting response headers for report download");
}
}

最佳答案

我在您的代码中找不到sendRedirect。无论如何,请考虑每个 HTTP 请求只有一个 http 响应,您可能需要在客户端使用一些 JavaScript 解决方案。

导出操作,或者通常是stream结果类型操作应如下所示:

 @Action(value = "sample-export", results = { @Result(name = "success", type = "stream", params = {
"inputName", "inputStream",
"contentType", "${exportContentType}; charset=UTF-8",
"Content-Disposition", "attachment; filename=\"${filename}\"",
"contentDisposition","attachment; filename=\"${filename}\"",
"bufferSize", "2048" }) })
public String export() throws ClientException {

inputStream = exportInputStream();

return SUCCESS;

}
//Setter and getters for inputStream (java.io.InputStream)

正如您所看到的,返回成功不会也不应该将用户重定向到新页面,用户发送请求并获得一个流(例如 PDF)作为结果。

如果你想重定向,你需要通过javascript做更多的事情,或者改变下载步骤,请参见Is it possible in Struts 2 to have a result that downloads a file (stream) *and* redirects?这可能有帮助。通过更改下载步骤,我的意思是您可以将文件保存在服务器上的临时位置,将用户重定向到最终页面并将下载链接放在那里。

关于java - 在 Struts2 中提交响应后无法调用 sendRedirect(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278271/

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