2014-10-18 68 views
0

我正試圖從過濾器中寫入log.txt文件。我把文件放在WEB-INFWEB-INF/logs.txt)。該代碼是:在過濾器servlet中寫入文件

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); 

該應用程序在執行時沒有失敗,但該文件未被寫入。有任何想法嗎?

+0

的可能的情況是,如果正在系統上創建文件成功,每到這個代碼路徑遍歷的時候,你在以前的條目踐踏(因爲你不使用['FileOutputStream'的替代構造函數](http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html)。我還強烈建議不要嘗試使用自制解決方案來編寫記錄並查看Log4J2或Logback,因爲這些配置和使用起來要容易得多。 – Makoto 2014-10-18 01:31:05

回答

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*/ 
    } 
     } 
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>