简体   繁体   English

java - 根据url请求调用特定的servlet?

[英]java - Calling specific servlet based on url request?

I'm pretty new to JSP, Servlet and Tomcat. 我是JSP,Servlet和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? 如果我将多个域指向服务器的IP地址,我是否可以根据请求的域以编程方式调用相关的Servlet?

Maybe there something I can do in web.xml? 也许我可以在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. HTTP主机头将告诉您客户端请求的域。

The way to obtain this via the Servlet API is: 通过Servlet API获取此方法的方法是:

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. 如果您希望相同的Web应用程序响应多个域,您可能会考虑使用调度程序servlet或调度程序筛选器。 Frameworks like Struts 2 and Spring MVC use these concepts to route requests to the appropriate servlet. 像Struts 2和Spring MVC这样的框架使用这些概念将请求路由到适当的servlet。 With a dispatcher servlet, you can use whatever conditions you want (in your case, hostname) to route to the approriate servlet. 使用调度程序servlet,您可以使用您想要的任何条件(在您的情况下,主机名)来路由到适当的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 . 如果您希望让单独的 Web应用程序响应不同的主机名和/或IP地址(通常称为虚拟主机),那么您可能希望查看Tomcat虚拟主机 This is also commonly handled by putting a web server like Apache or IIS in front of Tomcat. 这通常通过在Tomcat之前放置像Apache或IIS这样的Web服务器来处理。

使用“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
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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