如何在Wiremock Servlet中启用Response Templating?
Perfect question! When you're running WireMock as a servlet in a WAR (like the sample-war project you mentioned), enabling Response Templating isn't as straightforward as the JUnit rule or standalone server options—but it's definitely doable by tweaking your servlet configuration. Let's walk through the steps:
1. Update Your web.xml Configuration
The key is adding an initialization parameter to the WireMock servlet definition to turn on templating. Here's how to modify your web.xml:
<servlet> <servlet-name>WireMockServlet</servlet-name> <servlet-class>com.github.tomakehurst.wiremock.servlet.WireMockServlet</servlet-class> <!-- Add this init-param to enable response templating --> <init-param> <param-name>response-templating.enabled</param-name> <param-value>true</param-value> </init-param> <!-- Keep any existing init-params (like port, stub mappings directory) --> </servlet>
If you're using Servlet 3.0+ and annotation-based configuration instead of web.xml, you can add the init parameter directly to your @WebServlet annotation:
@WebServlet( name = "WireMockServlet", urlPatterns = "/*", initParams = { @WebInitParam(name = "response-templating.enabled", value = "true") } ) public class CustomWireMockServlet extends WireMockServlet { // Empty implementation unless you need custom extensions }
2. Verify Templating Works
Once you redeploy your WAR to Tomcat, create a test stub to confirm templating is active. For example, add this stub mapping (usually in your mappings directory):
{ "request": { "method": "GET", "url": "/greet" }, "response": { "status": 200, "body": "Hi there, {{request.queryParams.username}}! Today is {{now format='yyyy-MM-dd'}}" } }
Now send a request like GET /greet?username=Jacob—you should get a response with the username and current date filled in, which means the templating is working as expected.
3. Optional: Add Custom Template Helpers
If you need custom Handlebars helpers, you can extend the WireMockServlet to register them. Create a custom servlet class:
public class CustomWireMockServlet extends WireMockServlet { @Override protected WireMockConfiguration buildWireMockConfiguration() { return super.buildWireMockConfiguration() .extensions(new MyCustomTemplateHelper()); } }
Then update your web.xml to use this custom servlet class instead of the default WireMockServlet.
内容的提问来源于stack exchange,提问作者jacobcs

