SpringMVC-DispatcherServlet配置(Spring-servlet.xml)


接上一篇:web.xml

 


Spring-servlet.xml

  1. <context:component-scan base-package="com.spring.mvc.controller"/>

    掃描指定的包中的類上的注解,常用的注解有:

    @Controller 聲明Action組件
    @Service    聲明Service組件    @Service("myMovieLister") 
    @Repository 聲明Dao組件
    @Component   泛指組件, 當不好歸類時. 
    @RequestMapping("/menu")  請求映射
    @Resource  用於注入,( j2ee提供的 ) 默認按名稱裝配,@Resource(name="beanName") 
    @Autowired 用於注入,(srping提供的) 默認按類型裝配 
    @Transactional( rollbackFor={Exception.class}) 事務管理
    @ResponseBody
    @Scope("prototype")   設定bean的作用域

  2. <mvc:annotation-driven /> 是一種簡寫形式,完全可以手動配置替代這種簡寫形式,簡寫形式可以讓初學都快速應用默認配置方案。<mvc:annotation-driven /> 會自動注冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC為@Controllers分發請求所必須的。
  3. 視圖解析類,使用普通bean的配置方式:
    1 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    2 <property name="prefix" value="/WEB-INF/views/"></property>
    3 <property name="suffix" value=".jsp"></property>
    4 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    5 </bean>
  4. 添加靜態資源訪問的支持:
    1 <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

    匹配URL  /resources/**  的URL被當做靜態資源,由Spring讀出到內存中再響應http。

    或直接使用默認的Servlet來響應靜態文件。

    <mvc:default-servlet-handler/>

示例:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context.xsd
12         http://www.springframework.org/schema/mvc
13         http://www.springframework.org/schema/mvc/spring-mvc.xsd">
14     <context:component-scan base-package="com.spring.mvc.controller"/>
15     <mvc:annotation-driven/>
16         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
17             <property name="prefix" value="/WEB-INF/views/"></property>
18             <property name="suffix" value=".jsp"></property>
19         </bean>
20     <!--添加訪問靜態資源的功能 -->
21  <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
22 </beans>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM