1、向客户端输出文本消息:使用PrintWrite类。实例:
package chapter4;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Helloworld extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<b>ÏìÓ¦ÏûÏ¢</b>");
}
}
2、向客户端输出字节消息,如:图像和二进制文件等,用ServletOutputStream类实现。实例:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowImage extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("image/jpeg");
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[8192];
String imageName = request.getParameter("name");//使用name请求参数传递图像文件的绝对路径
FileInputStream fis = new FileInputStream(imageName);
int count = 0;
while(true)
{
count = fis.read(buffer);
if(count <= 0)
break;
os.write(buffer, 0, count);
}
fis.close();
}
}
假设在D盘MyEclipse目录下有一个.img文件,在浏览器中输入如下URL:http://localhost:8080/show/servlet/ShowImage?name=D:\MyEclipse\04.jpg即可显示图片。
版权声明:本文为liminlimin_limin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。