Spring+MVC+MyBatis综合例证
Spring+MVC+MyBatis综合例子
2,applicationContext.xml 这spring的默认配置文件,可以通过它整个其它第三方框架到spring中,本例整合mybatis到spring中,
3,mybatisConfig.xml 这个是myBatis的配置文件,它可以单独使用,但如果整合到spring中部分部分不再使用,具体见文件中注释,
4,spring3MVC-Dispatcher-servlet.xml 这个是springMVC配置文件,默认文件名格式为:springMVC的servlet名称 + "-servlet.xml",各个扫描包定义,参数,静态资源,国际化,拦截器,上传功能,错误处理,试图前后缀等处理在此定义,具体参见如下:
这比较综合的例子,在myEclipse环境实验中运行OK,因myEclipse和Eclipse有些不同,以及所引入的 jar 不完全相同,以及新旧版本不同,在搭建是注意考虑这些小问题;
现在已经很多spring+mvc+mybatis例子,网上已经很多,本例子是在实验时spring整合mybatis的综合情况,以下是例子使用myEclipse建立搭建的各个配置文件,分别如下:
1,项目web.xml ,spring,listerner等引入;
<?xml version="1.0" encoding="utf-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>SITE637Hulian</display-name> <!-- high version alread handle in MVC filter --> <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> --> <!-- high version should not active --> <!-- <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> --> <!-- filter: char code filter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- filter: login status filter --> <filter> <filter-name>loginFilter</filter-name> <filter-class> com.stshl.filter.LoginFilter </filter-class> </filter> <!-- each filter mapping --> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/memberCenter/be</url-pattern> <url-pattern>/memberCenter/be/*</url-pattern> </filter-mapping> <!-- listener define, can count online user in listener --> <listener> <description>GetOnlineUserNumber</description> <listener-class>com.stshl.listener.OnlineListener</listener-class> </listener> <!--Spring的ApplicationContext 载入高版本如MyEclipse10可以不启用,因有些版本已经具备XML扫描功能 --> <!-- <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> --> <!-- Spring 刷新Introspector防止上下文Context内存泄露, 高版本或如MyEclipse10可以不启用 --> <!-- ok too, <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> --> <!-- <listener> <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class> </listener> --> <!-- Spring 加载Log配置文件, 如果用apache的可以不启用 --> <!-- <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> --> <!-- 指定Spring3的配置文件和MVC配置文件和其它整合到spring中的第三方框架 --> <servlet> <servlet-name>spring3MVC-Dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/*.xml</param-value> <!-- 扫描加载 applicationContext.xml [Spring配置文件,可以用来整合第三方框架] 和spring3MVC-Dispatcher.xml[MVC使用] 和server-cache.xml文件 [可整合到spring中的缓存配置文件] 说明:这两个配置XML文件中定义的Bean是工具类的Bean; 它们是根据Spring,MyBatis等第三方框架已经开发好的jar包中提供的类文件来建立Bean; --> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置spring3MVC-Dispatcher映射器,作用的目标资源 --> <servlet-mapping> <servlet-name>spring3MVC-Dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 单位:分钟 --> <session-config> <session-timeout>35</session-timeout> </session-config> <!-- 在SpringMVC的配置文件中已经处理了错误,这里可以不启用 --> <!-- <error-page> <error-code>404</error-code> <location>/resources/common/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/resources/common/500.jsp</location> </error-page> --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
2,applicationContext.xml 这spring的默认配置文件,可以通过它整个其它第三方框架到spring中,本例整合mybatis到spring中,
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- classpath:...仅仅匹配本工程的classpath下文件; classpath*:...匹配本工程的classpath下文件外,还匹配本工程引用的所有jar下的classpath下文件; --> <!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="order" value="1" /> <property name="locations"> <list> <value>classpath:config/properties/config.properties</value> </list> </property> </bean> --> <!-- (未启用)指定spring使用的 properties 资源文件, 上面id=propertyConfigurer的Bean低或其它版本使用--> <context:property-placeholder location="classpath:config/configDBInfo.properties" /> <!-- 连接池 DBCP 参数意义和设置可参考网上说明nba 本示例采用DBCP连接池,以MS SQL SERVER2008库为例子, 应预先把的DBCP的jar包复制到工程的lib目录下, 用到的jar包各个版本有 commons-dbcp.jar,commons-collections.jar和commons-pool-1.3.jar; 此外还需要各个数据库对应的JDBC的jar包; --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- DB driverName: mysql: com.mysql.jdbc.Driver; SQLServerV2005+: com.microsoft.sqlserver.jdbc.SQLServerDriver Oracle: oracle.jdbc.driver.OracleDriver DB URL: mysql: jdbc:mysql://localhost:3306/mybatis_spring?useUnicode=true&characterEncoding=UTF-8 SQLServerV2005+: jdbc:sqlserver://localhost:1433;databaseName=YourDataBaseName Oracle: jdbc:oracle:thin:@localhost(/IP):1521(/port):oracleSID --> <property name="driverClassName" value="${database.driverClassName}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.userName}" /> <property name="password" value="${database.password}" /> <!--以MS SQL SERVER2008为例子--> <!-- <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=dbName" /> <property name="username" value="dbUserName" /> <property name="password" value="dbPassword" /> --> <property name="initialSize" value="30" /> <property name="maxIdle" value="100" /> <property name="minIdle" value="30" /> <property name="maxActive" value="100" /> <property name="removeAbandoned" value="false" /> <property name="removeAbandonedTimeout" value="600" /><!-- 自动回收超时时间(以秒数为单位) --> <property name="maxWait" value="90000" /><!--超时等待时间以毫秒为单位--> <property name="defaultAutoCommit" value="false" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis"> <value>300000</value> </property> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis"> <value>300000</value> </property> <property name="validationQuery"> <value>SELECT 1</value> </property> <property name="testOnBorrow"> <value>true</value> </property> <property name="testOnReturn"> <value>false</value> </property> </bean> <!-- 使用org.apache.commons.dbcp.BasicDataSource 连接 Oracle数据库 --> <!-- http://blog.****.net/kunkun378263/article/details/8506355 --> <!-- ================ MyBatis SqlSession配置 ================ --> <!-- 使用SqlSessionFactoryBean工厂产生SqlSession对象,方便后期注入Dao --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--dataSource属性指定要用到的连接池--> <property name="dataSource" ref="dataSource"/> <!--configLocation属性指定mybatis的核心配置文件--> <property name="configLocation"> <value>classpath:config/mybatisConfig.xml</value> </property> <property name="mapperLocations"> <list> <!-- 可单个文件一一列出,如下面所示 <value>classpath:config/mybatis/xTableMapper.xml</value> --> <!-- 可使用各种正则匹配模式进行匹配,例如表示匹配在config/mybatis目录下的任意包下 以-resultMap.xml或-mapper.xml结尾所有文件 <value>classpath:config/**/mybatis/**/*Mapper.xml</value> --> <!-- 注意:这里已经扫描/加载数据库各个表的映射XML文件,MyBatis的配置文件中就 不用重复扫描/加载各个映射XML,否则Bean的唯一性检测不通过; --> <value>classpath:config/mybatis/*.xml</value> </list> </property> </bean> <!-- 注册mybatis的mapper(接口)方式1, 这种方式,每个接口得定义一个对应bean,id不同且唯一;class相同; 内部的property元素的name相同,value属性值不同,对应各个接口; --> <!-- <bean id="xxxServicesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.stshl.service.xxxBeanService"/> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> --> <!-- 注册mybatis的mapper(接口)方式2,(推荐方式,因简单,代码少) 不指定mapper,而是指定某个包,使用自动扫描方式注册包中各个Mapper(即接口),但底版本spring和mybatis暂时不可用, 高版本[如:spring3和mybatis-spring-1.2.1.jar]可用 参考 http://haohaoxuexi.iteye.com/blog/1843309 --> <bean id="servicesMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage"> <value>com.xxx.yyy.service,com.xxx2.yyy2.app.service</value> <!-- 可设置多个接口包,多个接口包之间用逗号隔开 --> </property> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <!-- =====================以下是事务有关===================== --> <!-- 用spring的AOP给代码添加事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 事务应用到哪些方法上,这里使用XML配置声明, 也可以加入支持注解的JAR包然后使用注解的方式完成, --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 各个方法名的定义可自定义,哪些只读,哪些可回滚,方法名的前缀定义可参考如下 --> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true"/> <tx:method name="list*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="edit*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="execute*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="*" read-only="true" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <!-- 用spring AOP给service层的方法添加事务管理 --> <aop:config> <!-- pointcut定义切入点 --> <aop:pointcut id="bussinessService" expression="execution(public * com.xxx.yyy.service..*.*(..))" /> <!-- advisor 是切入点pointcut和通知advice的适配器,使某切入点使用什么建议,把两者连接一起综合使事务起作用 --> <aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" /> </aop:config> <aop:config> <!-- pointcut定义切入点 --> <aop:pointcut id="bussinessService2" expression="execution(public * com.xxx.kkk.app.service..*.*(..))" /> <!-- advisor 是切入点pointcut和通知advice的适配器,使某切入点使用什么建议,把两者连接一起综合使事务起作用 --> <aop:advisor pointcut-ref="bussinessService2" advice-ref="txAdvice" /> </aop:config> <!-- 因无法自动完成Bean加载而需要人工手动定义Bean到Spring配置文件,这里完成加载到Sprint容器中 --> <!-- <bean class="com.stshl.validator.BookCategoryValidator"></bean> --> <!-- 向Spring容器注册扩展了Spring以有功能的用户自定义的某个验证器/解析器 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" init-method=""> <property name="webBindingInitializer"> <bean class="com.xxx.kkk.validator.SystemWebBindingInitializer"></bean> </property> </bean> <!-- bean配置时加init-method属性,则指定的bean在实例化完成并加入spring容器之后自动运行init-method属性指定的方法 --> <bean class="com.stshl.config.SystemConfigComFunService" init-method="refreshSystemConfigInfoFromDatebase"> </bean> </beans>
3,mybatisConfig.xml 这个是myBatis的配置文件,它可以单独使用,但如果整合到spring中部分部分不再使用,具体见文件中注释,
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 属性配置,当没有整合到spring框架中时,可以把数据库的连接信息设置放到properties文件中 --> <!-- <properties resource="jdbc.properties"/> --> <!-- 设置缓存和延迟加载等等重要的运行时的行为方式,更多相关属性参考如下URL http://blog.sina.com.cn/s/blog_9344098b0100vrot.html http://limingnihao.iteye.com/blog/1060764 http://takeme.iteye.com/blog/1732801 [解释相当详细] --> <settings> <!-- 配置全局性 cache 的 (开 / 关) default:true --> <setting name="cacheEnabled" value="true" /> <!-- 是否使用 懒加载 关联对象 同 hibernate中的延迟加载 一样 default:true --> <setting name="lazyLoadingEnabled" value="true" /> <!-- [当对象使用延迟加载时 属性的加载取决于能被引用到的那些延迟属性,否则,按需加载(需要的是时候才去加载)] --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true--> <setting name="useColumnLabel" value="true" /> <!--允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键, 有一些驱动器不兼容,不过仍然可以执行。 default:false--> <!-- <setting name="useGeneratedKeys" value="false" /> --> <!-- <setting name="enhancementEnabled" value="true" /> why?导致出错 --> <!-- 这是默认的执行类型 SIMPLE:简单 REUSE:执行器可能重复使用prepared statements 语句 BATCH:执行器可以重复执行语句和批量更新 --> <setting name="defaultExecutorType" value="SIMPLE" /> <!-- 设置驱动等待数据响应的超时数 默认没有设置--> <setting name="defaultStatementTimeout" value="60000"/> <!--指定 MyBatis 如何自动映射 数据基表的列 ,NONE:不隐射 PARTIAL:部分 FULL:全部--> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- [是否启用 行内嵌套语句 defaut:false] --> <setting name="safeRowBoundsEnabled" value="false"/> <!-- [是否 启用 数据中 A_column 自动映射 到 java类中驼峰命名的属性 default:fasle] --> <setting name="mapUnderscoreToCamelCase" value="false"/> <!-- 设置本地缓存范围, session:就会有数据的共享;statement:语句范围 (这样就不会有数据的共享),defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 设置但JDBC类型为空时,某些驱动程序要指定值,default:other --> <setting name="jdbcTypeForNull" value="OTHER"/> <!-- 设置触发延迟加载的方法 --> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> </settings> <!-- POJO的别名设置,一般仅把首字母改小写即可,也可根据需要改成需要的别名 --> <typeAliases> <typeAlias alias="news" type="com.xxx.ttt.model.News" /> <typeAlias alias="newsCategory" type="com.xxx.ttt.model.NewsCategory" /> <typeAlias alias="user" type="com.xxx.ttt.model.Member" /> <!-- 更多可在这里定义 --> </typeAliases> <!-- 当整合进Spring时下面的内容不用;由Spring指定连接信息,最多仅用上面的settings和typeAliases定义而已, 但仅保留方便单独使用mybatis时做参考, 如下是各种库的驱动名和URL,本例以MS SQL SERVER2008为例; DB driverName: mysql: com.mysql.jdbc.Driver; SQLServerV2005+: com.microsoft.sqlserver.jdbc.SQLServerDriver Oracle: oracle.jdbc.driver.OracleDriver DB URL: mysql: jdbc:mysql://localhost:3306/mybatis_spring?useUnicode=true&characterEncoding=UTF-8 SQLServerV2005+: jdbc:sqlserver://localhost:1433;databaseName=YourDataBaseName Oracle: jdbc:oracle:thin:@localhost(/IP):1521(/port):oracleSID --> <!-- <environments default="development"> <environment id="development"> < ! - - 使用JDBC的事务管理, 此处为MS SQL SERVER 2008 - - > <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/> <property name="url" value="jdbc:sqlserver://localhost(/IP):1433(/port);databaseName=dbName" /> <property name="username" value="dbUser"/> <property name="password" value="dbPassword"/> </dataSource> </environment> </environments> --> <!-- 当整合到Spring后,数据库各个表的映射XML文件由Spring配置文件中名或ID为sqlSessionFactory的Bean 的名或ID为mapperLocations的property元素列表扫描/加载; 这里就不用扫描/加载,否则Bean的唯一性检测不通过 --> <!-- <mappers> <mapper resource="config/mybatis/xTableMapper.xml"/> </mappers> --> </configuration>
4,spring3MVC-Dispatcher-servlet.xml 这个是springMVC配置文件,默认文件名格式为:springMVC的servlet名称 + "-servlet.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"> <!-- 可以根据需要整合其它配置的XML文件 --> <!-- <import resource="config/demo-servlet.xml"/> --> <!-- 启动时扫com.xxx.yyy.controller包下所有的controller(控制器)并注册进spring容器, 同时扫描扫com.xxx.yyy.common包下所有的资源类并注册进spring容器,多个包时,各个包之间用逗号隔开,也可分开写 参考:http://www.cnblogs.com/xdp-gacl/p/3495887.html --> <context:component-scan base-package="com.xxx.yyy.controller,com.xxx.yyy.validator"/> <context:component-scan base-package="com.xxx.ttt.common,com.ttt.yyy.common"/> <!-- 主要作用于@Controller,激活该模式,下面是一种简写形式,完全可以手动配置替代这种简写形式, 它会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter, 是spring MVC为@Controllers分发请求所必须的 --> <!-- <mvc:annotation-driven /> --> <!-- 为controller中方法返回client的字符进行进行UTF-8编码 参见: http://www.cnblogs.com/zemliu/p/3497025.html --> <!-- filter 中已经做处理,这里可以省 --> <!-- <bean id="utf8Charset" class="java.nio.charset.Charset" factory-method="forName"> <constructor-arg value="UTF-8"/> </bean> --> <!-- 前面 annotation-driven 没有加载,这里再显示加载,并列出需要的类 --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="cacheSeconds" value="0"></property> <property name="messageConverters"> <list> <!-- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> --> <!-- 负责读取和写入json格式的数据,本此在MyEclipse应该使用的jar版本不同,冒似不成功 --> <!-- 没有这个Bean那控制器中以JSON返回将出问题,在控制器内完成Bean到JSON的转换,然后以String返回到Client --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value><!-- test ok --> </list> </property> <!-- <constructor-arg ref="utf8Charset"/> --> <!-- 指定返回的字符编码: (why不成功) 返回字符编码设置参见:http://www.cnblogs.com/zemliu/p/3497025.html --> </bean> <!-- 负责读取字符串格式的数据和写出二进制格式的数据 --> <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/> <!-- 负责读取资源文件和写出资源文件数据 --> </list> </property> </bean> <!-- 更多参见: http://luanxiyuan.iteye.com/blog/1849169 --> <!-- 配置JS,CSS,Image等静态文件直接映射到对应的文件夹,不需被DispatcherServlet处理 --> <mvc:resources location="/resource/" mapping="/resource/**" /> <mvc:resources location="/chkcode/" mapping="/chkcode/**" /> <mvc:resources location="/news/" mapping="/news/**" /> <mvc:resources location="/appnews/" mapping="/appnews/**" /> <!-- 自定义的一些访问路径直接映射到对应视图,不经过controller --> <!-- <mvc:view-controller path="/login" view-name="/login" /> <mvc:view-controller path="/logout" view-name="/" /> --> <!-- session 解析区域,并设置默认的语言区域 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"> <property name="defaultLocale" value="zh_CN"/> </bean> <!-- 上面是locale转换成真正的Locale对象,然后将对象保存在Session中,比较好; 下面是基于请求头信息和Cookie方式的国际化 --> <!-- <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/> --> <!-- 链接请求式i18n国际化、网址拦截器 --> <!-- 拦截请求参数 locale=zh_CN|en_US 参考:http://chinaxxren.iteye.com/blog/794899 http://xph.iteye.com/blog/1695199 http://chinaxxren.iteye.com/blog/794899 --> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="locale"/> <!--locale为用户设置的语言参数名称,如果不指定property元素则默认为locale --> </bean> <!-- 这里可以增加含有某些功能的用户自定义的拦截器 --> <!-- start: set server to client cache --> <!-- <mvc:interceptor> <mvc:mapping path="/*"/> <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor"> <property name="cacheSeconds" value="0"/> <property name="useExpiresHeader" value="true"/> <!- - <property name="useCacheControllerHeader" value="true"/> <property name="useCacheControllerNoStore" value="false"/> - -> <property name="cacheMappings"> <props> <prop key="/xPath/yPath/**">180</prop> </props> </property> </bean> </mvc:interceptor> --> <!-- end: set server to client cache --> <!-- 用户自定义拦截/过滤器 --> <!-- <mvc:interceptor> <mvc:mapping path="/xPath/yPath/*"/> <mvc:mapping path="/xPath/kPath/*"/> <mvc:mapping path=""/> 可定义多个拦截(/过滤)路径,可正则匹配路径模式,也可匹配具体某路径 <mvc:exclude-mapping path="/xPath/yPath/zPath"></mvc:exclude-mapping> 某个路径排出在外,不用经过拦截/过滤器,但好像本版本不支持mvc:exclude-mapping元素 自定义拦截器写法参考com.xxx.yyy.interceptor.UserDefineInterceptor <bean id="userInterceptor" class="com.xxx.yyy.interceptor.UserDefineInterceptor"></bean> </mvc:interceptor> --> </mvc:interceptors> <!-- 为了使用国际化信息源,Spring MVC 必须实现MessageSource接口。 我们需要做的是注册一个MessageSource类型的Bean。 Bean的名称必须为messageSource,从而方便DispatcherServlet自动检测它。 每个DispatcherServlet只能注册一个信息源的Bean,但该Bean中可列出需要的多个资源文件的基本名称, 比如全名为Label_en_US.properties的文件,只用列出基本名Label即可 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="defaultEncoding" value="UTF-8" /> <property name="cacheSeconds" value="0" /> <property name="basenames"> <list> <value>classpath:config/properties/Labels</value> <value>classpath:config/properties/Messages</value> </list> </property> </bean> <!-- Application Message Bundle 国际化信息源另一写法 ,仅单个资源文件 --> <!-- <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:/config/properties/messages" /> <property name="cacheSeconds" value="0" /> </bean> --> <!-- Spring负责处理上传问题的Bean,只有一个name为maxUploadSize的property子元素来设置最大上传大小问题 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"> <!-- <property name="maxUploadSize" value="2097160" /> --> </bean> <!--maxUploadSize:2MB=2*1024*1024=2097152--> <!-- 这里为全局上传大小定义;上传文件大小也可放到Controller中进行更灵活限制和管理 --> <!-- - Spring关于的错处处理方式 - This bean resolves specific types of exceptions to corresponding logical - view names for error views. The default behaviour of DispatcherServlet - is to propagate all exceptions to the servlet container: this will happen - here with all other types of exceptions. --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="error/error" /> <property name="exceptionMappings"> <props> <!-- exceptionMappings 异常处理映射prop,key="异常名称",value=异常处理视图 当试图是放在被MVC过滤的路径下时,如果设置了试图的前后缀值了,则只提供试图的前面的基本名,如404; 开发阶段用于查看/处理错误信息,当结束开发时候启用如下错误处理 --> <prop key="org.springframework.web.servlet.PageNotFound">error/404</prop> <prop key="org.springframework.web.DataAccessException">error/500</prop> <prop key="org.springframework.transaction.TransactionException">error/500</prop> <prop key="java.lang.Exception">error/error</prop> </props> </property> </bean> <!-- Spring关于JSTL视图的处理Bean --> <bean name="veiwPrefixSuffix" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
这比较综合的例子,在myEclipse环境实验中运行OK,因myEclipse和Eclipse有些不同,以及所引入的 jar 不完全相同,以及新旧版本不同,在搭建是注意考虑这些小问题;
知识有限可能有部分错漏问题,欢迎指出和拍砖讨论...