Latest

recent

Resource usage in Servlets


In request dispatching, discussed above, we can only dispatch to another active application resource, such as another servlet. We described passive application resources as elements such as HTML files.

We have shown that we can redirect to an application’s resources, such as HTML files. But how do we get access to this application’s resources directly, without having to redirect?

We can interact with an application’s passive resources through the servlet context. The ServletContext object allows us access to these resources through the getResource or getResourceAsStream methods:

❑  getResource: This method returns a URL object to a resource known to the servlet context, and we can access the resource as a URL object: 
URL url = servletContext.getResource("resourcefilename");

getResourceAsStream: This method allows us to read the resources body directly as an InputStream that we can manipulate: 
 InputStream is = servletContext.getResourceAsStream("resourcefilename");

The ResourceHandler servlet (code A) shows how we can implement these objects. In this example, we are accessing the HTML file shown in Code B. We reference it as a URL, through the getResource method, and also as an input stream, through the getResourceAsStream method. Note that only the TITLE tag of the servlet is displayed in the output, not the title of the included HTML file.

CODE A

package itso.servjsp.servletapi;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ResourceHandler extends HTMLFormHandler {
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML><TITLE>HTMLFormHandlerResource</TITLE></BODY>");
out.println("<H2>Servlet API Example -
HTMLFormHandlerResource</H2><HR>");
ServletContext sc = getServletContext();
URL url = sc.getResource("HTMLFormHandlerRedirect.html");
out.println("URL name: " + url.getFile());
out.println("<HR> Now the input file html:");
BufferedReader in = new BufferedReader(new
InputStreamReader(sc.getResourceAsStream("ResourceHandlerHTML.html")));
String str;
while ((str = in.readLine()) != null)
out.println(str);
in.close();
out.println("<HR></BODY></HTML>");
}
}

CODE B

<HTML>
<HEAD>
<TITLE>Servlet Examples - ResourceHandlerHTML</TITLE>
</HEAD>
<BODY>
<h4> Just a plain-old static HTML page </h4>
</BODY>
</HTML>
Resource usage in Servlets Reviewed by 1000sourcecodes on 00:39 Rating: 5
Powered by Blogger.