Write Glassfish output into servlet html page

旧街凉风 提交于 2020-01-05 07:11:14

问题


How to redirect Glassfish server output into HttpServletResponse.out? I am making servlet in NetBeans.


回答1:


here is a working example, just expose this as a servlet

public class ReadLogs extends HttpServlet {

    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.append("<html>\n<head>\n\n");
        out.append("<script>function toBottom()" + "{"
                + "window.scrollTo(0, document.body.scrollHeight);" + "}");
        out.append("\n</script>");
        out.append("\n</head>\n<body onload=\"toBottom();\">\n<pre>\n");
        try {
            File file = new File("C:\\pathToServerLogFile");
            BufferedReader in = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            while (in.ready()) {
                String x = in.readLine();
                sb.append(x).append("<br/>");
            }
            in.close();
            out.append("\n</pre>\n</body>\n</html>");
            out.close();
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

UPDATE

If you need to print only the last portion of the file use this after line "in.close();"

      //print only 1MB Oof data
      if(sb.length()>1000000){
        out.append(sb.substring(sb.length()-1000000, sb.length()));
      }else{
        out.append(sb.toString());
      }



回答2:


So.. to print only lines which appeared after invoking script I've made such code:

BufferedReader reader = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
int lines = 0;
while (reader.readLine() != null) {
    lines++;
}

reader.close();

BufferedReader reader2 = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
String strLine;
int i = 0;
while (i != lines) {
   reader2.readLine();
   i++;

}
while ((strLine = reader2.readLine()) != null) {
    out.println(stringToHTMLString(strLine));
    out.println("<br>");
}

reader2.close();

When servlet starts it counts lines in server log (saves it in variable i), then after clicking on action form it read lines which indexes are higher than i and displays it on html page. I've used function stringToHTMLString which I found somewhere on stackoverflow.

Greets.



来源:https://stackoverflow.com/questions/11988648/write-glassfish-output-into-servlet-html-page

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