Extracting The Subdomain In Java

A short code example today: how to extract the subdomain in Java. The req object represents HttpServletRequest.

String subdomain = req.getRequestURL().toString();
subdomain = subdomain.substring(subdomain.indexOf("/") + 2, subdomain.indexOf("."));

For example, if the user entered http://subdomain.example.com , this code would store the word subdomain in the subdomain variable.