`

Spring配置

 
阅读更多
1、web.xml文件 
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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_2_5.xsd"
	version="2.5">
	<display-name>notepad</display-name>
	<!-- 默认页面 -->
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>
	<!-- servlet上下文初始化参数 -->
	<!-- applicationContext.xml -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<!-- 启动容器就会加载此处配置的配置文件 第一种写法,配置文件放在src/main/resources下 第二种写法,配置文件放在/WEB-INF/conf/spring下,个人倾向第二种 -->
		<!-- <param-value>classpath:applicationContext.xml</param-value> -->
		<param-value>/WEB-INF/conf/spring/applicationContext.xml</param-value>
	</context-param>
	<!-- log4j.properties -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/conf/log/log4j.properties</param-value>
	</context-param>

	<!-- listener -->
	<!-- log4j监听器 应放在spring监听器之前,因为spring也会加载log4j.properties,放在后面会抛出两个警告 -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- filter -->
	<!-- 字符过滤器 -->
	<filter>
		<filter-name>characterEncodingFilter</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-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- servlet -->
	<!-- springMVC的servlet,加载/WEB-INF/conf/spring/springMVC-config.xml文件,启动springMVC 如果没有contextConfigLocation参数,则在/WEB_INF下去找springMVC-servlet.xml文件 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- <param-value></param-value> -->
			<param-value>/WEB-INF/conf/spring/springMVC-config.xml</param-value>
		</init-param>
		<!-- 值大于等于0表示容器启动应用时候加载该servlet,数值越小优先级越高 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>  

 

2、applicationContext.xml文件 
 
<?xml version="1.0" encoding="UTF-8"?>
<!-- xmlns 声明默认的命名空间 xmlns:context 声明context命名空间 xmlns:p 声明p命名空间,用于简化spring配置文件中属性声明的写法 xmlns:mvc 声明mvc命名空间 
	xmlns:xsi 声明XML Schema实例名称空间,并将xsi前缀与该命名空间绑定 xsi:schemaLocation 引入Schema模式文档,解析器使用文档对xml进行校验,它的值是成对出现的, 
	第一个表示命名空间,第二个表示该命名空间模式文档位置,中间用空格隔开 如果抛出Failed to read schema document异常,是因为无法访问网址,需要在pom中添加相关依赖 -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 需要扫描的包,@Repository、@Service等 -->
	<context:component-scan base-package="com.cpkf.notpad">
		<!-- 启用了对类包进行扫描以实施注释驱动 Bean 定义的功能, 启用了注释驱动自动注入的功能,隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和 
			CommonAnnotationBeanPostProcessor,就可以将 <context:annotation-config/>移除了 -->
	</context:component-scan>
	<!-- 引入别的配置文件 -->
	<!-- 引入springI18n-config.xml -->
	<import resource="springI18n-config.xml" />
	<!-- 引入springHibernate-config.xml -->
	<import resource="springHibernate-config.xml" />
</beans> 

 

3、springMVC-config.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<!-- springMVC配置 -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-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">
	<!-- 对指定包中所有类进行扫描,完成bean的创建和自动依赖注入功能 -->
	<context:component-scan base-package="com.cpkf.notpad.controller"></context:component-scan>
	<!-- 启动springMVC注解功能,完成请求和注解POJO的映射 mvc:annotation-driven代替了AnnotationMethodHandlerAdapter、DefaultAnnotationHandlerMapping单独注册 
		在WebApplicationContext中注册下面两个类 org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping 
		org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter 支持数据绑定过程中的类型转换服务 支持数字、日期、时间等数据的格式化 
		支持使用JSR-303的数据验证功能 支持XML和JSON的读写 -->
	<mvc:annotation-driven />
	<!-- 对模型视图名称进行解析,在模型视图名称上添加前后缀 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/webs/"
		p:suffix=".jsp"></bean>

	<!-- 这个default-servlet-handler 可以使用DispatcherServlet的url-pattern 是/*, 如果springmvc找不到handler来处理请求, 会自动放过,让serlvet 
		container处理 -->
	<mvc:default-servlet-handler />
	<!-- 该tag方便请求根view,这个view一般是静态的 -->
	<mvc:view-controller path="/about" view-name="ablot" />
	<!-- 这个tag是方便重定向路径 -->
	<mvc:resources location="/media/**" mapping="/media/" />
	<!-- json支持,依赖jackson-core-lgpl.jar、jackson-mapper-asl.jar、jackson-mapper-lgpl.jar -->
	<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
	<!-- 注解验证,依赖validation-api.jar,hibernate-validator.jar -->
	<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"></bean>
	<!-- file上传,依赖commons-fileupload.jar -->
	<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
	<!-- exception处理 -->
	<beans:bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
		p:defaultErrorView="common/error">
		<beans:property name="exceptionMappings">
			<beans:props>
				<beans:prop key="java.lang.RuntimeException">common/error</beans:prop>
			</beans:props>
		</beans:property>
	</beans:bean>
</beans> 
 
4、写登录实例
  编写login.jsp/main.jsp、编写loginController 
 
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

/**
 * Filename: LoginController.java Description: 登录控制层,以springMVC注解的方式实现 Company:
 * 
 * @author: Jiang.hu
 * @version: 1.0 Create at: May 6, 2011 2:14:20 PM modified:
 */
@Controller
public class LoginController {

    /*
     * @RequestMapping 方法的返回类型 ModelAndView Model A Map object for exposing a
     * model View String 指定view name void if the method handles the response
     * itself If the method is annotated with @ResponseBody,the return type is
     * written to the response HTTP body redirect, forward跳转 使用"redirect:"前缀,如
     * "redirect:/view" 相应地使用"forward:"前缀表示servlet内部跳转 Handling a file upload in
     * a form 使用@RequestParam("file") MultipartFile file获取上传的文件
     */
    @RequestMapping(value = "/login.do", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {

        String email = request.getParameter("email");
        String passWord = request.getParameter("passWord");
        String nowTime = DateUtil.dateFormat(new Date(),
                DateFormatConstants.DAY_MONTH_YEAR_HOUR_MIN_SEC);

        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("email", email);
        modelMap.put("passWord", passWord);
        modelMap.put("nowTime", nowTime);

        ModelMap modelMap2 = new ModelMap();
        modelMap2.addAttribute("email", email);
        modelMap2.addAttribute("passWord", passWord);
        modelMap2.addAttribute("nowTime", nowTime);

        /*
         * 返回ModelAndView对象,常见的几种方式 view-返回网页名称,在springMVC文件中已经配置了前缀和后缀
         * model数据可以直接用键值对,也可用hashmap、modelmap以及addobject的方式
         */
        // return new ModelAndView("index","nowTime",nowTime);
        // return new ModelAndView("index",modelMap);
        // return new ModelAndView("index",modelMap2);
        return new ModelAndView("index").addObject("email", email).addObject("passWord", passWord)
                .addObject("nowTime", nowTime);
    }
}
 
5、添加i18n支持
      在src/main/resources下创建messages文件夹,并创建messages.properties、messages_en.properties、messages_zh_CN.properties文件 
 
<?xml version="1.0" encoding="UTF-8"?>
<!-- 国际化配置 -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-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">
	<!-- 配置资源文件 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<!-- 国际化文件通用名 -->
				<value>messages/messages</value>
			</list>
		</property>
		<!-- JSP渲染器为JSTL支持的,JSP文件中可使用fmt标记 -->
		<property name="useCodeAsDefaultMessage" value="true"></property>
	</bean>
	<!-- 配置resolve 基于session org.springframework.web.servlet.i18n.SessionLocaleResolver 基于request org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver 
		基于cookieorg.springframework.web.servlet.i18n.CookieLocaleResolver -->
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
	</bean>
	<!-- 配置拦截器 -->
	<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
		<property name="paramName" value="lang"></property>
	</bean>
</beans> 
 
 6、添加log支持
       pom添加log4j包 
 
<dependency>  
    <groupId>log4j</groupId>  
    <artifactId>log4j</artifactId>  
    <version>1.2.16</version>  
    <scope>compile</scope>  
</dependency>  
<dependency>  
    <groupId>org.slf4j</groupId>  
    <artifactId>slf4j-api</artifactId>  
    <version>1.6.1</version>  
    <type>jar</type>  
    <scope>compile</scope>  
</dependency>  
<dependency>  
    <groupId>org.slf4j</groupId>  
    <artifactId>slf4j-log4j12</artifactId>  
    <version>1.6.1</version>  
    <type>jar</type>  
    <scope>compile</scope>  
</dependency> 
 
7、web.xml添加咯个配置
 
    <!-- log4j.properties -->
<context-param>
	<param-name>log4jConfigLocation</param-name>
	<param-value>/WEB-INF/conf/log/log4j.properties</param-value>
</context-param>
<!-- log4j监听器 应放在spring监听器之前,因为spring也会加载log4j.properties,放在后面会抛出两个警告 -->
<listener>
	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>  
 
8、log4j.properties配置
 
    #指定根logger,以及日志输出级别,大于该级别的日志被输出(DEBUG INFO WARN ERROR FATAL) OFF为关闭  
    #A1,A2为两个输出目的地  
    log4j.rootLogger=INFO,A1,A2  
      
    #指定A1为每日输出一个日志文件  
    log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender  
    #文件输出地址  
    #系统把web目录的路径压入一个叫webapp.root的系统变量  
    #log4j.appender.A1.File=${webapp.root}/WEB-INF/logs/myfuse.log  
    #相对路径,在tomcat中与webapps同级  
    log4j.appender.A1.File=../notepadLog/notepad.log  
    #设置文件编码格式  
    log4j.appender.A1.encoding=UTF-8  
    #新日志文件名在原有基础上加上日期  
    log4j.appender.A1.DatePattern='.'yyyyMMdd  
    #指定日志的布局格式  
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
    #设置格式参数  
    log4j.appender.A1.layout.ConversionPattern=%r %d{yyyy-MM-dd HH:mm:ss} %c %p -%m%n   
      
    #指定A2为控制台  
    log4j.appender.A2=org.apache.log4j.ConsoleAppender  
    log4j.appender.A2.encoding=UTF-8  
    log4j.appender.A2.layout=org.apache.log4j.PatternLayout  
    log4j.appender.A2.layout.ConversionPattern=[notepad] %r %d{yyyy-MM-dd HH:mm:ss} %c %p -%m%n  
 
9、java中使用Logger
      private static Logger logger = Logger.getLogger(LoginController.class);  
      ……  
      logger.info("******");
 
10、springHibernate-config.xml
 
    <?xml version="1.0" encoding="UTF-8"?>
<!-- hibernate配置 -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-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/aop   
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!-- 加载配置文件 -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>/WEB-INF/conf/db/jdbc-parms.properties</value>
				<value>/WEB-INF/conf/db/pool-parms.properties</value>
				<value>/WEB-INF/conf/db/hibernate-parms.properties</value>
			</list>
		</property>
	</bean>
	<!-- 配置c3p0数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<property name="acquireIncrement" value="${pool.acquireIncrement}" />
		<property name="initialPoolSize" value="${pool.initialPoolSize}" />
		<property name="minPoolSize" value="${pool.minPoolSize}" />
		<property name="maxPoolSize" value="${pool.maxPoolSize}" />
		<property name="autoCommitOnClose" value="${pool.autoCommitOnClose}" />
	</bean>
	<!-- hibernate的annotation会话管理,依赖hibernate、hibernate-annotations、persistence-api包 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- packagesToScan可以自动搜索某个package的全部标记@Entity class -->
		<property name="packagesToScan">
			<list>
				<value>com.cpkf.notpad.entity</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
			</props>
		</property>
	</bean>
	<!-- 引入hibernateTemplate -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
	<!-- 配置事务的传播特性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="upd*" propagation="REQUIRED" />
			<tx:method name="del*" propagation="REQUIRED" />
			<tx:method name="log*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!--给aop切面加入事务,依赖aspectjweaver.jar -->
	<aop:config>
		<aop:pointcut id="allServiceMethod" expression="execution(* com.cpkf.notpad.server.**.*(..))" />
		<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
	</aop:config>
</beans>  
 
11、加入applicationContext.xml文件 
    <!-- 引入springHibernate-config.xml -->  
    <import resource="springHibernate-config.xml"/>  
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics