Reputation: 195
I have previously achieved this by using web.xml
like so:
<servlet>
<servlet-name>Test1</servlet-name>
<servlet-class>com.abc.test.Servlet</servlet-class>
<init-param>
<param-name>propertyKey</param-name>
<param-value>test1</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>Test2</servlet-name>
<servlet-class>com.abc.test.Servlet</servlet-class>
<init-param>
<param-name>propertyKey</param-name>
<param-value>test2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Test1</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Test2</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
This means that if I go to http://server/project/Test1
, the Servlet
class will get the value test1
for propertyKey
and if I go to http://server/project/Test2
, it will get the value test2
.
I'm now starting to develop an application for Tomcat 7, so I tried to replicate this using annotations:
@WebServlet(name = "Test1", urlPatterns = "/test1", initParams = @WebInitParam(name = "propertyKey", value = "test1"))
@WebServlet(name = "Test2", urlPatterns = "/test2", initParams = @WebInitParam(name = "propertyKey", value = "test2"))
public class Servlet extends HttpServlet {
// ...
This resulted in the error "Duplicate annotation @WebServlet
".
I also tried putting in arrays of parameters and URL patterns, but they still all apply to the same servlet.
Is it possible to do this, or should I just stick with web.xml
? Or maybe I'll suck it up and go with ?propertyKey=test1
and ?propertyKey=test2
but I think it's nicer to hide that stuff.
Upvotes: 1
Views: 1400
Reputation: 279890
If you don't want to go with XML, you can also register two (or more) instances of your Servlet
with a ServletContainerInitializer
and specify different init parameters.
Other than JB Nizet's suggestion, I don't think you'll find a solution with annotations.
Upvotes: 0