Oi GUJ,
tudo bem ?
Pessoal estou recendo o erro : “Cannot forward after response has been committed” eu estou chamando essa servlet através de uma .jsp que eu tenho :
<form class="formEvento" id="formUpload" action="Uploader" method="post" ENCTYPE="multipart/form-data" onsubmit="return carregarFoto()">
package Servlet;
import javax.servlet.annotation.WebServlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
* @author Valter
*/
@WebServlet(name = "Uploader", urlPatterns = {"/Uploader"})
public class Uploader extends HttpServlet {
// atributos necessários para o FileUploader
private static final String TMP_DIR_PATH = "C:\\Users\\Valter\\Documents\\NetBeansProjects\\TAGIT_v2\\trunk\\TagIT\\build\\web";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/files";
private File destinationDir;
private String realPath;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String arquivo = "";
String titulo = "NOME DO EVENTO";
String descricao = "DESCRICAO DO EVENTO";
String url = "";
//PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
//Set the size threshold, above which content will be stored on disk.
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
//Set the temporary directory to store the uploaded files of size above threshold.
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
RequestDispatcher rd = null;
try {
// Parse the request
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
// Handle Form Fields.
if (item.isFormField()) {
System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
if (item.getFieldName().equals("titulo")) {
titulo = item.getString();
} else {
if (item.getFieldName().equals("descricao")) {
descricao = item.getString();
}
}
} else {
//Handle Uploaded files.
arquivo = item.getName();
System.out.println("Arquivo = " + item.getName()
+ ", Tipo de arquivo = " + item.getContentType()
+ ", Tamanho = " + item.getSize());
if(!item.getName().equals("")){
if (item.getContentType().contains("jpeg") || item.getContentType().contains("jpg") || item.getContentType().contains("png") || item.getContentType().contains("bmp")) {
// Write file to the ultimate location.
File file = new File(destinationDir, item.getName());
item.write(file);
request.getSession().setAttribute("type", "cxdialogo_sucesso");
request.getSession().setAttribute("message", "<p>- Upload realizado com <strong>sucesso !</strong> </p><p>- Clique na caixa para fechar.</p>");
url = "/Flickr?acao=upload&caminho=" + realPath + "&arquivo=" + arquivo + "&titulo=" + titulo + "&descricao=" + descricao;
} else {
url = "AjaxCadastrarEvento.jsp";
request.getSession().setAttribute("type", "cxdialogo_erro");
request.getSession().setAttribute("message", "<p>- <strong>Apenas</strong> imagens serão aceitas (.jpeg, .jpg, .png ou .bmp) .</p><p>- Clique na caixa para fechar.</p>");
}
}else{
url = "AjaxCadastrarEvento.jsp";
request.getSession().setAttribute("type", "cxdialogo_erro");
request.getSession().setAttribute("message", "<p>- <strong>Forneça </strong> uma imagem para cadastrar o seu evento</p><p>- Clique na caixa para fechar.</p>");
}
}
System.out.println("ANTES DO FOWARD");
rd = request.getRequestDispatcher(url);
rd.forward(request, response);
}
} catch (FileUploadException ex) {
log("Error encountered while parsing the request", ex);
} catch (Exception ex) {
log("Error encountered while uploading file", ex);
} finally {
//out.close();
}
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Pelo o que entendi (lendo em outros fóruns) eh que quando se utiliza o Writer e dá uma writer.close estaria fechando o envio e recebimento para outras servlets.
Mas aqui eu nem uso ele.
O que seria então pessoal ?
Obrigado desde já.