如何编写Java日志Servlet?

问题描述 投票:1回答:3

我想在我的系统中做一些日志,比如用户操作,我知道在servicelet中我可以得到请求的所有session,参数等。

所以我想写Servlet

public class UserActionCheck extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        Map map = request.getParameterMap();
        Set keSet = map.entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }

            for (int k = 0; k < value.length; k++) {
                System.out.println(ok + "=" + value[k]);
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //HttpSession session = request.getSession();
    }
}

然后我可以在tomcat控制台看到参数输出,但我得到的是空白页面。

似乎页面在 doGet 方法...

那么我应该如何让它继续下去呢?

用那个 RequestDispatcher?

也是如何处理在 doPost?

java servlets
3个回答
2
投票

对于你的目的,最好的方法是使用一个叫做 Filter.

例子 :

@WebFilter(filterName = "monitoringFilter", urlPatterns = { "/*" })
public class MonitoringFilter implements Filter
{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    {
        // Right here do your stuff pretty much like in a servlet
        request // ... get information you need

        // Process request as normal
        chain.doFilter(request,response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException
    {

    }

    @Override
    public void destroy()
    {

    }
}

更多信息 :


-1
投票

你应该使用 log4j文件处理程序 在你的应用程序中实现日志记录.类似这样:::

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class A{
  static Log log = LogFactory.getLog(A.class);
  void methodA(){
   try{
    log.info("I am inside A");
   } catch(Exception e) {
      log.error("error" , e);
     }
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.