Prasad K
Prasad K

Reputation: 153

Force browser download in Servlet- Spring

I am new to Spring MVC and I had a doubt about accessing the HttpServletResponse object in a servlet.

Basically my code is something like this:

@RequestMapping("/part of requesturl")
@ResponseBody String methodName(HttpServletRequest request)
{
    //All the computations which build up a JSon

    return json;
}

Right now this json file is being displayed on the browser as a response. I need to force it to be downloaded to the disk of the user irrespective of the browser. By looking at the other posts, I figured I should do someting like this:

response.setContentType("application/force-download");

How do I get the response object here? Also, if someone could shed some more light on forcing download onto the browser that would be great. Thanks in advance!

Upvotes: 0

Views: 2725

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

How do I get the response object here ?

Very intuitive:

@ResponseBody String methodName(
        HttpServletRequest request, 
        HttpServletResponse response
) {
    response.setContentType("application/force-download");
        //...
}

Also, if someone could shed some more light on forcing download onto the browser that would be great.

See:

Upvotes: 3

Related Questions