Martini Services Groovy Class HTTP Endpoint
Martini allows you to expose services through Groovy-based Spring controllers, providing an alternative to traditional REST and SOAP API development. The platform's integration with Spring makes creating beans and adding controllers seamless and efficient.
This section will guide you through using Spring to create RESTful web services in Martini.
Simple Controller Example
Let's look at a basic example of a Groovy class, PersonController, which defines a REST endpoint:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
This controller handles GET requests at /person/new and returns a Person object. The Person class is defined as:
1 2 3 4 5 6 7 8 9 10 11 | |
The JSON response would typically be:
1 2 3 4 5 | |
To deploy this endpoint:
1. Create Person and PersonController Groovy classes in a Martini package's code directory.
2. Once compiled, the endpoint will be accessible at /person/new. Test it using this command:
1 2 3 | |
Annotation Breakdown
@RestController: This annotation combines@Controllerfor controller definitions and@ResponseBodyto bind method return values to the response body.@RequestMapping: Maps HTTP requests to controller methods based on URL patterns and request types.@RequestParam: Binds query parameters to method parameters.
Note on @PathVariable
For binding URI template variables to method parameters, @PathVariable is used, as shown below:
1 2 3 4 | |
Request Content-Type Detection and Parameter Mapping
Martini determines the Content-Type of a request by considering @RequestMapping annotations, query parameters, and HTTP headers. Parameter mapping in Martini goes beyond standard Spring MVC, handling various data types and special parameters like InputStream, Reader, and custom classes like DataWrapper.
Supported Handler Method Return Types
Martini supports a wide range of return types for handler methods, including void, HttpEntity, ResponseEntity, asynchronous types like Callable<?> and DeferredResult, and more. Custom return types can be handled by registered HttpMessageConverters, given that the method is annotated with @ResponseBody.
Response Content-Type Resolution
Martini follows a series of steps to determine the Content-Type for responses, considering @RequestMapping produces properties, query parameters, and HTTP Accept headers.
Troubleshooting Common Issues
- Issue: Methods in controllers not recognized.
- Resolution: Ensure proper use of annotations like
@RestControllerand@RequestMapping. - Issue: Incorrect response
Content-Type. - Resolution: Verify the
producesattribute in@RequestMappingand request headers.
Advanced Topics
For advanced topics on Spring controllers in Martini, such as custom HttpMessageConverter implementation or handling asynchronous requests, refer to the Spring MVC documentation.