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 ...
随机推荐
- hiho42 : 骨牌覆盖问题·二
描述 上一周我们研究了2xN的骨牌问题,这一周我们不妨加大一下难度,研究一下3xN的骨牌问题?所以我们的题目是:对于3xN的棋盘,使用1x2的骨牌去覆盖一共有多少种不同的覆盖方法呢?首先我们可以肯定, ...
- 微信公众账号开发教程(二) 基础框架搭建——转自http://www.cnblogs.com/yank/p/3392394.html
上一章,我们已经初步讲解了微信公众账号开发的基本原理,今天我们来探索设计实现. 首先我们设计了模块层次图,当然图中只是给出一种实现方式,不局限于此.具体见下图. 主要功能介绍如下: 1)请求接口层.处 ...
- Mac OS X 上启动 FTP/SFTP server,并设置 log level
木易小伟的博客| 木易小伟的博客 2013-08-13 5708 阅读 FTP Log SFTP Mac OS 系统配置 1. 启动FTP Server: 命令行下, sudo -s launch ...
- 移动设备优先viewport
Bootstrap 3 的设计目标是移动设备优先,然后才是桌面设备.这实际上是一个非常及时的转变,因为现在越来越多的用户使用移动设备. 为了让 Bootstrap 开发的网站对移动设备友好,确保适当的 ...
- 用户控件UserControl图片资源定位(一)---Xaml引用图片
MEF编程实现巧妙灵活松耦合组件化编程,一些细节需要花费不小心思去处理: 其中组件中若包含用户控件,且需要访问图片资源,那么Xaml引用资源需要做以下设置 1. 用户控件(usercontrol)所在 ...
- Java中重点关键词的区分
1.final, finally, finalize的区别final-修饰符(关键字)如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承. 因此一个类不能既被声明为 abs ...
- 设计模式:命令模式(Command)
定 义:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化:对请求排列或者记录请求日志,以及支持可撤销的操作. 结构图: Command类: abstract class Comma ...
- ASP.NET MVC4中用 BundleCollection使用问题手记
ASP.NET MVC4中对JS和CSS的引用又做了一次变化,在MVC3中我们这样引用资源文件: <link href="@Url.Content("~/Content/Si ...
- Selenium2学习-029-WebUI自动化实战实例-027-判断元素是否存在
非常简单的源码,敬请各位小主参阅.若有不足之处,敬请大神指正,不胜感激! /** * Verify the element exist or not * * @author Aaron.ffp * @ ...
- Selenium2学习-002-Selenium2 Web 元素定位及 XPath 编写演示示例
此文主要对 Selenium2 的 Web 元素定位及 XPath 编写示例,敬请各位亲们参阅,共同探讨.若有不足之处,敬请各位大神指正,不胜感激! 通过 Firefox(火狐)浏览器的插件 Fire ...