javahttpplayframework-1.x

PlayFramework 1.4 prevent propagation after condition not fulfilled


I have a following problem: I want o use @Before to intercept requests and check if a certain condition is fulfilled; if not, prevent propagation and return a message to user.

Is there any other way than throwing an exception?

Code example:

in routes:

   GET /someRoute  MainController/someMethod
   GET /otherRoute MainController/otherMethod

in Controller

public class MainController{
@Before
public static void check(){
// checking, if not fulfilled - render error and requested method is not invoked.
}
public static void someMethod() {/*some action*/}
public static void otherMethod() {/*...other action*/}

Solution

  • Since the method annotated with @Before is on a Controller, you can use all the static function to directly answer. For example if you want to return a plain text :

    public class MainController{
    @Before
    public static void check(){
      // checking, if not fulfilled - render error and requested method is not invoked.
      renderText("Error");
    }
    public static void someMethod() {/*some action*/}
    public static void otherMethod() {/*...other action*/}
    

    That will stop the propagation and send a response to the request.

    You can also use error() or forbidden() for example.