Problem: i want to do a sendRedirect from an actionListener method of a JSF backingBean.
After reading the servlet response i do a sendRedirect but it is not sufficent, because i got this exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
So, i must include this code after the sendRedirect method:
FacesContext context= FacesContext.getCurrentInstance();
context.responseComplete();
Ex.:
try {
HttpJsfUtil.getResponse().sendRedirect(url);
FacesContext context=FacesContext.getCurrentInstance();
context.responseComplete();
} catch (IOException e1) {
e1.printStackTrace();
}
The code above is the same in the case of a response stream: if you want to write in the response stream inside the actionListener method, after you close the response you have to include the above code before exit the method.
Ex.:
try{
HttpJsfUtil.getResponse().setContentType("application/x-download");
HttpJsfUtil.getResponse().setHeader("Content-Disposition", "attachment; filename="+fileName);
HttpJsfUtil.getResponse().setHeader("Cache-Control", "no-cache");
ServletOutputStream out= HttpJsfUtil.getResponse().getOutputStream();
out.write(imageBytes);
out.close();
FacesContext context=FacesContext.getCurrentInstance();
context.responseComplete();
}
catch (IOException ex)
{
System.out.println ("Envelope error: " + ex.getMessage ());
}
where HttpJsfUtil.getResponse() is
public static HttpServletResponse getResponse()
{
return (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
}
From InputStream to byte array
Oh! And finally happen!
This is the code from converting(/writing/copying) an InputStream object into an array of byte:
InputStream is=urlc.getInputStream();
ByteArrayOutputStream outb = new ByteArrayOutputStream();
final int BUF_SIZE = 1 << 8; //1KiB buffer
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while((bytesRead = is.read(buffer)) > -1) {
outb.write(buffer, 0, bytesRead);
}
is.close();
byte[] imageBytes = outb.toByteArray();
And it works!
This is the code from converting(/writing/copying) an InputStream object into an array of byte:
InputStream is=urlc.getInputStream();
ByteArrayOutputStream outb = new ByteArrayOutputStream();
final int BUF_SIZE = 1 << 8; //1KiB buffer
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while((bytesRead = is.read(buffer)) > -1) {
outb.write(buffer, 0, bytesRead);
}
is.close();
byte[] imageBytes = outb.toByteArray();
And it works!
Iscriviti a:
Post (Atom)