As like in Java code we canĂ¢t hardcode the filenames in JSP. Because the
application path differ from server to server and it needs to be generated
dynamically. So getting the application path at run time is the key point in
reading a flat file from JSP. Once we get the application path the remaining
part is similar to Java code.
The method that is used to get the application path is getRealPath. This is available in the interface ServletContext. We can access this method in JSP using implicit object, Application.
The method that is used to get the application path is getRealPath. This is available in the interface ServletContext. We can access this method in JSP using implicit object, Application.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Question & Answer Page</title> </head> <body> <h2><center>Welcome to Questionnaire Forum....!</center></h2> <br/><br/> <%@ page import = "java.lang.*,java.io.*,java.util.*" %> <% // variables for connecting to the flat file data source // Note: this is set up to look in the same directory as the jsp file. String fileName = "question_answer.txt"; BufferedReader br = null; FileReader fr; String inputPath = application.getRealPath("/") + File.separatorChar; try { // open a bufferedreader to read the file // get the current path of the jsp under the application server. // 'application' is a freebie from the parent servlet. fr = new FileReader (new File(inputPath + fileName)); br = new BufferedReader (fr); String line = br.readLine(); while (line != null) { out.println(line); %> <br/> <% line = br.readLine(); } br.close(); } catch (Exception e) { } %> </body> </html>