spring配置文件相关


SpringMVC(15):  http://www.cnblogs.com/liukemng/p/3750117.html

org.springframework.web.servlet.view.velocity(springVelocity 配置)
:http://www.boyunjian.com/javadoc/org.springframework/spring-webmvc/3.2.3.RELEASE/_/org/springframework/web/servlet/view/velocity/VelocityViewResolver.html
【Spring MVC 环境 搭建
【总结】SpringMVC环境搭建其实非常简单,就三步:第一步,导入jar包。第二步,修改web.xml配置。第三步,增加对应的xml.利用百度、google搜索关键字【Spring MVC 环境 搭建】找到的大部分网上的文章都是正确的。出现问题,无非是少jar包,url-pattern路径配置不正确,servlet编译后的XXXX.class路径不对。

web.xml中webAppRootKey

------------------------------------------------------------------------------------------------
1、 web.xml配置
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param>
"webapp.root"这个字符串可以随便写任何字符串。如果不配置默认值是"webapp.root"。
 
可以用System.getProperty("webapp.root")来动态获项目的运行路径。
一般返回结果例如:/usr/local/tomcat6/webapps/项目名
作用:该元素用来声明应用范围(整个WEB项目)内的上下文初始化参数。
param-name 设定上下文的参数名称。必须是唯一名称
param-value 设定的参数名称的值
初始化过程:
1.在启动Web项目时,容器(比如Tomcat)会读web.xml配置文件中的两个节点<listener>和<contex-param>。
2.接着容器会创建一个ServletContext(上下文),应用范围内即整个WEB项目都能使用这个上下文。
3.接着容器会将读取到<context-param>转化为键值对,并交给ServletContext。
4.容器创建<listener></listener>中的类实例,即创建监听(备注:listener定义的类可以是自定义的类但必须需要继承ServletContextListener)。
5.在 监听的类中会有一个contextInitialized(ServletContextEvent event)初始化方法,在这个方法中可以通过 event.getServletContext().getInitParameter("contextConfigLocation") 来得到context-param 设定的值。在这个类中还必须有一个contextDestroyed(ServletContextEvent event) 销毁方法.用于关闭应用前释放资源,比如说数据库连接的关闭。
6.得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早。
由上面的初始化过程可知容器对于web.xml的加载过程是context-param >> listener? >>?fileter? >> servlet
如何使用
1.页面中
${initParam.contextConfigLocation}
2.
3.Servlet中
String paramValue=getServletContext().getInitParameter("contextConfigLocation")

文件开头作用

这个文件中,有以下内容:
<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: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-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
            default-lazy-init="true">
含义:
首先xml文档有格式,而为了spring的配置文件增加的节点能满足要求,合法,所以必须引入校验该xml的格式文件。那么上面你列出来的就是为了格式文件的地址。一个一个地给你解释:
第一个xmlns是关于初始化bean的格式文件地址。
第二个xmlns也是辅助初始化bean.
第三个是关于切面编程。
第四个是关于spring上下文,包括加载资源文件


2、解决以下报错

部署在同一容器中的Web项目,要配置不同的<param-value>,不能重复,否则报类似下面的错误:
Web app root system property already set to different value: 'webapp.root' = [/home/user/tomcat/webapps/project1/] instead of [/home/user/tomcat/webapps/project2/] - Choose unique values for the 'webAppRootKey' context-param in your web.xml files!
意思是“webapp.root”这个key已经指向了项目1,不可以再指向项目2.

3、加载方式

Spring通过org.springframework.web.util.WebAppRootListener 这个监听器来运行时的项目路径。
但是如果在web.xml中已经配置了 org.springframework.web.util.Log4jConfigListener这个监听器,
则不需要配置WebAppRootListener了。因为Log4jConfigListener已经包含了WebAppRootListener的功能
一般配置类型下面的例子:
Xml代码  收藏代码

    <!-- 加载Log4J 配置文件  -->  
    <context-param>  
        <param-name>log4jConfigLocation</param-name>  
        <param-value>WEB-INF/conf/log4j.properties</param-value>  
    </context-param>     
      
    <context-param>  
        <param-name>log4jRefreshInterval</param-name>  
          <param-value>3000</param-value>  
     </context-param>  
      
    <listener>  
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
     </listener>  



 <aop:aspectj-autoproxy proxy-target-class="true" />

 通过配置织入@Aspectj切面

虽然可以通过编程的方式织入切面,但是一般情况下,我们还是使用spring的配置自动完成创建代理织入切面的工作。

通过aop命名空间的<aop:aspectj-autoproxy/>声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring

在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy/>隐藏起来了

<aop:aspectj-autoproxy/>有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。


之前我的做法是用一个filter,在filter的init中调用String root = servletContext.getRealPath("/");,然后再去设置对应一个常量类文件的属性。做法差不多,但是spring的做法更可以借鉴!

org.springframework.web.context.ContextLoaderListener
1、用法
ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了 ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。至于 ApplicationContext.xml这个配置文件部署在哪,如何配置多个xml文件,书上都没怎么详细说明。现在的方法就是查看它的API文 档。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完 成。看看它的API说明
  第一段说明ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。如果查看ContextLoaderServlet的API,可以看到它也关联了ContextLoader这个类而且它实现了HttpServlet。这个接口
  第二段,ContextLoader创建的是 XmlWebApplicationContext这样一个类,它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->BeanFactory这样一来spring中的所有bean都由这个类来创建
  第三段,讲如何部署applicationContext的xml文件,如果在web.xml中不写任何参数配置信息,默认的路径是”/WEB-INF /applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。 如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:
??
?contextConfigLocation?
? ?
? /WEB-INF/classes/applicationContext-*.xml?
? ?
?
  在里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。上面的applicationContext-*.xml采用通配 符,比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext- action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。
  由此可见applicationContext.xml的文件位置就可以有两种默认实现:
  第一种:直接将之放到/WEB-INF下,之在web.xml中声明一个listener、
  第二种:将之放到classpath下,但是此时要在web.xml中加入,用它来指明你的applicationContext.xml的位置以供web容器来加载。按照 Struts2 整合spring的官方给出的档案,写成:
  ? ?
?
contextConfigLocation?
/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml?
  
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring/root-config.xml
        </param-value>
      </context-param>




spring/root-config.xml里的内容:

<context:component-scan base-package="com.banksteel">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
先写一个小例子,剩下的在下面解释
<!-- 定义扫描根路径为leot.test,不使用默认的扫描方式 -->
<context:component-scan base-package="leot.test" use-default-filters="false">
??<!-- 扫描符合@Service @Repository的类 -->
??<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
??<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>
?
下面是引用spring framework开发手册中的一段话“
Spring 2.5引入了更多典型化注解(stereotype annotations):?@Component、@Service和?@Controller。@Component是所有受Spring管理组件的通用形式;而@Repository、@Service和?@Controller则是@Component的细化,用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。也就是说,你能用@Component来注解你的组件类,但如果用@Repository、@Service?或@Controller来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。例如,这些典型化注解可以成为理想的切入点目标。当然,在Spring Framework以后的版本中,?@Repository、@Service和?@Controller也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用@Component还是@Service,那@Service显然是更好的选择。同样的,就像前面说的那样,?@Repository已经能在持久化层中进行异常转换时被作为标记使用了。”
?<aop:aspectj-autoproxy proxy-target-class="true" />

http://kld208.iteye.com/blog/1632935
<aop:aspectj-autoproxy
/>有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy?
poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。


<context:property-placeholder location="classpath:spring/dubbo.properties" />
http://blog.csdn.net/superdog007/article/details/41825355
spring中context:property-placeholder/元素
?
1.有些参数在某些阶段中是常量
??? 比如:a、在开发阶段我们连接数据库时的连接url,username,password,driverClass等?
???????????????? b、分布式应用中client端访问server端所用的server地址,port,service等??
????????????????? c、配置文件的位置
2.而这些参数在不同阶段之间又往往需要改变
??? 比如:在项目开发阶段和交付阶段数据库的连接信息往往是不同的,分布式应用也是同样的情况。
期望:能不能有一种解决方案可以方便我们在一个阶段内不需要频繁书写一个参数的值,而在不同阶段间又可以方便的切换参数配置信息
解决:spring3中提供了一种简便的方式就是context:property-placeholder/元素
只需要在spring的配置文件里添加一句:<context:property-placeholder?location="classpath:jdbc.properties"/>?即可,这里location值为参数配置文件的位置,参数配置文件通常放在src目录下,而参数配置文件的格式跟java通用的参数配置文件相同,即键值对的形式,例如:
#jdbc配置
test.jdbc.driverClassName=com.mysql.jdbc.Driver
test.jdbc.url=jdbc:mysql://localhost:3306/test
test.jdbc.username=root
test.jdbc.password=root
行内#号后面部分为注释
应用:
1.这样一来就可以为spring配置的bean的属性设置值了,比如spring有一个jdbc数据源的类DriverManagerDataSource
在配置文件里这么定义bean:
<bean id="testDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
??? <property name="driverClassName" value="${test.jdbc.driverClassName}"/>
??? <property name="url" value="${test.jdbc.url}"/>
??? <property name="username" value="${test.jdbc.username}"/>
??? <property name="password" value="${test.jdbc.password}"/>
</bean>

2.甚至可以将${ }这种形式的变量用在spring提供的注解当中,为注解的属性提供值
  --------------------------------------------------------- ?
  外在化应用参数的配置
  在开发企业应用期间,或者在将企业应用部署到生产环境时,应用依赖的很多参数信息往往需要调整,比如LDAP连接、RDBMS JDBC连接信息。对这类信息进行外在化管理显得格外重要。PropertyPlaceholderConfigurer和PropertyOverrideConfigurer对象,它们正是担负着外在化配置应用参数的重任。
? <context:property-placeholder/>元素
  PropertyPlaceholderConfigurer实现了BeanFactoryPostProcessor接口,它能够对<bean/>中的属性值进行外在化管理。开发者可以提供单独的属性文件来管理相关属性。比如,存在如下属性文件,摘自userinfo.properties。
db.username=scott
db.password=tiger
  如下内容摘自propertyplaceholderconfigurer.xml。正常情况下,在userInfo的定义中不会出现${db.username}、${db.password}等类似信息,这里采用PropertyPlaceholderConfigurer管理username和password属性的取值。DI容器实例化userInfo前,PropertyPlaceholderConfigurer 会修改userInfo的元数据信息(<bean/>定义),它会用userinfo.properties中db.username对应的 scott值替换${db.username}、db.password对应的tiger值替换${db.password}。最终,DI容器在实例化 userInfo时,UserInfo便会得到新的属性值,而不是${db.username}、${db.password}等类似信息。
  ?
  代码示例1:
[html] view plaincopy
1.<bean?id="propertyPlaceholderConfigurer"?class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
9.<bean?name="userInfo"?class="test.UserInfo">
10.<property?name="username"?value="${db.username}"/>
11.<property?name="password"?value="${db.password}"/>
12.</bean>
  通过运行并分析PropertyPlaceholderConfigurerDemo示例应用,开发者能够深入理解PropertyPlaceholderConfigurer。为简化PropertyPlaceholderConfigurer的使用,Spring提供了<context:property-placeholder/>元素。下面给出了配置示例,启用它后,开发者便不用配置PropertyPlaceholderConfigurer对象了。
  <context:property-placeholder?location="userinfo.properties"/>
  或<context:property-placeholder location="classpath:application.properties" />
  ?

  PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM 系统属性(System.getProperty())和环境变量(System.getenv())中寻找。通过启用 systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。


错误信息配置:

<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>message</value>
            </list>
        </property>
    </bean>
地址:http://blog.csdn.net/qyf_5445/article/details/8124431
当一个ApplicationContext被加载时,它会自动在context中查找已定义为MessageSource类型的bean。此bean的名称须为messageSource。如果找到,那么所有对上述方法的调用将被委托给该bean。否则ApplicationContext会在其父类中查找是否含有同名的bean。如果有,就把它作为MessageSource。如果它最终没有找到任何的消息源,一个空的StaticMessageSource将会被实例化,使它能够接受上述方法的调用。
Spring目前提供了两个MessageSource的实现:ResourceBundleMessageSource和StaticMessageSource。它们都继承NestingMessageSource以便能够处理嵌套的消息。StaticMessageSource很少被使用,但能以编程的方式向消息源添加消息。ResourceBundleMessageSource会用得更多一些,为此提供了一下示例:
<beans>
  <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
      <list>
        <value>format</value>
        <value>exceptions</value>
        <value>windows</value>
      </list>
    </property>
  </bean>
</beans>
这段配置假定在你的classpath中有三个资源文件(resource bundle),它们是format, exceptions和windows。通过ResourceBundle,使用JDK中解析消息的标准方式,来处理任何解析消息的请求。出于示例的目的,假定上面的两个资源文件的内容为…
# in 'format.properties'
message=Alligators rock!
# in 'exceptions.properties'
argument.required=The '{0}' argument is required.

http://m.blog.csdn.net/blog/rainyear/20150553




 <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:spring/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
  
  http://jinnianshilongnian.iteye.com/blog/1602617
3.1、DispatcherServlet作用
DispatcherServlet是前端控制器设计模式的实现,提供Spring Web MVC的集中访问点,而且负责职责的分派,而且与Spring IoC容器无缝集成,从而可以获得Spring的所有好处。?具体请参考第二章的图2-1。
?
DispatcherServlet主要用作职责调度工作,本身主要用于控制流程,主要职责如下:
1、文件上传解析,如果请求类型是multipart将通过MultipartResolver进行文件上传解析;
2、通过HandlerMapping,将请求映射到处理器(返回一个HandlerExecutionChain,它包括一个处理器、多个HandlerInterceptor拦截器);
3、通过HandlerAdapter支持多种类型的处理器(HandlerExecutionChain中的处理器);
4、通过ViewResolver解析逻辑视图名到具体视图实现;
5、本地化解析;
6、渲染具体的视图等;
7、如果执行过程中遇到异常将交给HandlerExceptionResolver来解析。
?
从以上我们可以看出DispatcherServlet主要负责流程的控制(而且在流程中的每个关键点都是很容易扩展的)。
?
3.2、DispatcherServlet在web.xml中的配置
    <servlet>
        <servlet-name>chapter2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>chapter2</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
?
load-on-startup:表示启动容器时初始化该Servlet;
url-pattern:表示哪些请求交给Spring Web MVC处理,?“/”?是用来定义默认servlet映射的。也可以如“*.html”表示拦截所有以html为扩展名的请求。
?
该DispatcherServlet默认使用WebApplicationContext作为上下文,Spring默认配置文件为“/WEB-INF/[servlet名字]-servlet.xml”。
?

DispatcherServlet也可以配置自己的初始化参数,覆盖默认配置:摘自Spring Reference



Spring MVC 学习笔记

参考资料spring官方网站 http://www.springframework.org/spring api http://www.springframework.org/docs/api/index.htmlspring reference documentation http://www.springframework.org/docs/reference/index.htmlspring framework 开发参考手册(中文版)http://www.jactiongroup.net/reference/html/index.html

1.重要的接口和类

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.1 DispatcherServlet ------ 前置控制器

      

使用Spring MVC,配置DispatcherServlet是第一步;

DispatcherServlet是一个servlet,所以可以配置多个DispatcherServlet;

DispatcherServlet是前置控制器,配置在web.xml文件中;

拦截匹配规则要自己定义,DispatcherServlet会把拦截下的请求,依据某某规则分发到目标Controller来处理(某某规则根据你使用HandlerMapping接口实现类的不同而不同).

配置文件举例(web.xml):

<web-app>

<servlet>

<servlet-name>spring3</servlet-name><!--可以有多个,根据名字区分>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1<load-on-startup> 

</servlet>

<servlet-mapping>

<servlet-name>spring3</servlet-name>

<url-pattern>*.jsp</url-pattern>

</servlet-mapping>

</web-app>

DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[servlet-name]-servlet.xml 的配置文件,生成文件中定义的bean

关于<load-on-startup>:

1)load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法)

2)它的值必须是一个整数,表示servlet应该被载入的顺序

3)当值为0或者大于0时,表示容器在应用启动时就加载并初始化这个servlet

4)当值小于0或者没有指定时,则表示容器在该servlet被选择时才会去加载。

5)正数的值越小,该servlet的优先级越高,应用启动时就越先加载。当值相同时,容器就会自己选择顺序来加载。所以,<load-on-startup>x</load-on-startup>,中x的取值12345代表的是优先级,而非启动延迟时间。

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.2 HandlerMapping接口 ------ 处理请求的映射

       

HandlerMapping的实现类:

          (1)SimpleUrlHandlerMapping ------ 通过配置文件,Url映射到controller类上;

          (2)DefaultAnnotationHandlerMapping ------ 通过注解,Url映射到controller类上;

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.3 HandlerAdapter接口 ------ 处理请求的映射

       

HandlerAdapter的实现类:

         (1)AnnotationMethodHandlerMapping ------ 通过注解,Url映射到controller类的方法上

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.4 HandlerInterceptor接口 ------ 拦截器(自己实现)

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.5 ViewResolver接口 ------ 视图解析器(根据controller中返回的view名关联到具体的View

ViewResolver的实现类:

(1)UrlBasedViewResolver:通过配置文件,把一个视图名交给到一个View处理

(2)比上面的类,加入了JSTL的支持

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.6 View

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.7 LocalResolver接口

            

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

1.8 HandlerExceptionResolver接口 ------ 异常处理

    

SimpleMappingExceptionResolver

1.9 ModelAndview

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

2.核心流程图

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

MVC设计模式:

Model(模型):数据模型,提供要展示的数据,因此包含数据和行为,可以认为是领域模型或JavaBean组件(包含数据和行为),不过现在一般都分离开来:Value Object(数据) 和 服务层(行为)。也就是模型提供了模型数据查询和模型数据的状态更新等功能,包括数据和业务。

View(视图):负责进行模型的展示,一般就是我们见到的用户界面,客户想看到的东西。

Controller(控制器):接收用户请求,委托给模型进行处理(状态改变),处理完毕后把返回的模型数据返回给视图,由视图负责展示。 也就是说控制器做了个调度员的工作。

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

3.[servlet-name]-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:tx="http://www.springframework.org/schema/tx"  

    xmlns:context="http://www.springframework.org/schema/context"    

    xmlns:mvc="http://www.springframework.org/schema/mvc"    

    xsi:schemaLocation="http://www.springframework.org/schema/beans   

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   

10     http://www.springframework.org/schema/tx   

11     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  

12     http://www.springframework.org/schema/context  

13     http://www.springframework.org/schema/context/spring-context-3.0.xsd  

14     http://www.springframework.org/schema/mvc  

15     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  

16 <!--引入properties文件-->

17  <context:property-placeholder location="jdbc.properties"/>

18 <!--自动扫描的包名-->

19 <context:component-scan base-package="包名"/>

20 <!--支持注解映射-->

21 <mvc:annotation-driven/>

22 <!--数据源的配置-->  

23 <bean id="**DataSource" class="com.alibaba.druid.pool.DruidDataSource"   init-method="init" destroy-method="close">

24     <property name="driverClassName">

25          <value>${mysteel.dataSource.driverClassName}</value>

26     </property>

27    <property name="url">巧合而已,恩,那你是什么方向的,需求?

28          <value>${mysteel.dataSource.url}</value>

29    </property>

30    <property name="userName">

31          <value>${mysteel.dataSource.userName}</value>

32    </property>

33    <property name="password">

34          <value>${mysteel.dataSource.password}</value>

35    </property>

36    <property name="initialSize">

37          <value>${mysteel.dataSource.initialSize}</value>

38    </property>

39    <property name="maxActive">

40          <value>${mysteel.dataSource.maxActive}</value>

41    </property>

42    <property name="minIdle">

43          <value>${mysteel.dataSource.minIdle}</value>

44    </property>

45    <property name="testOnBorrow">

46          <value>${mysteel.dataSource.testOnBorrow}</value>

47    </property>

48    <property name="testWhileIdle">

49          <value>${mysteel.dataSource.testWhileIdle}</value>

50    </property>

51    <property name="validationQuery">

52          <value>${mysteel.dataSource.validationQuery}</value>

53    </property>

54 

55 <!--引入velocity模板引擎-->

56 <bean id="velocityConfigure"

57          class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"/>

58    <property name="resourceLoaderPath">

59        <value>/WEB-INF/views</value>

60    </property>

61    <property name="velocityProperties">

62       <props>

63            <prop key="input.encoding">gbk</prop>

64            <prop key="output.encoding">gbk</prop>

65       </props>

66     <property>

67 </bean>

68 <!--velocity视图解析器-->

69 <bean id="viewResolver" 

70      class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">

71    <property name="suffix"><value>.vm</value><property>

72 

73    <property name="contentType">

74            <value>text/html;charset=UTF-8</value>

75    </property>

76    

77    <property name="exposeSessionAttributes">

78         <value>true</value>

79    <property>

80 

81    <property name="exposeRequwstAttributes">

82         <value>true</value>

83    </property>

84 

85    <property name="viewClass">

86         <value>

87          org.springframework.web.servlet.view.velocity.VelocityToolboxView

88         </value>

89    <property>

90 

91 </bean>

92 <!-- 对静态资源文件的访问  方案一 (二选一) -->

93 <mvc:default-servlet-handler/> <!--使用默认的servlet来响应静态文件-->

94 <!-- 对静态资源文件的访问  方案二 (二选一)-->

95 <mvc:resources mapping="/skin/images/**" location="/skin/images/"/>

96 <mvc:resources mapping="/skin/js/**" location="/skin/js"/>

97 <mvc:resources mapping="/skin/css/**" location="/skin/css"/>

98 <!--总错误处理-->

99 <bean id="exceptionResolver"      class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

100       <property name="defaultErrorView">

101              <value>exception</value>

102       </property>

103       <property name="defaultStatusCode">

104              <value>500</value>

105       </property>

106       <property name="warnLogCategory">

107              <value>

108            org.springframwork.web.servlet.handler.SimpleMappingExceptionResolver

109              </value>

110       </property>

111 </bean>

112 <!--mybatis配置-->

113 < bean id="**SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean "  autowire="byName">

114      <property name="mapperLocation">

115           <value>classpath*:xml的位置</value>

116      </property>

117      <property name="dataSource" ref="**DataSource"></property>

118 </bean>

119 <!--MapperScannerConfigurer配置-->

120 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

121 <!--basePackage指定要扫描的包,在此包之下的映射器都会被搜索到.可指定多个包,包与包之间用逗号或分号分隔-->

122    <property name="basePackage"><value>**.dao</value></property>

123    <property name="sqlSessionFactoryBeanName"><vlaue>**SqlFactory</value></property>

124 </bean>

125 </beans>

 配置文件相关说明:

(1) <content:component-scan base-package="包名">扫描指定包中类中的注解,常用的注解有:

@Controller 声明Action组件

@Service 声明Service组件,格式@Service("接口名:小写")

@Repository 声明Dao组件,可以不写,格式同@Service

@Component 泛指组件,当不好归类时

@RequestMapping 请求映射,格式@RequestMapping(value="url")

@Resource 用于注入,(J2EE提供)按名称装配,格式@Resource(name="BeanName")

@Autowired 用于注入,(Spring提供)按类型装配

 

(2) <mvc:annotation-driven/>是一种简写形式,会自动注册DefaultAnnotationHandlerMappingAnnotationMethodHandlerAdapter两个Bean

(3) 数据源的配置及原理另作说明

org.springframework.context.ApplicationContextAware使用理解

(一)org.springframework.context.ApplicationContextAware是一个接口,此接口作用如下:

当一个类实现此接口之后,这个类就可以方便获得ApplicationContext中的所有bean,即这个类可以直接获取spring配置文件中,所有有引用到的bean对象.

(二)用法:

例如我有一个方法类AppUtil,这个方法类中需要使用到的ApplicationContext中的某个beancompanyService)。

1、因为spring要建立属于自己的容器,就必须要加载自己的配置文件。

     这个时候,需要注册ContextLoaderListener或者这个类的子类。

web.xml加上以下的信息:

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

当然,这样子的话只会读取默认路径下的application.xml配置文件的。如果需要读取特定路径下的配置文件。需要在web.xml

添加如下信息。可以参考我的示例,指定配置文件,如下:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:conf/app-context.xml</param-value>
 </context-param>

注意:<param-name>contextConfigLocation</param-name>是不能改变的。

2、方法类AppUtil的处理

方法类AppUtil实现ApplicationContextAware接口:

public class AppUtil
  implements ApplicationContextAware

为方法类AppUtil增加一个静态的成员ApplicationContext类型的对象。以后方法类AppUtil获取ApplicationContext,就是通过读取这个

成员变量的。具体如下所示:

private static ApplicationContext appContext;

实现ApplicationContextAware接口的默认方法:

 public void setApplicationContext(ApplicationContext paramApplicationContext)
    throws BeansException
  {
    appContext = paramApplicationContext;
  }

3、在spring的配置文件中,注册方法类AppUtil

严格上来说,方法类AppUtil是一个bean,而且从步骤2中我们不难发现,之所以方法类AppUtil能够灵活自如地获取ApplicationContext

就是因为spring能够为我们自动地执行了setApplicationContext。但是,spring不会无缘无故地为某个类执行它的方法的,所以,就很有必要

通过注册方法类AppUtil的方式告知spring有这样子一个类的存在。

其实,方法很简单,就是将方法类AppUtil作为一个普通的beanspring的配置文件中进行注册:

<bean id="appUtil" class="com.htsoft.core.util.AppUtil"/>

4、使用静态的成员ApplicationContext类型的对象,appContext,来调用其他bean。在方法类AppUtil中增加如下方法:

public static Object getBean(String paramString)
  {
    return appContext.getBean(paramString);
  }

那么,在方法类AppUtil中就能够灵活地调用其他任何一个bean了,例如:

CompanyService localCompanyService = (CompanyService)getBean("companyService");

注:配置文件中关于companyService的内容:

<bean id="companyService" class="com.kaiwii.service.system.impl.CompanyServiceImpl">
        <constructor-arg index="0" ref="companyDao"/>      
</bean>

关于SpringApplicationContext的说明

一、简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例(对象).可以用:

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
RegisterDAO registerDAO = (RegisterDAO)ac.getBean("RegisterDAO");

如果是两个以上:
ApplicationContext ac = new ClassPathXmlApplicationContext

(new String[]{"applicationContext.xml","dao.xml"});

或者用通配符:
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/*.xml");


二、ClassPathXmlApplicationContext[只能放在WEB-INF/classes目录下的配置文件]FileSystemXmlApplicationContext的区别


classpath:前缀是不需要的,默认就是指项目的classpath路径下面;
如果要使用绝对路径,需要加上file:前缀表示这是绝对路径;

对于FileSystemXmlApplicationContext:
默认表示的是两种:

1.没有盘符的是项目工作路径,即项目的根目录;
2.有盘符表示的是文件绝对路径.

如果要使用classpath路径,需要前缀classpath:

public class HelloClient {

protected static final Log log = LogFactory.getLog(HelloClient.class);

public static void main(String[] args) {
// Resource resource = new ClassPathResource("appcontext.xml");
// BeanFactory factory = new XmlBeanFactory(resource);

// classpath路径
// ApplicationContext factory = new     ClassPathXmlApplicationContext("classpath:appcontext.xml");
  //ApplicationContext factory=new 

                    ClassPathXmlApplicationContext("appcontext.xml");

        // ClassPathXmlApplicationContext使用了file前缀是可以使用绝对路径的
        //ApplicationContext factory=new     ClassPathXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml");

// 用文件系统的路径,默认指项目的根路径
// ApplicationContext factory = new FileSystemXmlApplicationContext("src/appcontext.xml");
// ApplicationContext factory=new  FileSystemXmlApplicationContext("webRoot/WEB-INF/appcontext.xml");

// 使用了classpath:前缀,这样,FileSystemXmlApplicationContext也能够读取classpath下的相对路径
//ApplicationContext factory=new

FileSystemXmlApplicationContext("classpath:appcontext.xml");

//ApplicationContext factory=new  FileSystemXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml");

// 不加file前缀
ApplicationContext factory=new  FileSystemXmlApplicationContext("F:/workspace/example/src/appcontext.xml");

IHelloWorld hw = (IHelloWorld)factory.getBean("helloworldbean");
log.info(hw.getContent("luoshifei"));
}
}

 

注解:

1. @ResponseBody

作用: 

      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如jsonxml等)使用;


contextClass    实现WebApplicationContext接口的类,当前的servlet用它来创建上下文。如果这个参数没有指定, 默认使用XmlWebApplicationContext。
contextConfigLocation    传给上下文实例(由contextClass指定)的字符串,用来指定上下文的位置。这个字符串可以被分成多个字符串(使用逗号作为分隔符) 来支持多个上下文(在多上下文的情况下,如果同一个bean被定义两次,后面一个优先)。
namespace    WebApplicationContext命名空间。默认值是[server-name]-servlet。
?
因此我们可以通过添加初始化参数
?
    <servlet>
        <servlet-name>chapter2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet-config.xml</param-value>
        </init-param>
    </servlet>

如果使用如上配置,Spring Web MVC框架将加载“classpath:spring-servlet-config.xml”来进行初始化上下文而不是“/WEB-INF/[servlet名字]-servlet.xml”。
spring-servlet-config.xml:
<bean id="contentNegotiationManager"
          class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="favorPathExtension" value="false"/>
        <property name="favorParameter" value="true"/>
        <property name="mediaTypes">
            <value>
                json=application/json
                xml=application/xml
            </value>
        </property>
  </bean>
  
  http://www.cnblogs.com/zemliu/p/3369476.html
  
  
SpringMVC中使用Interceptor拦截器顺序等
  
  http://blog.csdn.net/ufo2910628/article/details/24423413

  
  
关于<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />3个属性的说明(可以都不设置而用其默认值):

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <!-- 设置cookieName名称,可以根据名称通过js来修改设置,也可以像上面演示的那样修改设置,默认的名称为 类名+LOCALE(即:org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE-->
    <property name="cookieName" value="lang"/>
    <!-- 设置最大有效时间,如果是-1,则不存储,浏览器关闭后即失效,默认为Integer.MAX_INT-->
    <property name="cookieMaxAge" value="100000">
    <!-- 设置cookie可见的地址,默认是“/”即对网站所有地址都是可见的,如果设为其它地址,则只有该地址或其后的地址才可见-->
    <property name="cookiePath" value="/"></bean>

猜你喜欢

转载自blog.csdn.net/jakeswang/article/details/50577516