Get output stream from HttpServletResponse : Response « Servlets « Java






Get output stream from HttpServletResponse

  
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CounterServer extends HttpServlet {
  static final String COUNTER_KEY = "Counter.txt";

  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    HttpSession session = req.getSession(true);
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
      count = i.intValue() + 5;
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    DataInputStream in = new DataInputStream(req.getInputStream());
    resp.setContentType("application/octet-stream");
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.writeInt(count);
    out.flush();
    byte[] buf = byteOut.toByteArray();
    resp.setContentLength(buf.length);
    ServletOutputStream servletOut = resp.getOutputStream();
    servletOut.write(buf);
    servletOut.close();
  }
}

   
  








Related examples in the same category

1.Set content type to charset=ISO-8850-1
2.URL rewriting through HttpServletResponse
3.Add headers to prevent browsers and proxies from caching this reply.