I am woking on web service.Now I have session folders for each user, and each user has it's log file there. Now I want to read log files from java and pass it to index.jsp for show. As I have already used javax.servlet.http.HttpServletRequest req
- the req.setAttribute(REQUEST_IS_LOG, log);
and req.getRequestDispatch开发者_运维技巧er("index.jsp").forward(req, res);
do not work for me. Can someone help me to find another way? How can I take the text from file in display it in index?
Are they any way to do this with ajax?
Thank you in advance!
If it's in public webcontent, just use <jsp:include>
.
<pre>
<jsp:include page="logs/user123.txt" />
</pre>
Otherwise bring a HttpServlet
in between which gets an InputStream
of the desired resource and writes it to the OutputStream
of the response.
<pre>
<jsp:include page="logservlet/user123.txt" />
</pre>
Or if it is located at a different public domain, use JSTL <c:import>
.
<pre>
<c:import url="http://other.com/logs/user123.txt" />
</pre>
As to the Ajax part, just do something like
document.getElementById("log").innerHTML = xhr.responseText;
See also my answer on this question for more extensive examples.
JSP:
<% BufferedReader reader = new BufferedReader(new FileReader("log.txt")); %>
<% String line; %>
<% while ((line = reader.readLine()) != null) { %>
<%=line %>
<% } %>
This will work because jsp's can do anything Java can do. However, for larger projects you should look into using a Model-View-Controller implementation. There are several frameworks that can assist with this, such as Spring or Struts.
Finally I did like:
res.setContentType("text/plain");
request.setAttribute(REQUEST_IS_LOG, logs);
request.getRequestDispatcher("index.jsp").forward(req, res);
return;
Before I write like:
java.io.OutputStream result=res.getOutputStream();
that was why I couldn't use the method, which I wrote above. I just change to file like:
java.io.OutputStream result = new java.io.FileOutputStream((destinationDir+System.getProperty("file.separator")+"result"+n+"."+targetFormat.toLowerCase()));
and it works!
精彩评论