如何使用Java Servlet从文本文件读取到html页面

时间:2017-08-04 04:28:17

标签: java html jsp servlets netbeans

我正在尝试创建一个HTML表单,它使用Java Servlet显示文本文件中的文本。我不断收到以下错误:实例化servlet类servlets.ReportServlet时出错。

以下是HTML页面:

<html>
<head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <form name = "managementReports" method = "get" action = 
"ReportServlet">
    <input type="submit">
    </form>
</body>
</html>

这是我的servlet:

package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.annotation.WebServlet;
@WebServlet(urlPatterns = { "/ReportServlet" })
public class ReportServlet extends HttpServlet   
{
public void service(HttpServletRequest req, HttpServletResponse res) throws 
ServletException, IOException  
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();

String name = req.getParameter("filename");

BufferedReader br = new BufferedReader(new 
FileReader("c:/Consignment.txt"));

String str;
while( (str = br.readLine()) != null )
{
 pw.println(str + "<BR>");
}

br.close();
pw.close();
}
}

这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 version="3.1">
<servlet>
    <servlet-name>CustomerServlet</servlet-name>
    <servlet-class>servlet.CustomerServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>ConsignmentServlet</servlet-name>
    <servlet-class>servlet.ConsignmentServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>ReportServlet</servlet-name>
    <servlet-class>servlet.ReportServlet</servlet-class>
</servlet>
session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
</web-app>

任何建议都将不胜感激

1 个答案:

答案 0 :(得分:-1)

试试这个one并尝试此one。如果您的错误,请查看此one