Servlet Display Image - Following are the required files to get an image in servlet.
index.html
[html]<body>
<form method="get" action="./WI">
Enter User Name <input type="text" name="userField"> </br></br>
<input type="submit" value="Hey man see the picture">
</form>
</body>
[/html]
Where the developer just created text field to enter the
User Name.
DisplayImage.java
[java]package servletimage;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DisplayImage extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
{
//PrintWriter out = res.getWriter();
res.setContentType("image/gif"); // see different MIME type
ServletOutputStream sos = res.getOutputStream();// for binary stream of image files
String userName = req.getParameter("userField");
if(userName.startsWith("s") || userName.startsWith("a")|| userName.startsWith("i"))
{
File f = new File("e:\\splessons.png");
DataInputStream dis = new DataInputStream(new FileInputStream(f));
byte[] barray = new byte[(int) f.length()];
try
{
dis.readFully(barray); // now the array contains the image
}
catch (Exception e)
{
barray = null;
}
finally
{
dis.close( );
}
sos.write(barray); // send the byte array to client
sos.close();
}
else
{
sos.print("user name should be s/a/i");
}
}
}
[/java]
ServletOutputStream class provides a stream to write binary data into the response. It is an abstract class. The
getOutputStream() method of
ServletResponse interface returns the instance of
ServletOutputStream class. As mentioned in the code user name should be start with any letter of the name
sai. The
Java.io.DataInputStream class gives an application a chance to peruse primitive Java information sorts from a fundamental info stream in a machine-autonomous manner.
web.xml
[xml]
<web-app>
<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>servletimage.DisplayImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/WI</url-pattern>
</servlet-mapping>
</web-app>
[/xml]
Here make sure that
servlet name should be same and URL name should be same with the
HTML form.
Output
Following is the input page where user has to give user name and make sure that user should start with s or a or i.
After entering the correct username following image will come.
In case user give wrong user name then following message will be displayed.