简体   繁体   中英

java - Calling specific servlet based on url request?

I'm pretty new to JSP, Servlet and Tomcat. If I point multiple domains to the IP adress of a server, is there a way I can call the relevant Servlet programmically, based on which domain has been requested?

Maybe there something I can do in web.xml?

Sorry for my lack of knowledge - I'm just getting started:(

The HTTP host header will tell you which domain the client requested.

The way to obtain this via the Servlet API is:

javax.servlet.http.HttpServletRequest.getHeader("host");

If you are looking to have the same web application respond to multiple domains, you might look at having a dispatcher servlet or dispatcher filter. Frameworks like Struts 2 and Spring MVC use these concepts to route requests to the appropriate servlet. With a dispatcher servlet, you can use whatever conditions you want (in your case, hostname) to route to the approriate servlet.

If you are instead looking to have separate web applications respond to the different hostnames and/or IP addresses (commonly referred to as virtual hosting), then you might want to look at Tomcat virtual hosting . This is also commonly handled by putting a web server like Apache or IIS in front of Tomcat.

使用“RequestDispatcher”将请求重定向到正确的servlet

use something like:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
 throws IOException {

        // Get client's IP address
        String ipAddress = req.getRemoteAddr(); // ip 

        // Get client's hostname
        String hostname = req.getRemoteHost(); // hostname
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM