Java servlets, write data from text file to web page

可紊 提交于 2019-12-24 17:15:50

问题


I have this servlet code in java:

package servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import java.net.*;


public class Servlet1 extends GenericServlet{
 private ServletConfig sc;
 public void init(ServletConfig conf) throws ServletException{
     super.init(conf);
     sc = conf;
 }

 public void read_file(){
     String filename = "/web/WEB-INF/Data.txt";
     BufferedReader br = new BufferedReader(new FileReader(filename));
     // Why this doesn't work ?

 }

 public void service(ServletRequest req, ServletResponse resp) throws ServletException,IOException{   
     resp.setContentType("text/html; charset=windows-1251");
     PrintWriter pw = resp.getWriter();
     pw.println("<html><head>");
     pw.println("<title>sdasdasda</title>");
     pw.println("</head><body><h2>Servlet information</h2>");
     pw.println("Servlet name - "+sc.getServletName()+ "<br>");
     pw.println("Servlet parametrs: <br>");
     //pw.println(read_file());
     Enumeration names = sc.getInitParameterNames();

     while(names.hasMoreElements()){
        String name = (String)names.nextElement();
        pw.print(name + ": ");
        pw.println(sc.getInitParameter(name)+"<br>");
     }
     pw.println("</body></html>");
     pw.flush();
     pw.close();
 }
 public void destroy(){
     sc = null;
 }

}

And this BufferedReader br = new BufferedReader(new FileReader(filename)); always shows that there is no suck file, but I put it in ProjectName/web/Web-INF/ folder. How do i read from this file, or get the right path to it ?


回答1:


First of all you are specifying an absolute path (your path starts with /)

Second FileReader is not the correct way of loading a resource in a web application, what is if your application war is not extracted? It will still fail.

You should use ServletContext#getResourceAsStream to get an InputStream and use it to read your resource.



来源:https://stackoverflow.com/questions/20775889/java-servlets-write-data-from-text-file-to-web-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!