19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 42.25<br />

The servlet returns an image along with the text.<br />

Create the servlet named ImageContent in Listing 42.13.<br />

<br />

<br />

package chapter42;<br />

Listing 42.13 ImageContent.java<br />

import javax.servlet.*;<br />

import javax.servlet.http.*;<br />

import java.io.*;<br />

public class ImageContent extends HttpServlet {<br />

/** Process the HTTP Get request */<br />

public void doGet(HttpServletRequest request, HttpServletResponse<br />

response) throws ServletException, IOException {<br />

response.setContentType("text/html");<br />

PrintWriter out = response.getWriter();<br />

String country = request.getParameter("country");<br />

out.println("");<br />

// Read description from a file and send it <strong>to</strong> the browser<br />

java.util.Scanner input = new java.util.Scanner(<br />

new File("c:\\book\\" + country + ".txt"));<br />

// Read a line from the text file and send it <strong>to</strong> the browser<br />

while (input.hasNext()) {<br />

out.println(input.nextLine());<br />

}<br />

}<br />

}<br />

out.close();<br />

<br />

You should create a direc<strong>to</strong>ry C:\book\liangweb\web\resources\image and<br />

s<strong>to</strong>re image files in this direc<strong>to</strong>ry.<br />

The country parameter determines which image file and text file are<br />

displayed. The servlet sends the HTML contents <strong>to</strong> the browser. The<br />

contents contain an tag (lines 16–17) that references <strong>to</strong> the image<br />

file.<br />

44

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!