Passing a request to a java class

Hey guys, how`s everyone?

I need to do the following:

I have service that handles a response from an external validation server, and I need to get this response and pass it to my java class. Is that possible? How can I achieve that?

I need my request object from javascript to be converted to a HttpRequest object in java.

Thanks!

You can access the current request from Java code using PortalRequestAccessor:

package foo;
import com.enonic.xp.portal.PortalRequestAccessor;

public class MyClass {

  public void doSomething() {
    HttpServletRequest request = PortalRequestAccessor.get().getRawRequest();
    // do something with request
  }

}

For this to work you have to call your Java class from the controller receiving the request, as you would call Java code in a library.

exports.get = function (req) {

  var bean = __.newBean('foo.MyClass');
  bean.doSomething();

}
6 Likes

That’s pretty amazing, thanks a bunch!

Hey @aro,

and, how can we do with HttpServletResponse?

What exactly are you trying to do?

Can you just return some object (String or ByteSource) from the Java method and make the controller return it in the response as body?

We are trying to use the library java-saml in enonic, https://github.com/onelogin/java-saml. Some methods have HttpServletRequest and HttpServletResponse as parameters. For example, here https://github.com/onelogin/java-saml/blob/b8a7c92bb798e005170abf03565f4c60886941b1/toolkit/src/main/java/com/onelogin/saml2/Auth.java

That will not work within a controller request. The Java code in that class is using the HttpServletResponse to redirect, it cannot work within the context of a XP request.
It’s probably easier to just implement it in Java.

2 Likes