Hi @jayv25585659,
Yes, technically it is possible to do a redirect from a Sling Model, but it’s not recommended and generally considered bad practice.
Here is ehy:
-
Sling Models are meant to represent content, provide data for the view, or encapsulate business logic for rendering.
-
Redirecting is an HTTP response action, which is a controller-level concern. Doing it from a model mixes responsibilities and can lead to hard-to-maintain code.
If you still want to do it:
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
@Model(adaptables = javax.servlet.http.HttpServletRequest.class,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class RedirectModel {
@Inject
private SlingHttpServletResponse response;
@PostConstruct
protected void init() {
try {
boolean someCondition = checkSomeLogic();
if (someCondition) {
response.sendRedirect("/content/site/en/pageY.html");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean checkSomeLogic() {
return true;
}
}
Santosh Sai

