springmvc在项目中使用较多,本文将基于spring注解springMVC+freemarker+slf4j整合在一起,便于开发,后续还会将ibatis整合进来。
第一步:使用编程工具建立web工程,本文使用eclipse + tomcat 7.0 + jdk 1.7。
第二步:引入工程使用到的jar文件:
commons-logging-1.1.3.jar、freemarker-2.3.20.jar、logback-classic-1.0.9.jar、logback-core-1.0.9.jar、slf4j-api-1.7.7.jar、slf4j-ext-1.7.7.jar、spring-aop-4.0.5.RELEASE.jar、spring-beans-4.0.5.RELEASE.jar、spring-context-4.0.5.RELEASE.jar、spring-context-support-4.0.5.RELEASE.jar、spring-core-4.0.5.RELEASE.jar、spring-expression-4.0.5.RELEASE.jar、spring-web-4.0.5.RELEASE.jar、spring-webmvc-4.0.5.RELEASE.jar
第三步:web.xml文件增加springmvc配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>BBS</display-name>
<!-- Spring 服务层的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Spring 容器启动监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
第四步:在web.xml同层目录建立相应spring-servlet.xml文件,该文件名称由web.xml中servlet-name加-servlet组成。内容如下:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!--对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.zxy"/>
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 请求映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!--视图解释器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="suffix">
<value>.ftl</value>
</property>
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
</beans>
第五步:建立日志配置logback.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 控制台输出 -->
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n</Pattern>
</encoder>
</appender>
<!-- 文件输出 -->
<appender name="fileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>../logs/bbs.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n</Pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="consoleAppender" />
<appender-ref ref="fileAppender" />
</root>
</configuration>
第六步:在applicationContext.xml文件中增加freemarker的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Freemarker配置 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/view/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="number_format">0.##########</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="classic_compatible">true</prop>
<prop key="template_exception_handler">ignore</prop>
</props>
</property>
</bean>
</beans>
第七步:建立页面展示hello.ftl文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${title}</title>
</head>
<body>
${content}
</body>
</html>
第八步:建立日志帮助类LoggerUtil.java:
/**
*
*/
package com.zxy.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author zxy
*
*/
public class LoggerUtil {
private static String NAME = LoggerUtil.class.getName();
private LoggerUtil()
{
}
public static Logger getLogger()
{
return getLogger(getClassName());
}
public static Logger getLogger(String className)
{
return LoggerFactory.getLogger(className);
}
private static String getClassName()
{
StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
for (int i = 1; i < stacks.length; i++) {
if(!NAME.equals(stacks[i].getClassName()))
{
return stacks[i].getClassName();
}
}
return NAME;
}
}
第九步:建立后台控制文件HelloWorldController.java
/**
*
*/
package com.zxy.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.zxy.util.LoggerUtil;
/**
* @author zxy
*
*/
@Controller
public class HelloWorldController{
private final Logger logger = LoggerUtil.getLogger();
@RequestMapping(value="/hello", method={RequestMethod.GET})
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
logger.info("hello start...");
ModelAndView mv = new ModelAndView("hello");
mv.addObject("title", "Spring MVC And Freemarker");
mv.addObject("content", " Hello world , test my first spring mvc ! ");
logger.info("hello end...");
return mv;
}
}
第十步:将web工程加入tomcat容器中,并启动服务,访问url:http://localhost:8080/BBS/hello,后台出现如下日志,则证明部署成功:
......
......
信息: Mapped URL path [/hello] onto handler ‘HelloAction‘
六月 09, 2014 11:06:46 下午 org.springframework.web.servlet.DispatcherServlet initServletBean
信息: FrameworkServlet ‘spring‘: initialization completed in 420 ms
六月 09, 2014 11:06:46 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-apr-8080"]
六月 09, 2014 11:06:46 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-apr-8009"]
六月 09, 2014 11:06:46 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 2967 ms
2014-06-09 23:07:02.739 [http-apr-8080-exec-5] INFO com.zxy.controller.HelloWorldController - hello start...
2014-06-09 23:07:02.743 [http-apr-8080-exec-5] INFO com.zxy.controller.HelloWorldController - hello end...
PS:工程文件目录如下
springMVC+freemarker+slf4j整合(基于注解方式),布布扣,bubuko.com
springMVC+freemarker+slf4j整合(基于注解方式)
原文地址:http://www.cnblogs.com/justdoits/p/3779185.html