The following is the structure of an application.
The following are the required files, before starting user need to add all the jersy jar files into an application.
FileDownloadService.java
[java]import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@Path("/files")
public class FileDownloadService {
private static final String FILE_PATH = "d:\\myfile.txt";
@GET
@Path("/txt")
@Produces("text/plain")
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"splessons_file.txt\"");
return response.build();
}
} [/java]
In the above code file path has been given with the name
myfile
that consists of the message
welcome to splessons
. Where @Produces is the annotation to get the type of the content.
web.xml
[xml]<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.splessons.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app> [/xml]
The following are the servlet methods.
Loading the servlet class: When the web container gets the request from the browser for servlet then servlet class will be loaded.
Creating servlet instance: The web container creates an object for the servlet when servlet class is loaded, here the important point is an object and will be created in life cycle only once.
init method: This method will be called by the web container after an object was created to the servlet. The functionality of the init() method is to initialize the servlet.
service method: The service() method will be called by web container when servlet will have the request, in case servlet is not initialized then above methods will be utilized. In the life cycle of servlet this method will be utilized only once.
destroy method: Web container is the responsibility to call this method utilized while vanishing an object of the Servlet from the service, it provides the chance for servlet to clean up the memory or junk data.
index.html
[html]<a href="rest/files/txt">Download Text File</a> [/html]
Now compile the code on the server the following is the link will be opened.
Now click on the displayed link then following file will be opened.
Now click on the open button the following text will be opened.