第一步:配置
web.xml
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ajaxchart</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 配置配置文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext.xml, classpath*:springcxf.xml </param-value> </context-param> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- SpringMvc配置 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <!-- 如果不指定该参数,tomcat系统时不会初始化所有的action,等到第一次访问的时候才初始化 --> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <!-- 配置全局的错误页面 --> <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/404.jsp</location> </error-page> </web-app>
applicationContex.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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:component-scan base-package="com.zf" /> <context:annotation-config /> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 注解方式支持事务 (如果要让注解方式也支持事务,就要配置该项)--> <aop:aspectj-autoproxy proxy-target-class="true"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"> <!-- 指定连接数据库的驱动 --> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <!-- 指定连接数据库的URL --> <property name="jdbcUrl" value="jdbc:mysql://192.168.1.140:3306/ajax"/> <!-- 指定连接数据库的用户名 --> <property name="user" value="root"/> <!-- 指定连接数据库的密码 --> <property name="password" value="root"/> <!-- 指定连接数据库连接池的最大连接数 --> <property name="maxPoolSize" value="20"/> <!-- 指定连接数据库连接池的最小连接数 --> <property name="minPoolSize" value="1"/> <!-- 指定连接数据库连接池的初始化连接数 --> <property name="initialPoolSize" value="1"/> <!-- 指定连接数据库连接池的连接的最大空闲时间 --> <property name="maxIdleTime" value="20"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.query.substitutions">true 1,false 0</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.OSCacheProvider</prop> <prop key="hibernate.cache.use_query_cache">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.zf.pojo</value> </list> </property> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"ref="sessionFactory"></property> </bean> <!-- XML方式配置事务 --> <tx:advice transaction-manager="transactionManager"id="transactionAdvice"> <tx:attributes> <tx:method name="*"propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- AOP配置事务 --> <aop:config> <aop:pointcut expression="execution(*com.zf.service.*.*(..))" id="servicePoint"/> <aop:advisor advice-ref="transactionAdvice"pointcut-ref="servicePoint"/> </aop:config> </beans>
springmvc.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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:annotation-config /> <context:component-scan base-package="com.zf.control" /> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- Freemarker配置 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath"value="/" /> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">0</prop> <!-- 测试时设为0,一般设为3600 --> <prop key="defaultEncoding">utf-8</prop> </props> </property> </bean> <!-- Freemarker视图解析器 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/> <property name="suffix"value=".ftl" /> <property name="contentType"value="text/html; charset=UTF-8" /> <property name="allowSessionOverride"value="true" /> </bean> <!-- View Resolver (如果用Freemarker就可以将该视图解析器去掉) --> <!-- <bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"> --> <!-- <property name="viewClass"value="org.springframework.web.servlet.view.JstlView" /> --> <!-- <property name="prefix"value="/" /> 指定Control返回的View所在的路径 --> <!-- <property name="suffix"value=".jsp" /> 指定Control返回的ViewName默认文件类型 --> <!-- </bean> --> <!-- 将OpenSessionInView打开 --> <bean id="openSessionInView" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 处理在类级别上的@RequestMapping注解--> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <!-- 配置过滤器 --> <list> <ref bean="openSessionInView" /> </list> </property> </bean> <!--JSON配置--> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- 该类只有org.springframework.web-3.1.2.RELEASE.jar及以上版本才有 使用该配置后,才可以使用JSON相关的一些注解--> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"/> </property> </bean> </list> </property> </bean> </beans>
oscache.properties
cache.memory=true
cache.key=__oscache_cache
cache.capacity=10000
cache.unlimited.disk=true
如果有些类在转换为JSON时,需要对其属性做一些格式那要用JSONjackson-annotations-.jar提供的一些注解如下:
@JsonSerialize(using = DateJsonSerelized.class) //表示该字段转换为json时,用DateJsonSerelized类进行转换格式 @Temporal(TemporalType.DATE) @Column(name = "date") private Date date ; @JsonIgnore //表示转换成JSON对象时忽略该字段 @OneToMany(mappedBy = "media" , fetch = FetchType.LAZY ) private List<Plane> planes ;
DateJsonSerelized类的定义如下:
package com.zf.common; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; public class DateJsonSerelized extends JsonSerializer<Date>{ private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); @Override public void serialize(Date value, JsonGenerator jgen,SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeString(sdf.format(value)); } }
Spring 监听器
package com.zf.common; import javax.annotation.Resource; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import com.zf.service.MediaService; /** * SpringMVC 监听器 在启动容器的时候会随着启动 * @author zhoufeng * */ @Component public class StartUpHandler implementsApplicationListener<ApplicationEvent>{ @Resource(name = "MediaService") private MediaService mediaService ; @Override public void onApplicationEvent(ApplicationEvent event) { //将数据全部查询出来,放入缓存 mediaService.queryAll(); } }
Spring类型转换器
package com.zf.common; import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import org.springframework.stereotype.Component; /** * 自定义Date类型的类型转换器 * @author zhoufeng * */ @Component("DateEdite") public class DateEdite extends PropertyEditorSupport{ private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Override public String getAsText() { return getValue() == null ? "" : sdf.format(getValue()); } @Override public void setAsText(String text) throws IllegalArgumentException { if(text == null || !text.matches("^\d{4}-\d{2}-\d{2}$")) setValue(null); else try { setValue(sdf.parse(text)); } catch (ParseException e) { setValue(null); } } }
然后在需要转换的Controller里面注册该类型转换器就可以了
/** * 类型转换器 * @param binder */ @InitBinder public void initBinder(WebDataBinder binder){ binder.registerCustomEditor(Date.class, dateEdite); }
Freemarker访问静态方法和属性
/** * Access static Method FTL访问静态方法和属性(可以将该方法提取出来,让所有的Controller继承,避免每个类中都要写一个该方法) * @param packname * @return * @throwsTemplateModelException */ private final static BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); private final static TemplateHashModel staticModels = wrapper.getStaticModels(); protected TemplateHashModel useStaticPacker(Class<?> clazz){ try { return (TemplateHashModel) staticModels.get(clazz.getName()); } catch (TemplateModelException e) { throw new RuntimeException(e); } };
然后在Action方法中加入下面的代码:
mav.getModelMap().put("MediaService", useStaticPacker(MediaService.class)); //允许Freemarker访问MediaService类的静态方法