spring 小结
第一步:配置
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类的静态方法
spring 小结的更多相关文章
- Spring小结
一.环境搭建 创建Maven项目 一般pom.xml会出错,本地若无相应版本的jar包,则无法下载或下载速度非常慢,我的解决方案是,查找本地仓库的jar,修改为本地仓库有的jar即可 pom.xml的 ...
- Spring mvc中@RequestMapping 6个基本用法小结(转载)
小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMapping(value="/departments" ...
- Spring boot中使用springfox来生成Swagger Specification小结
Rest接口对应Swagger Specification路径获取办法: 根据location的值获取api json描述文件 也许有同学会问,为什么搞的这么麻烦,api json描述文件不就是h ...
- spring security 3中的10个典型用法小结
spring security 3比较庞大,但功能很强,下面小结下spring security 3中值得 注意的10个典型用法 1)多个authentication-provide可以同时使用 &l ...
- spring mvc中的拦截器小结 .
在spring mvc中,拦截器其实比较简单了,下面简单小结并demo下. preHandle:预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Control ...
- Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结
Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...
- Spring mvc中@RequestMapping 6个基本用法小结
Spring mvc中@RequestMapping 6个基本用法小结 小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMa ...
- Spring归纳小结(山东数漫江湖)
前言 如果说有什么框架是Java程序员必然会学习.使用到的,那么Spring肯定是其中之一.本篇博客,将根据博主在日常工作中对Spring的使用做一个系统的归纳小结. Spring的一些概念和思想 S ...
- 转:Spring mvc中@RequestMapping 6个基本用法小结
Spring mvc中@RequestMapping 6个基本用法小结 发表于3年前(2013-02-17 19:58) 阅读(11698) | 评论(1) 13人收藏此文章, 我要收藏 赞3 4 ...
随机推荐
- notepad++ gvim editplus 三款选择试用
notepad++开源 试用还不错 但默认不会识别语法高亮 要自己设置 比较烦 gvim 在XP下竟然无法返回命令行 百般折腾无奈放弃 editplus 自带资源栏 选择器 文件查找功能 ...
- 利用Excel画柱状图,并且包含最大最小值
如何利用Excel画出如上样式的图? 1.绘制柱状图.如何绘制柱状图,操作非常简单,选中数据,点击合适的图表样式即可. 2.添加误差线.选中已绘制好的图,添加误差线.如果误差线没有出现,可以使用”更多 ...
- 如何用Apache TCPMon来截获SOAP消息
在WebService服务器和客户机之间会传递SOAP消息,有时我们需要得到这些消息以便调试,而Apache的TCPMon可以帮助我们做到这一点. TCPMon的下载地址在http://ws.apa ...
- Thread safety
https://en.wikipedia.org/wiki/Thread_safety Thread safety is a computer programming concept applicab ...
- Android 加入一个动作按钮
在XML中声明一个动作按钮 所有的动作按钮和其他的可以利用的items都定义在menu资源文件夹中的XML文件中.为了增加一个动作按钮到工具栏,需要在工程 /res/menu/ 目录下面创建一个新的X ...
- 关于jQuery学习
≡[..]≡≡[..]≡ 所有的实例都位于document.ready里面--为了防止文档在未完全加载之前就运行函数导致操作失败. $(document).ready(function(){ --- ...
- Delphi出现“borland license information was found,but it is not valid for delphi”的错误,无法运行的解决方法
1) 删除文件: C:\documents and settings\<username>\.borland\registry.slm,如果在win8或在win7下,即C:\Users\H ...
- getComputedStyle()与currentStyle
getComputedStyle()与currentStyle计算元素样式 发表于 2011-10-27 由 admin “DOM2级样式”增强了document.defaultView,提供了get ...
- [Virtualization][SDN] VXLAN到底是什么 [转]
写在转发之前: 几个月以前,在北大机房和燕园大厦直接拉了一根光钎.两端彼此为校园内公网IP.为了方便连接彼此机房,我做个一个VPN server在燕园的边界,北大机房使用client拨回.两个物理机房 ...
- Qt中单例模式的实现(4种方法)
最简单的写法: 12345 static MyClass* MyClass::Instance(){ static MyClass inst; return &inst;} 过去很长一段时间一 ...