在过滤器servlet中写入文件

时间:2014-10-18 00:18:53

标签: java file servlets

我尝试从过滤器中编写log.txt文件。我把文件放在WEB-INFWEB-INF/logs.txt)中。每次登录后都会执行过滤器。代码为:

HttpServletRequest httpReq = (HttpServletRequest) request;
String relpath = this.config.getInitParameter("Archivo");
String fullpath = this.config.getServletContext().getRealPath(relpath);

FileOutputStream out = new FileOutputStream(fullpath);
OutputStreamWriter outStream = new OutputStreamWriter(out);

// The write have some vars defined before...
outStream.write(remoteAddress + " | " + date + " | " + method + "\n");
outStream.close();

chain.doFilter(request, response);

执行时应用程序不会失败,但不会写入文件。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

import java.io.*;

 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.util.*;

  // Implements Filter class
  public class LogFilter implements Filter  {
 public void  init(FilterConfig config) 
                     throws ServletException{
  // Get init parameter 
  String testParam = config.getInitParameter("test-param"); 

  //Print the init parameter 
    System.out.println("Test Param: " + testParam); 
  }
   public void  doFilter(ServletRequest request, 
             ServletResponse response,
             FilterChain chain) 
             throws java.io.IOException, ServletException {

   // Get the IP address of client machine.   
   String ipAddress = request.getRemoteAddr();

   // Log the IP address and current timestamp.
    System.out.println("IP "+ ipAddress + ", Time "
                                   + new Date().toString());

    // Pass request back down the filter chain
    chain.doFilter(request,response);
  }
   public void destroy( ){
    /* Called before the Filter instance is removed 
    from service by the web container*/
     }
        }

答案 1 :(得分:0)

   this is web.xml

   <filter>
  <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
  <param-name>test-param</param-name>
  <param-value>Initialization Paramter</param-value>
   </init-param>
   </filter>
   <filter-mapping>
   <filter-name>LogFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>