Blankman
Blankman

Reputation: 267160

How can I retrieve the sub domain in a servlet? Does spring have any helpers

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?

Upvotes: 7

Views: 8939

Answers (2)

Renascienza
Renascienza

Reputation: 1647

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".

Upvotes: 1

AlexR
AlexR

Reputation: 115378

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.

Upvotes: 8

Related Questions