If yes to the question above, how can I do it?
--------------
redirect = I want to redirect the user from page X to page Y based on certain conditions.
I know I can use a filter for this one but just wondering if it can be done from a Sling model. Thank you!
Solved! Go to Solution.
Views
Replies
Total Likes
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() {
// your condition logic here
return true;
}
}
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() {
// your condition logic here
return true;
}
}
Views
Likes
Replies