Home > Net >  Get @RenderMapping to return external url
Get @RenderMapping to return external url

Time:09-17

I am using liferay and I have a spring portlet.

The view is rendered fine. I have a link to the same page - if clicked, it should perform some logic and then (conditionaly) open a new tab with a external site:

What I have so far:

@Component
@RequestMapping(value = "VIEW")
...
    @RenderMapping
    public String view(Model model, PortletRequest request, PortletResponse response) throws Exception {
....
response.setProperty(ResourceResponse.HTTP_STATUS_CODE, String.valueOf(HttpServletResponse.SC_MOVED_TEMPORARILY));
final String redirect = "https://......";
response.setProperty("Location", redirect);
            return "redirect:"   redirect;
.....

It does open a new tab, but it does not leave the portal context. It wont open the new location. Any hints?

CodePudding user response:

Given that you have access to try the following:

@RenderMapping
public String view(Model model, PortletRequest request, HttpServletResponse response) throws Exception {
    final String redirect = "https://......";
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", redirect);
    return "";
}

CodePudding user response:

Rendering a portlet always renders part of a page in a portal, thus you won't have access to the original HttpServletResponse without trickery. And even if you get access, the response might already be committed, the portal engine might have decided to deliver your content asynchronously - you're well shielded from the actual result. in short: you can't really think along any HTTP games.

You have a couple of other options though:

  • render JS that does the redirect
  • move your code to the portlet's Action phase, where state updates are expected (render phase is supposed to render, not to change state or make such decisions) - in the action phase you could issue a redirect, but it'll be hard to conditionally do so for opening in a new tab
  • move your code to the portlet's resource phase, trigger it asynchronously and decide in the frontend if you want to open a new tab or not, based on the return you get.
  • move your code to a REST service (continue as in the resource phase bullet point above)
  • Related