servlet向客户端输出信息

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("ÏìÓ¦ÏûÏ¢");
	}
}

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. 
* * 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即可显示图片。

你可能感兴趣的:(java,web开发)