项目使用Gradle作为依赖管理工具。此项目建立在上一篇博客的基础上。
集成beetl
使用beetl作为视图引擎。
- 添加beetl依赖
//模板引擎
compile group: 'org.beetl', name: 'beetl-core', version: '2.2.3'
- 修改src/main/resources/spring-context-config.xml,使用beetl作为视图引擎。
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- scan the package and the sub package -->
<context:component-scan base-package="cn.yerl.spring.demo"/>
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven />
<bean id="beetlConfig" class="org.beetl.ext.spring.BeetlGroupUtilConfiguration" init-method="init"/>
<bean id="viewResolver" class="org.beetl.ext.spring.BeetlSpringViewResolver">
<property name="contentType" value="text/html;charset=UTF-8"/>
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/view/" />
<!-- 后缀 -->
<property name="suffix" value=".html" />
</bean>
</beans>
- Controller
package cn.yerl.spring.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping
public class IndexController {
@RequestMapping("/engine")
public ModelAndView engine(){
ModelAndView view = new ModelAndView("engine");
view.addObject("text", "Spring");
return view;
}
}
- 在src/main/java/webapp/WEB-INF/view下添加engine.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello Spring</title>
</head>
<body>
Hello ${text}
</body>
</html>
在src/main/resources下添加beetl.properties文件,可以修改beetl的配置
返回Json
使用fastjson返回json格式的数据。
- 添加fastjson依赖
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.17'
- 修改spring-context-config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- scan the package and the sub package -->
<context:component-scan base-package="cn.yerl.spring.demo"/>
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
- Controller
@Controller
@RequestMapping
public class IndexController {
@RequestMapping("/json")
public @ResponseBody Person json(){
return new Person("Alan", 25);
}
}
- Model
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person(){}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
- 效果
集成Log4j
- gradle引用即可,需要排除
commons-logging
引用
compile(group: 'org.springframework', name: 'spring-webmvc', version: '4.3.3.RELEASE'){
exclude group: 'commons-logging'
}
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.21'
compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.21'
compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.21'
在src/main/resources中添加log4j.properties文件,并配置log4j
拦截器
- 实现拦截器
package cn.yerl.spring.demo.interceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
/**
* Created by PoiSon on 2016/9/27.
*/
public class LogInterceptor implements HandlerInterceptor {
protected final Log logger = LogFactory.getLog(getClass());
private static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod){
HandlerMethod method = (HandlerMethod)handler;
StringBuilder builder = new StringBuilder("Action report ----------- ").append(sdf.get().format(new Date())).append(" ---------------------------\n");
builder.append("Controller : ").append(method.getBeanType().getName()).append(".(").append(method.getBeanType().getSimpleName()).append(".java:1)\n");
builder.append("Method : ").append(method.getMethod().getName()).append("\n");
Enumeration<String> e = request.getParameterNames();
if (e.hasMoreElements()){
builder.append("Parameter : ");
while (e.hasMoreElements()){
String name = e.nextElement();
String[] values = request.getParameterValues(name);
if (values.length == 1) {
builder.append(name).append("=").append(values[0]);
}
else {
builder.append(name).append("[]={");
for (int i=0; i<values.length; i++) {
if (i > 0)
builder.append(",");
builder.append(values[i]);
}
builder.append("}");
}
builder.append(" ");
}
builder.append("\n");
}
builder.append("--------------------------------------------------------------------------------\n");
logger.info(builder.toString());
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
此功能实现输出参数信息
- 修改
spring-context-config.xml
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<bean class="cn.yerl.spring.demo.interceptor.LogInterceptor"/>
<mvc:interceptor>
<mvc:mapping path="/log/*"/>
<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
<bean class="cn.yerl.spring.demo.interceptor.LogInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
集成beetlSql
- 添加beetlsql的引用和数据库的引用
//数据库
compile group: 'com.alibaba', name: 'druid', version: '1.0.26'
compile group: 'com.ibeetl', name: 'beetlsql', version: '2.6.5'
compile(group: 'org.springframework', name: 'spring-jdbc', version: '4.3.3.RELEASE')
- 修改
spring-context-config.xml
<!--数据库-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.0.185:1521:orcl
</value>
</property>
<property name="username">
<value>hyoa_base</value>
</property>
<property name="password">
<value>hyoa</value>
</property>
<property name="initialSize">
<value>2</value>
</property>
<property name="maxActive">
<value>2</value>
</property>
</bean>
<bean name="beetlSqlScannerConfigurer" class="org.beetl.sql.ext.spring4.BeetlSqlScannerConfigurer">
<!-- 哪些类可以自动注入 -->
<property name="basePackage" value="cn.yerl.spring.demo" />
<property name="daoSuffix" value="Dao" />
<property name="sqlManagerFactoryBeanName" value="sqlManagerFactoryBean" />
</bean>
<bean id="sqlManagerFactoryBean" class="org.beetl.sql.ext.spring4.SqlManagerFactoryBean">
<property name="cs">
<bean class="org.beetl.sql.ext.spring4.BeetlSqlDataSource">
<property name="masterSource" ref="dataSource"></property>
</bean>
</property>
<property name="dbStyle">
<bean class="org.beetl.sql.core.db.OracleStyle"></bean>
</property>
<property name="sqlLoader">
<bean class="org.beetl.sql.core.ClasspathLoader">
<property name="sqlRoot" value="/sql"></property>
</bean>
</property>
<property name="nc">
<bean class="org.beetl.sql.core.UnderlinedNameConversion">
</bean>
</property>
<property name="interceptors">
<list>
<bean class="org.beetl.sql.ext.DebugInterceptor"></bean>
</list>
</property>
</bean>
<!--数据库-->