Java Batik: ClassNotFoundException: org.apache.batik.dom.svg.SVGDOMImplementation [duplicate] - java

This question already has answers here:
Where has org.apache.batik.dom.svg.SVGDOMImplementation gone?
(4 answers)
Closed 1 year ago.
I have a servlet where i´m trying to create a pdf out of a string containing svg code. Therefore i have this code:
public class Conversion extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String svgString = req.getParameter("svg");
StringReader svg = new StringReader(svgString);
File pdf = new File("/tmp/chart.pdf");
Transcoder transcoder = new PDFTranscoder();
TranscoderInput transcoderInput = new TranscoderInput(svg);
TranscoderOutput transcoderOutput = new TranscoderOutput(new FileOutputStream(pdf));
try {
transcoder.transcode(transcoderInput, transcoderOutput);
} catch (TranscoderException e) {
e.printStackTrace();
}
resp.setContentType("application/pdf");
InputStream in = new FileInputStream(pdf);
ServletOutputStream out = resp.getOutputStream();
byte[] buffer = new byte[4096];
while(in.read(buffer, 0, 4096) != -1){
out.write(buffer, 0, 4096);
}
in.close();
out.flush();
out.close();
}
}
When executing i get this error:
java.lang.ClassNotFoundException: org.apache.batik.dom.svg.SVGDOMImplementation
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1332)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
at org.apache.fop.svg.AbstractFOPTranscoder.<init>(AbstractFOPTranscoder.java:107)
at org.apache.fop.svg.PDFTranscoder.<init>(PDFTranscoder.java:84)
at com.Webmap_read.Conversion.doGet(Conversion.java:38)
at com.Webmap_read.Conversion.doPost(Conversion.java:68)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
When i check my Build Path, it seems like all the JARs that are contained in the Batik 1.8 archive file downloaded from: http://apache.lauf-forum.at/xmlgraphics/batik/binaries/. But the class SVGDOMImplementation is not there. How can i import all the necessary JARs/classes and why aren´t they contained in the standard zip? It´s driving me crazy right now... Or is there maybe an easier way to convert an SVG to PDF?

Take a look at http://www.findjar.com/class/org/apache/batik/dom/svg/SVGDOMImplementation.html an check if any of listed jars are in application classpath.
I suggest you to download Batik from https://xmlgraphics.apache.org/batik/download.html (official website)

Make sure all the necessary/related jar files are present when you compile your class. Simply reference any and all related folders by using javac -cp "[path to first folder with related jars]\*;[path to second folder with related jars]\*;[path to last folder with related jars]\*" yourclass.java .

Related

Simple Asynchronous Servlet example throwing an IllegalStateException. How to fix it?

I'm prototyping an e-commerce web application using Servlets and JSPs, so in order to make regular queries to get the status of a transaction (paid/not paid) from another server without stopping the web application, I'm trying to learn how to use asynchronous Servlets. After some reading and failed attempts of making examples of AsyncServlets found on the web, I've found maybe the simplest one on this video. Even so, it's giving me a headache. It throws an IllegalStateException, even if all the things seem to be in order, since it's a very simple application with no external libraries. I'm using NetBeans IDE 8.2, Java EE 7 Web and Tomcat 8.0.27.
This is the code:
package com.za.tutorial.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = {"/ProgressAsyncServlet"}, asyncSupported=true)
public class ProgressAsyncServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<html><head><title>Progress Async Servlet</title></head><body>");
printWriter.println("entering doGet() ==> thread name: " + Thread.currentThread().getName() + "<br>");
printWriter.println("<progress id='progress' max='100'></progress>");
AsyncContext asyncContext = request.startAsync();
asyncContext.start(() -> {
printWriter.println("thread name within asyncContext.start((): " + Thread.currentThread().getName() + "<br>");
int i = 0;
while (i <= 100) {
printWriter.println("<script>document.getElementById('progress').value=\"" + i++ + "\";</script>");
printWriter.flush();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
printWriter.println("<script>document.getElementById('progress').style.display='none';</script>");
printWriter.println("[time consuming generated and returned result]<br>");
printWriter.println("exiting doGet() ==> thread name: " + Thread.currentThread().getName() + "<br>");
printWriter.println("</body></html>");
asyncContext.complete();
});
}
}
Running the file containing the example of the synchronous ProgressServlet is ok, as expected. Though, after running the ProgressAsyncServlet file, which contains almost the same code (but with asynchronous methods), I get the following log:
04-Mar-2021 08:50:03.188 SEVERE [http-nio-8084-exec-23] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.za.tutorial.servlet.ProgressAsyncServlet] in context with path [/AsyncServletPrj01] threw exception
java.lang.IllegalStateException: A filter or servlet of the current chain does not support asynchronous operations.
at org.apache.catalina.connector.Request.startAsync(Request.java:1612)
at org.apache.catalina.connector.Request.startAsync(Request.java:1605)
at org.apache.catalina.connector.RequestFacade.startAsync(RequestFacade.java:1030)
at javax.servlet.ServletRequestWrapper.startAsync(ServletRequestWrapper.java:373)
at com.za.tutorial.servlet.ProgressAsyncServlet.doGet(ProgressAsyncServlet.java:32)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
It's driving me crazy. How can such a simple code work this wrong?

Tomcat [ERROR] java.io.IOException: Stream closed on uploaded file processing (Apache Commons File Upload)

I am having an issue and I broke my head for the last 4-5 hours debugging and finally reaching out for help here. I have a simple file upload servlet that uses Apache Commons ServletFileUpload and on detecting the file, it processes the content and generates output file. The code runs fine and generates output file that I can save but on Tomcat logs, I see Stream Closed error for every request. When I run the same on Jetty in GAE, there is no Stream Closed error. Finally, I just downloaded 100 MB JBoss AS server and there are no errors for the same codebase in JBoss too. However, our client uses Tomcat and we need to resolve this for tomcat. Tested in Tomcat 7.0.59, 7.0.62 and in 7.0.82 with same error. Code and Exception are as below. Any and all help is highly appreciated.
public void doPost(HttpServletRequest req, HttpServletResponse response)
throws IOException
{
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter;
String outFile = null;
try
{
iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField())
{
//Log the form field names
}
else
{
// File processing here.
System.out.println("Uploaded file field: " + name + " with file name: "
+ item.getName());
try{
fileName = item.getName();
response.setHeader("Content-Disposition","attachment;filename=" + outFile);
ServletOutputStream out = response.getOutputStream();
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(stream));
processRequest(zis, out);
req.setAttribute("fileName", outFile);
}
catch(Exception e)
{
log.error(e,e);
}
}
}
}
catch (FileUploadException e)
{
log.error(e,e);
}
catch(Exception e1)
{
log.error(e1,e1);
}
}
}
The exception line 46 refers to the statement
while (iter.hasNext()) {
Exception Stack trace is as below.
[ERROR] java.io.IOException: Stream closed
java.io.IOException: Stream closed
at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:312)
at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:200)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:977)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.close(MultipartStream.java:924)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.close(MultipartStream.java:904)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl.close(FileUploadBase.java:815)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:955)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.hasNext(FileUploadBase.java:1040)
at com.ks.act.web.BWScannerServlet.doPost(BWScannerServlet.java:46)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

"IllegalStateException: Response already committed" in Struts2 Interceptor chain on WebLogic 10.3.x on Linux [duplicate]

I have some code for download file from web server.
Everything works alright, but in console I have this exception:
июн 26, 2015 2:08:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/TestTask] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:462)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:109)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:57)
at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:909)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:576)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Why and what it can be? And how i can fix this problem? I try find answer in the google, but I failed.
The code:
package actions;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import org.apache.log4j.Logger;
import org.apache.struts.chain.contexts.ServletActionContext;
import service.CsvCreator;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadCsvAction extends ActionSupport {
private static final long serialVersionUID = -4714537109287679996L;
private CsvCreator CSVcreator;
private static final Logger logger = Logger.getLogger(DownloadCsvAction.class);
public CsvCreator getCSVcreator() {
return CSVcreator;
}
public void setCSVcreator(CsvCreator cSVcreator) {
CSVcreator = cSVcreator;
}
#Override
public String execute() {
HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse();
response.setHeader("Content-Disposition", "attachment; filename=\"phone_records.csv\"");
response.setContentType("text/csv");
ServletOutputStream out;
try {
out = response.getOutputStream();
String tableHeader = "Caller, Event, Reciever, Timestamp\n";
out.write(tableHeader.getBytes("UTF-8"));
out.write(CSVcreator.getAllRecordsInString().getBytes("UTF-8"));
out.flush();
out.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return SUCCESS;
}
}
And my struts.xml:
<action name="DownloadCsvAction" class="DownloadCsvAction">
<result name="success" type="dispatcher"/>
</action>
Why and what it can be?
Because response is already committed. You have closed response before it's used by the Struts2.
And how I can fix this problem?
When your action execution ends, return Action.NONE result code. This code tells the invoker to not execute any result because response might be already committed.
You can also rewrite the action implementation to use stream result type. In this way you have not to do with the response and let Struts2 do the rest. Example of using stream result is here.

"getOutputStream()" has already been called for this response

i'm working on a project with Spring, i have this problem, i google the error message and i did find a solutions even all SO posts about this same problem
java.lang.IllegalStateException: "getOutputStream()" has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:578)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:212)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:115)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:108)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:175)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:120)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
at org.apache.jsp.WEB_002dINF.Pages.generate_jsp._jspService(generate_jsp.java:209)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:584)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:523)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:230)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
this is my controller :
#RequestMapping(method = RequestMethod.GET, value = "/GenerateM")
public String genererGet(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {
// Some code ...
OutputStream out;
try {
response.setContentType("rtf");
String filename = name + ".out.rtf";
response.setHeader("Content-Disposition", "attachment; filename = " + filename);
out = response.getOutputStream();
FileInputStream in = new FileInputStream(new File(rtf.getRtfOutput()));
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
out.close();
} catch (IOException a) {
a.printStackTrace();
}
return "generate";
}
i saw many SO posts like : THIS and THIS and THIS but no solution for me
can some one help ?
You start by writing a response by yourself, and then return the name of the view, and thus telling Spring that it should generate an HTML page using the generate.jsp.
Make your method return void instead of a String. An HTTP response can have only one body: either it's a file attachment, or an HTML page, but not both.
#JB Nizet Thank's for help. In my case, I retured ModelAndView ojbect when download failing to forward error page:
#RequestMapping(value = { "/downloadfile.action" }, method = RequestMethod.POST)
public ModelAndView downloadFile(HttpServletRequest req, HttpServletResponse res, Model model)
{
catch (Excetion e) {
return errorPage
}
}
I change that to return null

Getting an IllegalStateException when i call forward() [duplicate]

This question already has an answer here:
java.lang.IllegalStateException: Cannot forward after response has been committed in servlet [duplicate]
(1 answer)
Closed 7 years ago.
I am trying to learn abt servlets.
I am getting a IllegalStateException when i call forward(). The error occurs in the LoginBean.do if block at the point where i call forward.
process(request,response);
}
private void process(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String uri = request.getRequestURI();
RequestDispatcher rd = null;
CAppModel model = new CAppModel();
System.out.println("Inside process ()");
try{
if(uri.contains("/Login"))
{
System.out.println("Inside Login.do");
rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request,response);
}
if(uri.contains("/Register.do"))
{
System.out.println("inside Register.do");
}
if(uri.contains("/LoginBean.do"))
{
System.out.println("Inside LoginBean.do");
LoginBean lb = (LoginBean)request.getAttribute("login");
System.out.println("toString(): "+lb.toString());
String result = model.authenticate(lb);
System.out.println("CS: result of auth "+result);
if(result.equals("Success"))
{
System.out.println("Inside if Success of loginbean");
HttpSession session = request.getSession(true);
session.setAttribute("user", lb.getEmail());
rd = request.getRequestDispatcher("Menu.jsp");
rd.forward(request, response);
}
else
{
System.out.println("failed auth "+result);
request.setAttribute("errorMsg", result);
rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request,response);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
process(request,response);
}
}
I am getting the following error
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:328)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at com.aditya.CApp.ControllerServlet.process(ControllerServlet.java:69)
at com.aditya.CApp.ControllerServlet.doGet(ControllerServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:741)
at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:711)
at org.apache.jsp.LoginInt_jsp._jspService(LoginInt_jsp.java:104)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
A request containing /LoginBean.do will trigger 2 if blocks causing 2 forwards to be invoked causing the error after the 2nd forward. While you could re-arrange the the if statements as
if (uri.contains("/LoginBean.do")) {
...
else if (uri.contains("/LoginBean")) {
...
Generally its simpler to use an individual servlet per if block functionality.
you must return; after a forward. otherwise the following code would executed also... in your case the conditions containing /Login and /LoginBean.do

Categories

Resources