Forwarding

An example of a simple forward to another page or site.

Back to overview

Server-side Forwarding

This illustrates a forwarding decision from the serverside. Any action can return an Attribute that causes the user to forward.

By default, you can only refer to locations within your own URL. For example, if the page is available on 'https://mysite.com/hello', then a call to 'https://mysite.com/something-else' is allowed.

Relative URLS ('/hello', '../hello') are also allowed but must either start with a '.' or a '/'

If you want to refer to a location on another URL, you must explicitly set the property 'medusa.allow-external-redirect' to true.

Client

<button m:click="forwardTo('basic-button')">Forward to 'basic button sample'</button>
<button m:click="forwardTo('live-data')">Forward to 'live data sample'</button>

Server

import io.getmedusa.medusa.core.annotation.UIEventPage;
import io.getmedusa.medusa.core.attributes.Attribute;
import io.getmedusa.medusa.core.attributes.StandardAttributeKeys;

import java.util.List;

@UIEventPage(path = "/detail/forwarding", file = "/pages/forwarding.html")
public class ForwardingController {

    public List<Attribute> forwardTo(String pathToForwardTo) {
        return List.of(
            new Attribute(StandardAttributeKeys.REDIRECT, "/detail/" + pathToForwardTo)
        );
    }

}

Server-initiated Forwarding

This same forwarding concept can also be triggered outside the scope of an action, via ServerToClient.

Client

<button m:click="registerMeForAForward()">Register me for a forward</button>

Server

import io.getmedusa.medusa.core.annotation.UIEventPage;
import io.getmedusa.medusa.core.attributes.Attribute;
import io.getmedusa.medusa.core.attributes.StandardAttributeKeys;
import io.getmedusa.medusa.core.bidirectional.ServerToClient;
import io.getmedusa.medusa.core.session.Session;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.List;

@UIEventPage(path = "/detail/forwarding", file = "/pages/forwarding.html")
public class ForwardingController {

    private final ServerToClient serverToClient;

    public ForwardingController(ServerToClient serverToClient) {
        this.serverToClient = serverToClient;
    }

    public void registerMeForAForward(Session session) {
        sessionIds.add(session.getId());
    }

    private final List<String> sessionIds = new ArrayList<>();

    @Scheduled(fixedDelay = 500)
    public void triggerForwardFromSchedule() {
        for(String sessionId : sessionIds) {
            serverToClient.sendAttributesToSessionIDs(List.of(
                new Attribute(StandardAttributeKeys.FORWARD, "/detail/basic-button")
            ), List.of(sessionId));
        }
        sessionIds.clear();
    }

}