Created
May 7, 2014 09:11
-
-
Save sjyun/b329e07ce490ee484d97 to your computer and use it in GitHub Desktop.
AsyncServlet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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