如何使用具有不同url模式的单个Servlet?

时间:2012-01-22 10:09:51

标签: jsp servlets

我需要使用具有不同url模式的单个servlet。我给tomcat服务器尝试如下所示。但我想知道真正的编码标准,请帮帮我吗?

String servletPath = request.getServletPath();

    if("/HelloServletone".equalsIgnoreCase(servletPath))
    {
        System.err.println("1?*");
                ///logic move to controller one

    }

    if("/HelloServlettwo".equalsIgnoreCase(servletPath))
    {
           System.err.println("2*");
           ///logic move to controller two
    }

的web.xml

<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

 <servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServletone</url-pattern>
</servlet-mapping>

 <servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlettwo</url-pattern>
</servlet-mapping>

JSP1:

<form method="post" action="HelloServletone">
  //getting inputs and move to servlet
<input type="submit" value="login " />

jsp2:

<form method="post" action="HelloServlettwo">
  //getting inputs and move to servlet

1 个答案:

答案 0 :(得分:10)

您可以在一个servlet映射中使用多个URL。

<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
<url-pattern>/HelloServletOne</url-pattern>
<url-pattern>/HelloServletTwo</url-pattern>
</servlet-mapping>