• 原创Log4jWebTest


          这几天学习了下Log4j,但只是在main 函数里测试用。我自己在想,log4j是否可以结合Web使用呢?举个简单的例子,就像一个用户登录系统一样,如果只是简单的登录验证,那也太简单了。自己试着想,如果可以把用户登录的信息,记录到数据库里或者写入某个文件里,那不是很好么?至少方便以后查询。所以,就决定开始行动了。

          心动不如行动!

     =================================我是华丽的分割线===============================

    A)创建数据库及数据表

       create database test;

      创建 user 表:

      

    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(20) DEFAULT NULL,
      `password` varchar(20) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    View Code

    创建 log 表:

    CREATE TABLE `log` (
      `id` int(4) NOT NULL AUTO_INCREMENT COMMENT '自增id号',
      `username` varchar(45) NOT NULL DEFAULT '' COMMENT '用户名',
      `msg` varchar(555) DEFAULT NULL COMMENT '日志信息',
      `level` varchar(45) DEFAULT NULL COMMENT '当前日志的级别',
      `createTime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '创建时间',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
    View Code

    好了,数据库及数据表创建完成。

    B)创建项目工程 TestLog4j

    •    打开myeclipse 创建一个Web Project 取名 TestLog4j
    •   引入jar包,此处我们使用 log4j-1.2.14.jar 和 commons-logging.jar ,数据库jar包 mysql-connector-java-5.0.8-bin.jar
    •  而后创建视图login.jsp 、 fail.jsp 、 success.jsp,其中会用到css,还有部分图片。此处就免了。

    login.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>登录界面</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        
        <link rel="stylesheet" type="text/css" href="css/style.css">
      
      </head>
      
      <body>
       <div class="login">
        <h2>登录界面</h2>
        <form action="LoginServlet" method="post">
          <form  method="post">
                  用户名:<input type="text" name="username"><br>&nbsp;&nbsp;码:<input type="password" name="password"><br>
          <input type="submit" value="登陆">
          <input type="reset" value="重置">
        </form>
        </div>
      </body>
    </html>
    View Code

    fail.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>失败页面</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        
        <link rel="stylesheet" type="text/css" href="css/style.css">
    
      </head>
      
      <body>
        <div class="login">
                 对不起,登录失败!
            <a href="login.jsp">重新登录</a><br>
            <img width="200px" height="200px" src="images/cry.jpg">
        </div>
      </body>
    </html>
    View Code

    success.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>成功页面</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        
        <link rel="stylesheet" type="text/css" href="css/style.css">
        
    
      </head>
      
      <body background="images/suc.jpg">
        <div class="login">
       
              恭喜您,登录成功! <br>
         <img width="200px" height="200px" src="images/smile.jpg">
        </div>
      </body>
    </html>
    View Code
    • 接着创建我们的model层。model层中包含了UserBean 、 UserBeanBO、ConnDB三个类。
    • 而后创建控制层即servlet层。 里面含有Log4jInit.java  LoginServlet.java 两个类

    附上Log4jInit.java代码

    package com.whf.control;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.PropertyConfigurator;
    
    public class Log4jInit extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public Log4jInit() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the GET method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            
            //从web.xml配置读取,名字一定要和web.xml配置一致
            String file =this.getInitParameter("log4j");
              if(file != null){
                 PropertyConfigurator.configure(file);
              }
        }
    
    }
    View Code

    附上LoginServlet.java代码

    package com.whf.control;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.Logger;
    import org.apache.log4j.MDC;
    import org.apache.log4j.PropertyConfigurator;
    
    import com.whf.model.UserBeanBO;
    
    public class LoginServlet extends HttpServlet {
        
        private final static String DEFAULT_USERNAME="anonymous";
        
        /**
         * Constructor of the object.
         */
        public LoginServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            
            //如果直接 className.class 日志输出到全局的 即rootLogger 指定的文件中
            Logger logger = Logger.getLogger(LoginServlet.class);
            
            //得到用户名和密码,验证用户是否合法
            String u=request.getParameter("username");
            String p=request.getParameter("password");
            //System.out.println("u="+u+" "+"p="+p);
            
            //验证用户
            UserBeanBO ubo=new UserBeanBO();
            if(ubo.checkUser(u, p)){
                //用户合法
                MDC.put("username", u);
                logger.info("用户登录成功");
                request.getRequestDispatcher("success.jsp").forward(request, response);
            }else{
                //用户不合法
                MDC.put("username", DEFAULT_USERNAME);
                logger.warn("非法用户登录");
                request.getRequestDispatcher("fail.jsp").forward(request, response);
            }
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            this.doGet(request, response);
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            //do nothing
        }
    
    }
    View Code
    • 在 web.xml 中,还需要配置。
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name></display-name>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.whf.control.LoginServlet</servlet-class>
      </servlet>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>Log4jInit</servlet-name>
        <servlet-class>com.whf.control.Log4jInit</servlet-class>
        <init-param>
          <param-name>log4j</param-name><!-- 这个是名字是下边路径配置的标识(好像KEY一样) -->
          <param-value>/WEB-INF/classes/log4j.properties</param-value><!--这是容器初始化时候加载log4j配置文件的路径(这好像一个value);-->
        </init-param>
      </servlet>
    
    
      <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>Log4jInit</servlet-name>
        <url-pattern>/Log4jInit</url-pattern>
      </servlet-mapping>    
      <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    View Code

    C)创建 log4j.properties 文件

    #定义3个输出端
    log4j.rootCategory=INFO,A1,A2,A3
    
    #定义A1输出到控制器
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    #定义A1的布局模式为PaternLayout
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    # 定义A1的输出格式
    log4j.appender.A1.layout.ConversionPattern=%4p [%t] (%F:%L) - %m%n
    
    #定义A2输出到文件
    log4j.appender.A2=org.apache.log4j.RollingFileAppender
    #定义A2输出到哪个文件
    log4j.appender.A2.File=./log.txt
    #定义A2输出文件的最大长度
    log4j.appender.A2.MaxFileSize = 3KB
    #定义A2的备份文件数
    log4j.appender.A2.MaxBackupIndex = 3
    #定义A2的布局模式为PatternLayout
    log4j.appender.A2.layout=org.apache.log4j.PatternLayout
    #定义A2的输出模式
    log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n
    
    #定义A3输出到数据库
    log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender
    log4j.appender.A3.URL=jdbc:mysql://localhost:3306/test
    log4j.appender.A3.driver=com.mysql.jdbc.Driver
    log4j.appender.A3.user=root
    log4j.appender.A3.password=
    #定义A3的布局和执行的SQL语句
    log4j.appender.A3.layout=org.apache.log4j.PatternLayout
    log4j.appender.A3.layout.ConversionPattern=Insert into log(username,msg,level,createTime) values('%X{username}','%m','%-5p','%d{yyyy-MM-dd hh:mm:ss}')
    View Code

    D)发布项目

     启动Tomcat,将项目发布到空间即可。

    如果还有什么疑问,可以在博客留言。欢迎转载。

  • 相关阅读:
    Windows Php Apache Phpstorm VS Code
    cygwin学习
    Linux链表理解
    gcc和arm-linux-gcc默认头文件库搜索路径
    测试DOS命令
    字符二维数组char[][]与char**(转)
    浅谈 C++ 中的 new/delete 和 new[]/delete[] (转)
    Linux抢占式调度简介(转)
    USB中的端点详细了解(转)
    QT窗口组件的父子关系
  • 原文地址:https://www.cnblogs.com/whf-Staring/p/4435844.html
Copyright © 2020-2023  润新知