Java Tutorial/Servlet/Log

Материал из Java эксперт
Перейти к: навигация, поиск

Servlet Context Log

   <source lang="java">

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet {

 private ServletContext context;
 public void init(ServletConfig config) throws ServletException  {
   super.init(config);
   context = getServletContext();
   context.log("Init has been invoked");
 }
 public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException
 {
   ServletOutputStream out = res.getOutputStream();
   context.log("doGet has now been invoked");
   res.setContentType("text/html");
   out.println("<html><head><title>Logging Servlet</title></head>");
   out.println("<body>Visit the <tomcat-home>\\logs and open the xx file to see the log entries");
   out.println("</body></html>");
 }

}</source>





Servlet Log Filter

   <source lang="java">

import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet implements Filter {

 FilterConfig config;
 public void init(FilterConfig config){
   
 }
 public void setFilterConfig(FilterConfig config) {
   this.config = config;
 }
 public FilterConfig getFilterConfig() {
   return config;
 }
 public void doFilter(ServletRequest req,
                      ServletResponse res,
                      FilterChain chain) {

// ServletContext context = getFilterConfig().getServletContext();

 //  long bef = System.currentTimeMillis();
   //chain.doFilter(req, res); // no chain parameter needed here

// long aft = System.currentTimeMillis();

   //context.log("Request to " + req.getRequestURI() + ": " +(aft-bef));
   
   System.out.println("logging");
 }
 public void destroy(){}

}</source>