Skip to content

Instantly share code, notes, and snippets.

@sjyun
Created May 7, 2014 09:11
Show Gist options
  • Select an option

  • Save sjyun/b329e07ce490ee484d97 to your computer and use it in GitHub Desktop.

Select an option

Save sjyun/b329e07ce490ee484d97 to your computer and use it in GitHub Desktop.
AsyncServlet
import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
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(name="AsyncServlet", urlPatterns="/async", asyncSupported=true)
public class AsyncServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//context를 저장할 List변수를 생성한다.
private List<AsyncContext> contexts = new LinkedList<>();
public AsyncServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//비동기요청에 대한 준비를 시작한다.
final AsyncContext context = request.startAsync( request, response );
context.setTimeout( 10 * 60 * 1000 );
contexts.add(context);
System.out.println(“start async”);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<AsyncContext> asyncContexts = new ArrayList<>( this.contexts );
this.contexts.clear();
String name = request.getParameter("name");
String message = request.getParameter("messaege");
String htmlMessage = "<p><b> " + name + "</b><br/>" + message + "</P>";
ServletContext sc = request.getServletContext();
if( sc.getAttribute("messages") == null){
sc.setAttribute("messages", htmlMessage);
}else{
String currentMessages = (String) sc.getAttribute("messages");
sc.setAttribute("messages", htmlMessage + currentMessages);
}
for( AsyncContext asynContext : asyncContexts){
try (PrintWriter writer = asynContext.getResponse().getWriter()) {
writer.println(htmlMessage);
writer.flush();
asynContext.complete();
}catch(Exception e){
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment