user1825015
user1825015

Reputation: 23

Vaadin navigating to @RequestMapping

I'm creating a webapplication using Springboot & Vaadin. I did write a controller that implements a @RequestMapping-method. This method generates a PDF that I should be able to see or download in a browser.

If I go to the link directly, everything does work. However when I use Vaadin's navigation, I do get some errors. (But when I refresh that page, it does work).

Below you can find my code:

@RestController
public class PDFController {
    @RequestMapping(value = "fichedownload", method = RequestMethod.GET,produces = MediaType.APPLICATION_PDF_VALUE)
    public static ResponseEntity<InputStreamResource> ficheReport() throws IOException {
        ByteArrayInputStream bis = GeneratePdfReport.ficheReport();
        HttpHeaders headers = new HttpHeaders();
        
        //Download
        //headers.add("Content-Disposition", "attachment; filename=fiche.pdf");

        //View in browser
        headers.add("Content-Disposition", "inline; filename=fiche.pdf");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(new InputStreamResource(bis));
    }
}

In some Vaadin-view

Button generatePDF = new Button();
generatePDF.addClickListener(event->{
    UI.getCurrent().navigate("fichedownload");
});

Manual link to 'http://localhost:8080/fichedownload' gives me the expected result.

generatePDF button navigates to 'http://localhost:8080/fichedownload' but gives a 'Couldn't find route for 'fichedownload' - error. Do I have to set a route, or does a navigate not 'trigger' the @RequestMapping?

Upvotes: 0

Views: 350

Answers (1)

Erik Lumme
Erik Lumme

Reputation: 5352

The UI.getCurrent().navigate(...), and other Router navigation methods, can only be used for navigating to routes registered with Vaadin (e.g. using @Route).

In your case I'd recommend using an Anchor instead of a button. It corresponds to a normal <a> link in the browser, and you can give it any URL. Another benefit is that no server-roundtrip is needed.

Alternatively you can try using the Button as you do, but navigating with UI.getCurrent().getPage().setLocation(...). If that doesn't work, try UI.getCurrent().getPage().executeJs("window.open('your_url', '_blank')").

Upvotes: 4

Related Questions