6

I first want to know if there is a built-in way of getting a subdomain from a url using pure servlets?

And then if spring has any helpers?

So my urls would be like:

jonskeet.stackoverflow.com

Where JonSkeet is the subdomain.

I will create a filter that will load a object based on the subdomain value.

BTW, when creating a filter, is there a way to order the filters to make sure they all fire in a specific order?

Kiril
  • 39,672
  • 31
  • 167
  • 226
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • Misspelled Jon Skeet's name there buddy, tisk tisk! – Kiril Mar 21 '12 at 20:32
  • 1
    +1 if you wondered if SO has really created a Jon Skeet sub-domain and tried to visit http://jonskeet.stackoverflow.com – Kiril Mar 21 '12 at 20:33
  • No, I don't think you can go further than obtaining the URL and then splitting the String yourself. BTW, you should not put more than one question, particularly when your question about filters can be answered quickly with a Google search. – madth3 Mar 21 '12 at 20:34
  • wow that is surprising, I was certain there would be something. – Blankman Mar 21 '12 at 20:36

2 Answers2

8

I doubt there is a special API for this. But you can get it from HttpRequest using request.getServerName().split("\\.")[0]. It seems it is easy enough.

Limitation is that you cannot support "subdomain" that contains dot characters, e.g. jon.skeet.stackoverflow.com.

AlexR
  • 114,158
  • 16
  • 130
  • 208
1

Use Guava.

Gradle:

dependencies {
 compile group: 'com.google.guava', name: 'guava', version: '19.0'
 ...
}

Java:

    private String getSubdomain(HttpServletRequest req) {

        String site = req.getServerName();

        String domain = InternetDomainName.from(site).topPrivateDomain().toString();
        String subDomain = site.replaceAll(domain, "");
        subDomain = subDomain.substring(0, subDomain.length() - 1);

        return subDomain;
}

So, "jon.skeet.stackoverflow.com" will return "jon.skeet".

Renascienza
  • 1,647
  • 1
  • 13
  • 16