如何将 html link 点击记录到文本文件
How to log html link clicks to a text file
目前我正在实施 Java servlet 网络应用程序。
在 html 页面上,用户可以找到很多 URL 链接。
我想记录点击日志,包括时间、用户帐户名和点击 URL,到服务器上的特定文本文件中。
我想知道如何将文本写入服务器上的文本文件。
您必须使用登录 java 使用 log4j read more
如果你点击任何 link 然后传递一些参数来识别你的 link 在服务器端,假设当你点击 link 它会去你的 servlet 然后得到link 的参数并将其记录在文件中。
这是一个完整的例子:
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>
基本上任何 link 单击 index.html 都会报告给 servlet 并将 href 存储到 MonitorLog.log 文件中 tomcat 日志文件夹。
希望对你有所帮助
你们把它搞得太复杂了,使用第三方库等,当 none 是必要的时候!
这是我用于类似事情的一些示例代码,它将对特定目录的所有请求记录到数据库中,主要只是为了跟踪哪些文件受欢迎,但您当然可以将其切换为平面文件日志记录
我的代码:
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>
目前我正在实施 Java servlet 网络应用程序。 在 html 页面上,用户可以找到很多 URL 链接。
我想记录点击日志,包括时间、用户帐户名和点击 URL,到服务器上的特定文本文件中。
我想知道如何将文本写入服务器上的文本文件。
您必须使用登录 java 使用 log4j read more
如果你点击任何 link 然后传递一些参数来识别你的 link 在服务器端,假设当你点击 link 它会去你的 servlet 然后得到link 的参数并将其记录在文件中。
这是一个完整的例子:
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>
基本上任何 link 单击 index.html 都会报告给 servlet 并将 href 存储到 MonitorLog.log 文件中 tomcat 日志文件夹。
希望对你有所帮助
你们把它搞得太复杂了,使用第三方库等,当 none 是必要的时候!
这是我用于类似事情的一些示例代码,它将对特定目录的所有请求记录到数据库中,主要只是为了跟踪哪些文件受欢迎,但您当然可以将其切换为平面文件日志记录
我的代码:
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>