Search code examples
javakotlinmicronaut

Alternatives for HttpServletRequest and HttpServletResponse in Micronaut


I am playing with Micronaut and what I currently miss is access to HttpServletRequest and HttpServletResponse. These normally allow to access things like:

  • request parameters
  • input/output stream (especially writing directly to output stream)
  • getting/setting cookies
  • getting/setting headers
  • getting client IP

Also I am not sure about alternatives for:

  • @RequestParam files: List<MultipartFile>
  • @RequestBody myClass: MyClass

Solution

  • https://docs.micronaut.io/latest/guide/index.html#requestResponse and https://docs.micronaut.io/latest/guide/index.html#binding shows how to bind to request parameters, cookies, headers, etc.

    https://docs.micronaut.io/latest/guide/index.html#uploads shows how to handle file uploads.

    input/output stream (especially writing directly to output stream)

    Micronaut does things differently so you don't have access to a stream to write to. You can return a reactive type to have your data pushed to the response as soon as it's available.

    getting client IP

    Typically available via the host header or https://docs.micronaut.io/latest/api/io/micronaut/http/HttpRequest.html#getRemoteAddress--

    Edit: Sending an XML file chunked

    @Get(uri = "/xml", produces = MediaType.TEXT_XML)
    Flowable<String> getXml() {
        return Flowable.create(emitter -> {
            emitter.onNext("<<xml header>>");
            //do some work
            emitter.onNext("more xml");
            emitter.onNext("<<xml footer>>");
        }, BackpressureStrategy.BUFFER);
    }