目前我正在实现一个Java servlet Web应用程序。 在html页面上,用户可以找到很多URL链接。
我想将带有时间的点击日志,用户的帐户名称和点击的URL记录到服务器上的特定文本文件中。
我想知道如何将文本写入服务器上的文本文件。
答案 0 :(得分:1)
您必须使用log4j read more
在java中使用日志记录如果单击任何链接,则传递一些将在服务器端标识链接的参数,假设当您单击链接时,它将转到您的servlet,然后获取该链接的参数并将其记录在文件中。
答案 1 :(得分:1)
这是一个完整的例子:
href servlet:
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log4JServlet extends HttpServlet {
static Logger log = Logger.getLogger(Log4JServlet.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("url");
response.setContentType("text/html");
log.info("info message " + url);
}
public void init(ServletConfig config) throws ServletException {
System.out.println("Log4JInitServlet is initializing log4j");
String log4jLocation = config.getInitParameter("log4j-properties-location");
ServletContext sc = config.getServletContext();
if (log4jLocation == null) {
System.err.println("*** No log4j-properties-location init param, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
} else {
String webAppPath = sc.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File logFile = new File(log4jProp);
if (logFile.exists()) {
System.out.println("Initializing log4j with: " + log4jProp);
PropertyConfigurator.configure(log4jProp);
} else {
System.err.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}
}
super.init(config);
}
}
然后是web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Log4JServlet</servlet-name>
<servlet-class>Log4JServlet</servlet-class>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Log4JServlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
log4j.property文件:
# Set the root logger to DEBUG.
log4j.rootLogger=INFO,MonitorAppender
# MonitorLog - used to log messages in the Monitor.log file.
log4j.appender.MonitorAppender=org.apache.log4j.FileAppender
log4j.appender.MonitorAppender.File=${catalina.base}/logs/MonitorLog.log
log4j.appender.MonitorAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.MonitorAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
index.html示例:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Link reporter</title>
</head>
<body>
<script>
$("body").delegate("a", "click", function (event) {
var url = $(this).attr('href');
reportUrl(url);
//remove the line below, I just used it so it would be easier to debug
event.preventDefault();
});
function reportUrl(url) {
$.get("/app/Log4JServlet", { url: url});
}
</script>
<a href="test.html">test1</a>
<a href="test2.html">test2</a>
<a href="test3.html">test3</a>
</body>
</html>
基本上,点击index.html的任何链接都将报告给servlet,并将href存储到tomcat logs文件夹中的MonitorLog.log文件中。
我希望有帮助
答案 2 :(得分:0)
当你们没有必要时,你们使用第三方库等过于复杂了!
这里有一些示例代码我用于类似的东西,它将所有请求记录到某个目录到数据库,主要是为了跟踪哪些文件很受欢迎,但你当然可以切换这个到flatfile日志记录
我的代码:
package com.zack6849.website.filters;
import com.zack6849.website.Database;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebFilter(urlPatterns = "/uploads/*")
public class StatisticsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
chain.doFilter(req, resp);
System.out.printf("[STATS] request to %s", request.getRequestURI());
if (request.getRequestURI() != null) {
Database database = new Database();
try {
ResultSet count = database.query("SELECT COUNT (url) as results FROM requests WHERE url = ?", request.getRequestURI());
boolean exists = count.getInt("results") > 0;
count.close();
if (!exists) {
database.executeUpdate("INSERT INTO requests (url, hits) VALUES (?, ?)", request.getRequestURI(), 0);
}
System.out.printf("[STATS] INCREMENTING 'hits' FOR %s", request.getRequestURI());
database.executeUpdate("UPDATE requests SET hits = hits + 1 WHERE url = ?", request.getRequestURI());
database.closeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
旧的servlet引擎可能要求您在web.xml中为此指定一个过滤器,它看起来应该是这样的
<filter>
<filter-name>logging</filter-name>
<filter-class>com.zack6849.website.filters.StatisticsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>logging</filter-name>
<url-pattern>/uploads/*</url-pattern>
</filter-mapping>