Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
Blankman Avatar asked Mar 21 '12 20:03

Blankman


People also ask

How do you find the sub domain?

While a subdomain will appear before your TLD, a subdirectory link will include the subdirectory name after the original TLD. For example: Subdomain example: mysubdomain.mywebsite.com. Subdirectory example: mywebsite.com/mysubdirectory.

Which part of this URL is the sub domain?

To recap, a subdomain is the portion of a URL that comes before the “main” domain name and the domain extension. For example, docs.themeisle.com .

Does Spring use Servlets?

Yes it is. Spring-MVC uses DispatcherServlet under the hood. Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers or HTTP-based remote service exporters.

Can we use sub domain?

By implementing subdomains on your website, you can create separate sections of content and services for your website without having to create new domain names for each part. Subdomains will also make it easier for users to find what they need, all in one place.


2 Answers

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.

like image 160
AlexR Avatar answered Oct 08 '22 10:10

AlexR


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

like image 38
Renascienza Avatar answered Oct 08 '22 10:10

Renascienza