demo程序代码如下:
HelloServlet.java:
package com.horizon.servlet; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HelloServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String output = ""; String fileName = request.getSession().getServletContext() .getRealPath("/") + "WEB-INF/conf/ff.txt"; fileName = fileName.replace("\\", "/"); System.out.println(fileName); File file = new File(fileName); try { BufferedReader input = new BufferedReader(new FileReader(file)); StringBuffer buffer = new StringBuffer(); String text; while ((text = input.readLine()) != null) buffer.append(text + "\n"); output = buffer.toString(); } catch (IOException ioException) { System.err.println("File Error!"); } request.setAttribute("output", output); request.getRequestDispatcher("/WEB-INF/jsp/FileDemo.jsp").forward( request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
web.xml:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">TestServletHelloServletHelloServlet<servlet-class>com.horizon.servlet.HelloServletclass>HelloServlet/HelloServlet
FileDemo.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">FileDemo<%=request.getAttribute("output")%>
访问:http://localhost:8080/TestServlet/HelloServlet
OK!