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 ...
随机推荐
- mysql IN 比等价的OR写法效率更高
- 第十章:鸟哥的Linux私房菜
第十章.vim程式编辑器 1. vi与vim 1.1 为何要学vim2. vi的使用 2.1 简易执行范例 2.2 按键说明 2.3 一个案例的练习 2.4 vim的暂存档.救援回复与开启时的警告讯息 ...
- double-clicking
<!doctype html> <button id="id0" onclick="w('id0','str0')">target0&l ...
- (转)面试题--JAVA中静态块、静态变量加载顺序详解
public class Test { //1.第一步,准备加载类 public static void main(String[] args) { new Test(); //4.第四步,new一个 ...
- http响应状态码301和302
HTTP返回码中301与302的区别 (2012-10-15 22:06:09) 一.官方说法 301,302 都是HTTP状态的编码,都代表着某个URL发生了转移,不同之处在于: 301 redir ...
- nginx生产配置
user www www; worker_processes 8; error_log /data/logs/nginx_error.log crit; pid /usr/local/webserve ...
- Python中整数和浮点数
Python支持对整数和浮点数直接进行四则混合运算,运算规则和数学上的四则运算规则完全一致. 基本的运算: 1 + 2 + 3 # ==> 6 4 * 5 - 6 # ==> 14 7.5 ...
- [Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement]错误解决
1.配置文件中将这行注销“secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.7/Uploads" ”:很多人添加权限依然不 ...
- c语言main函数返回值、参数详解(返回值是必须的,0表示正常退出)
C语言Main函数返回值 main函数的返回值,用于说明程序的退出状态.如果返回0,则代表程序正常退出:返回其它数字的含义则由系统决定.通常,返回非零代表程序异常退出. 很多人甚至市面上的一些书籍,都 ...
- 采用asyncore进行实时同步
最近在维护项目的时候,发现某个实时数据同步功能非常容易失败,故静下心来彻底弄清楚该设计的实现原理,以及其中用到的python异步sockethandler : asyncore. 实时数据同步功能的设 ...