How to redirect or forward request in Hybris?

What is basic difference between request Redirect Vs Forward?

Redirect: Server sends a header (in response) back to the browser/client, which contain redirect URL, then browser initiates a new request to redirect URL.
  • Browser creates a new request to the redirected URL.
  • The browser displays the redirected URL.
  • The client browser is involved.
  • Redirect is slower.
When can we use Redirect?
@RequestMapping(value = "/originalurl", method = {RequestMethod.POST})
public String method(final Model model)
{
    // ...
    return "redirect:/redirectToGeturl";
}
Usually, when data is posted to the server, we should redirect to get method(URL). So browser displays redirected URL(/redirectToGeturl). Which also prevent data resubmission on browser refreshed(F5) as the request to will go to redirected URL(/redirectToGeturl).

Forward: Within the server, control can be forwarded to target resource(URL). Which is done by container internally so browser/client is not aware of it.
  • The browser is not aware of forwarded URL, it displays the original URL.
  • The request is transferred do the forwarded URL internally.
  • The client browser is not involved.
  • Redirect is faster.
When can we use forward?
@ExceptionHandler(UnknownIdentifierException.class)
public String handleUnknownIdentifierException(final UnknownIdentifierException exception, final HttpServletRequest request)
{
    request.setAttribute("message", exception.getMessage());
    return "forward:/404";
}
Sometimes, we want to show different page/resource in response without changing original URL, then we can forward request to other controller mapping which serve the response and browser will not aware of it. In above case, where ever there is UnknownIdentifierException, the browser gets 404 page in the response of originally requested URL.

How to redirect to a different page in Hybris?

public static final String REDIRECT_PREFIX = "redirect:";
public static final String FORWARD_PREFIX = "forward:";
This class level constants are defined in AbstractController. You can use that by extending your controller to AbstractPageController or AbstractController. You can also refer many OOTB implementations which use these constants.
return REDIRECT_PREFIX + "/redirecturl";
return FORWARD_PREFIX + "/404";
Author Image

Ankitkumar Patel

Sr. SAP Hybris consultant, having 15+ years experience in SAP Commerce Cloud (Hybris), SAP Spartacus. Extensive experience in SAP Hybris development, third-party integrations, project architecture and design... Read more

Comments

Popular posts from this blog

Hybris flexible search query examples

How to Install temporary Hybris license?

How to remove or update all data records in Hybris?