3 Replies Latest reply on Sep 30, 2016 10:57 AM by natedrake2

    Trouble accessing HttpSession and setting cookies in custom HttpHandler

    natedrake2

      Hi,

       

      As part of migrating and application from JBoss 7.1.1 to Wildfly 10.1, I'm converting a Valve to a HttpHandler.  The handler needs to check if an HttpSession attribute is null, and if so it needs to delete a cookie.

       

      I've got a custom HttpHandler deploying in Wildfly and getting executed, but I'm having trouble getting the ServletRequestContext object.  It's always coming back null.  Do I need to do something else to my undertow configuration?  Is there a better was to access the HttpSession and modified cookies on the HttpResponse?

       

      Thanks!

       

      Nate

       

      Here is the custom handler:

       

      package com.example.handlers;
      
      import io.undertow.server.ExchangeCompletionListener;
      import io.undertow.server.HttpHandler;
      import io.undertow.server.HttpServerExchange;
      import io.undertow.server.session.Session;
      import io.undertow.servlet.handlers.ServletRequestContext;
      import io.undertow.servlet.spec.HttpServletRequestImpl;
      import io.undertow.servlet.spec.HttpServletResponseImpl;
      import io.undertow.util.Sessions;
      import javax.servlet.http.Cookie;
      import javax.servlet.http.HttpSession;
      import org.apache.log4j.Logger;
      
      public class TestHandler implements HttpHandler {
          private static final Logger logger = Logger.getLogger(TestHandler.class);
      
          private HttpHandler next;
      
          public TestHandler(HttpHandler next) {
              this.next = next;
          }
      
          @Override
          public void handleRequest(HttpServerExchange exchange) throws Exception {
              logger.info("Handling request...");
      
              ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
              // src is always null
              
              if(src != null) {
      
                  HttpServletRequestImpl request = src.getOriginalRequest();
                  HttpServletResponseImpl response = src.getOriginalResponse();
                  final HttpSession session = request.getSession(false);
      
                  if(session != null) {
                      logger.info("Session is not null!");
                      final Object attr = session.getAttribute("attr");
                      if (attr == null) {
                          logger.info("attr is not null " + attr);
                          for (Cookie c : request.getCookies()) {
                              if (c.getName().equals("the-cookie")) {
                                  logger.info("Found cookie...deleting...");
                                  c.setMaxAge(0);
                                  c.setValue("");
                                  c.setPath("/");
                                  response.addCookie(c);
                                  break;
                              }
                          }
                      
                      } else {
                          logger.info("attr is null");
                      }
                  } else {
                      logger.info("session is null");
                  }
              } else {
                  logger.info("src is null");
              }
              next.handleRequest(exchange);
          }
      }
      

       

       

      Here is the module xml file:

       

      <module name="com.example.handlers" xmlns="urn:jboss:module:1.3">
          <dependencies>
              <module name="javax.api"/>
              <module name="io.undertow.core"/>
              <module name="io.undertow.servlet"/>
              <module name="org.apache.log4j"/>
          </dependencies>
      
      
          <resources>
              <resource-root path="."/>
          </resources>
      </module>
      

       

       

       

       

      Here is the undertow subsystem configuration standalone.xml:

       

      <subsystem xmlns="urn:jboss:domain:undertow:3.1">
          <buffer-cache name="default"/>
          <server name="default-server">
              <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true" record-request-start-time="true"/>
              <https-listener name="https" socket-binding="https" security-realm="ManagementRealm" enable-http2="true" record-request-start-time="true"/>
              <host name="default-host" alias="localhost">
                  <access-log prefix="access." rotate="true" pattern="%h %l %u %t &quot;%r&quot; %s %b %D &quot;%{i,Referer}&quot; &quot;%{i,User-Agent}&quot; &quot;%I&quot;"/>
                  <filter-ref name="test"/>
              </host>
          </server>
          <servlet-container name="default">
              <jsp-config/>
              <websockets/>
          </servlet-container>
          <filters>
              <filter name="test" class-name="com.example.handlers.TestHandler" module="com.example.handlers"/>        
          </filters>
      </subsystem>
      
        • 1. Re: Trouble accessing HttpSession and setting cookies in custom HttpHandler
          swd847

          Handlers in standalone.xml get executed before the request has been dispatched to the Servlet implementation, so there is no ServletRequestContext object.

           

          You need to deploy it via undertow-handlers.conf or a ServletExtension instead.

          1 of 1 people found this helpful
          • 2. Re: Trouble accessing HttpSession and setting cookies in custom HttpHandler
            natedrake2

            Thanks, do you have any links on how I would configure it via undertow-handlers.conf?  I created an undertow-handlers.conf in my WARs web-inf directory, but on server startup it said a handler with the specified name didn't exist.  Next I tried adding an http-handler element to jboss-web.xml, but when I start up the server I get the following exception:

             

            10:16:42,332 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC000001: Failed to start service jboss.deployment.subunit."test.ear"."test.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."test.ear"."test.war".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of subdeployment "test.war" of deployment "test.ear"

              at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:154) [wildfly-server-2.2.0.Final.jar:2.2.0.Final]

              at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.6.Final.jar:1.2.6.Final]

              at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.6.Final.jar:1.2.6.Final]

              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_77]

              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_77]

              at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_77]

            Caused by: java.lang.RuntimeException: WFLYUT0066: Failed to configure handler null

              at org.wildfly.extension.undertow.deployment.UndertowHandlersDeploymentProcessor.handleJbossWebXml(UndertowHandlersDeploymentProcessor.java:103)

              at org.wildfly.extension.undertow.deployment.UndertowHandlersDeploymentProcessor.deploy(UndertowHandlersDeploymentProcessor.java:70)

              at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:147) [wildfly-server-2.2.0.Final.jar:2.2.0.Final]

              ... 5 more

            Caused by: java.lang.IllegalArgumentException: name is null

              at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:341) [jboss-modules.jar:1.5.2.Final]

              at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93) [jboss-modules.jar:1.5.2.Final]

              at org.wildfly.extension.undertow.deployment.UndertowHandlersDeploymentProcessor.handleJbossWebXml(UndertowHandlersDeploymentProcessor.java:94)

              ... 7 more

             

            I tried adding a public String name() method to the Handler as well as adding a public static Builder with a name() method (similar to how some of the built-in Undertow HttpHandlers seemt to it), but neither seems to work.

            • 3. Re: Trouble accessing HttpSession and setting cookies in custom HttpHandler
              natedrake2

              Nevermind, I had the syntax wrong in jboss-web.xml.

               

              This is what I needed:

               

                <http-handler>
                    <class-name>com.example.handlers.TestHandler</class-name>
                    <module>com.example.handlers</module>
                </http-handler>
              

               

               

              Thanks for your help!

               

              Actually, this works and my handler runs for every request.  If I wanted to use undertow-handlers.conf to use predicates to restrict which requests the handler runs for how could I do that?  I'm still not sure how to get my custom handler to register with the server with a name that I can reference in undertow-handlers.conf.