Tomcat的AccessLogValve组件可配置日志格式,将请求参数(包括GET的查询串、POST的表单数据)写入访问日志,是最常用的查看请求参数的方式。
配置步骤:
conf/server.xml文件(如/usr/share/tomcat/conf/server.xml)。<Host>标签内添加或修改<Valve>配置,通过pattern属性指定日志格式,关键参数说明如下: %r:记录HTTP请求的第一行(包含请求方法、URI及GET参数,如GET /hello?name=zhangsan HTTP/1.1)。%{postdata}r:仅记录POST请求的请求体数据(如表单提交的name=zhangsan&age=20),需Tomcat 7.0及以上版本支持。%q:记录查询串(即URI后的?及后续参数,如?name=zhangsan)。<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t "%r" %s %{postdata}r %q %T" resolveHosts="false"/> sudo systemctl restart tomcat(或sudo service tomcat restart)。logs/localhost_access_log.<日期>.txt,可通过tail -f logs/localhost_access_log.txt实时查看。注意:
%r或%q自动记录;%{postdata}r记录,但需确保请求的Content-Type为application/x-www-form-urlencoded(表单提交默认格式),若为JSON等格式则无法直接通过此方式获取。若需在代码中查看请求参数(如参数值、参数名),可通过HttpServletRequest对象的方法获取,适用于开发或调试场景。
关键代码示例:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取所有参数名 Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); // 获取单个参数值(单值参数) String paramValue = request.getParameter(paramName); System.out.println("GET参数 - 名称:" + paramName + ",值:" + paramValue); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置POST请求编码(避免中文乱码) request.setCharacterEncoding("UTF-8"); // 获取所有参数名 Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); // 获取单个参数值(单值参数) String paramValue = request.getParameter(paramName); System.out.println("POST参数 - 名称:" + paramName + ",值:" + paramValue); } } 说明:
getParameterNames():获取所有请求参数的名称(Enumeration集合);getParameter(String name):根据参数名获取单个值(若参数有多个值,仅返回第一个);request.setCharacterEncoding("UTF-8"):必须设置,否则POST请求的中文参数会出现乱码(Tomcat 8及以上GET请求默认UTF-8,无需设置)。pattern调整(如减少不必要的字段);pattern排除);%{postdata}r仅能记录application/x-www-form-urlencoded格式的POST数据(如表单提交),若为JSON、XML等格式,需通过代码解析请求体(如request.getInputStream())。