Jetty Redirect Based on Locale

2019-06-10 15:15发布

问题:

I want to -based on the locale of the requesting client- redirect a URL, server side in Jetty.

i.e.

  1. client makes a request for host:port/help/index.html ('help' being a webapp war)
  2. server side I read the clients locale, e.g. 'GB' and redirect to a seperate webapp, e.g. *host:port/help_GB/index.html*

I thought this would be as simple as the server side code that runs my Jetty server:-

    String i18nID = Locale.getDefault().getCountry();

    RewriteHandler rewrite = new RewriteHandler();
    rewrite.setRewriteRequestURI(true);
    rewrite.setRewritePathInfo(false);
    rewrite.setOriginalPathAttribute("requestedPath");

    RedirectRegexRule r = new RedirectRegexRule();
    r.setRegex("/help/(.*)");
    r.setReplacement("/help_" + i18nID + "/$1");
    rewrite.addRule(r);

    server.setHandler(rewrite);

But this doesn't work, I get 404s for all 'host:port/*' addresses. I then noticed that I was getting the locale server side anyhow and I want it client side so I wrote my own handler:-

  private class MyHandler extends RewriteHandler
  {
    @Override 
    public void handle(String target, 
                       Request baseRequest, 
                       HttpServletRequest request, 
                       HttpServletResponse response)
    {
      try
      {
        String country = baseRequest.getLocale().getCountry();
        String newTarget = target.replace("/help/", "/help_" + country + "/");

        if (target.contains("/help/") /*TODO And not GB locale */)
        {
          response.sendRedirect(newTarget);
        }
        else
        {
          super.handle(target, baseRequest, request, response);
        }

      }
      catch(Exception e)
      {
        /*DEBUG*/System.out.println(e.getClass() + ": " + e.getMessage());
        e.printStackTrace();
      }
    }
  }

...and used that instead of RewriteHandler. This accepts '/help/' requests, doesn't redirect, doesn't include some page elements and 404s every other URI not containing help.

Am I doing something wrong or using the rewrite/redirect handlers some way they're not supposed to be used?!

回答1:

Redirecting to another webapp should maybe be done with a Filter like so