简介
由于进一步的学习以及便于自己更好的调试程序中遇到的错误,开始了将log4j整合到web项目中,项目是基于springmvc的,所以就做了一个springmvc和web项目的整合demo,本篇博客适用于对Maven有一定了解的朋友查看交流,对于初学者,首先我们先将springmvc框架搭建起来,然后再加入Log4j的整合
使用maven创建一个web工程
创建过程就不详细说了,创建完成后我的项目结构如下
resources下面的log4j.properties暂时可以不创建,是整合log4j需要考虑的
二、首先添加创建springmvc框架时项目依赖的jar包
在pom.xml下面添加
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.1.2.RELEASE</spring.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
三、创建springmvc-servlet.xml
在WEB-INF下面创建springmvc-servlet.xml添加配置如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<!--springmvc的注解驱动-->
<mvc:annotation-driven />
<!--指定扫描 base-package下面的包-->
<context:component-scan base-package="com.*"/>
<!--配置springmvc的viewResolver解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
四、在web.xml配置中添加如下配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- class DispatcherServlet会自动扫描classpath下面的名字为<servlet-name>-servlet.xml的配置文件,在这里,因为我servlet-name配置
的是springmvc,所以扫描到的就是springmvc-servlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置springmvc拦截.do的请求,类似也可以是 / 表示拦截所有的-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--中文处理过滤,如果不设计中文的处理下面这部分可以移除-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
OK,到这里我们最基本的关于springMVC的配置部分就完成了,接下来创建类
五、创建model类
User.java
package com.model;
/**
* Created by Nagrand-FatCat on 2015/12/23.
*/
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
六、创建controller类
Helloworld.java
package com.controller;
import com.model.User;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by Nagrand-FatCat on 2015/12/23.
*/
@Controller
public class Helloworld {
//private Logger logger=Logger.getLogger(this.getClass());
@RequestMapping("index.do")
public String toIndex(){
return "index";
}
/*
@RequestMapping("welcome.do")
public String welcome(Model model){
model.addAttribute("res","hello world");
return "welcome";
}
*/
@RequestMapping("login.do")
public String login(User user, Model model){
System.out.println(user.getUsername());
//logger.info("用户:" + user.getUsername());
model.addAttribute("user",user);
return "welcome";
}
}
七、接下来创建页面
先创建index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2015/12/23
Time: 14:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
// 获得本项目的地址(例如: http://localhost:8080/MyApp/)赋值给basePath变量
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 将 "项目路径basePath" 放入pageContext中,待以后用EL表达式读出。
pageContext.setAttribute("basePath",basePath);
%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="login.do" method="post">
用户名 :<input type="text" name="username" >
密码 :<input type="password" name="password">
<input type="submit" value="登陆">
</form>
</body>
</html>
然后是welcome.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2015/12/23
Time: 14:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
// 获得本项目的地址(例如: http://localhost:8080/MyApp/)赋值给basePath变量
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 将 "项目路径basePath" 放入pageContext中,待以后用EL表达式读出。
pageContext.setAttribute("basePath",basePath);
%>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>Welcome ,</p>
<p> ${user.getUsername()} 用户</p>
</body>
</html>
将项目部署到服务器上,完成创建,跑一下试试,springmvc框架就搭建完成了
八、接下来我们将log4j加入到项目里
在resources/prop 下创建log4j.properties文件
内容如下:
### set log levels ###
log4j.rootLogger = debug,stdout,D,E
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
然后再web.xml中添加以下配置
<!--设置log4j的配置文件位置-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/prop/log4j.properties</param-value>
</context-param>
<!--使用监听加载log4j的配置文件-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
最后将上面我在controller层下的Helloworld.java类中的 单行注释 都去掉,因为这部分是关于log4j的。然后就可以使用了,很简单吧
跑一下,控制台会输出日志文件的信息,E://logs/log下面也生成了日志文件,用日志记录程序运行的过程对我们调BUG有很多帮助呢