Spring3.0.4 學習與問題總結系列 - 2 MVC

記得在3年前使用的是 Struct2 與Spring結合的框架開發。當時是用Structs2來進行MVC管理,使用Spring對BO與DAO的Bean管理。仍是一個新人的我,懵懂的作了3年。java

由於很長時間已經沒有接觸過這樣的框架了,目前我使用的所有都是SpringFrameWork,我不敢妄加評論,但我以爲一體化的方便與框架一致性,完整性帶來的好處使我用起來很爽。web

下面我就介紹一下Spring3的MVC架構與使用方法。(我會盡可能詳細的舉出各例,以及支持的場景,可是不保證全面)spring

Spring-3.0.4 MVC:spring-mvc

使用過Spring的人都應該知道,在SpringMVC中使用的是listener-class是
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>架構

使用的MVC中的C是mvc

 
<servlet>
   <servlet-name>SimpleServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>app

 

那麼在web.xml中的配置以下:框架

 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">jsp

    <!-- Reads request input using UTF-8 encoding -->
    <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>ide

    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-mvc/spring-mvc.xml, /WEB-INF/applicationContext/applicationContext.xml </param-value>
    </context-param>
   
    <!-- Handles all requests into the application -->
    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/spring/appServlet/servlet-context.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

 

(只是一個例子,沒什麼特殊的),跟通常的web application沒什麼兩樣。

來看看Spring-mvc.xml中的配置吧,這個纔是Spring3的重點:

 
<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    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/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <mvc:annotation-driven />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <context:component-scan base-package="com.*.*.*" />
 
    <!-- Application Message Bundle -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>/WEB-INF/messages/messages</value>
                <value>/WEB-INF/messages/expMessages</value>
                <value>/WEB-INF/messages/chartMessages</value>
            </list>
        </property>
        <property name="cacheSeconds" value="-1" />
    </bean>

</beans>

 

<mvc:annotation-driven />是作什麼用的呢? Configures the @Controller programming model

Spring會啓動Spring MVC的註解功能,完成請求和註解POJO的映射,並且自動使用Restful方式。

 

那麼<mvc:annotation-driven />是什麼的代替品呢?

 
<!-- Maps requests to @Controllers based on @RequestMapping("path") annotation values
If no annotation-based path mapping is found, Spring MVC sends a 404 response and logs a pageNotFound warning. -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="order" value="1" />
</bean>

<!-- REGISTERED HANDLER TYPES -->

<!-- Enables annotated @Controllers; responsible for invoking an annotated POJO @Controller when one is mapped. -->

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
   <!-- Configures Spring MVC DataBinder instances globally -->
   <property name="webBindingInitializer">
     <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
       <property name="conversionService" ref="conversionService" />
       <property name="validator" ref="validator" />
     </bean>
   </property>
</bean>

<!-- FIELD TYPE CONVERSION AND VALIDATION -->
<!-- Enables the Spring 3 Type Conversion system that uses Joda Time Formatting for Date/Time types -->
<bean id="conversionService" class="org.springframework.samples.petclinic.util.PetclinicConversionServiceFactory" />

<!-- Configures JSR-303 Declarative Validation with default provider on classpath (Hibernate Validator) -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

 

 

<context:component-scan base-package="com.*.*.*" /> 是對該配置路徑下面的類進行掃描並注入到springContainer中。像@Components @Controller @Service @Repository 這樣的類會被加到容器中。

至此Spring-MVC框架已成,咱們不須要再在xml文件中寫入大量的配置。

下面看看具體的Controller類吧:

@Controller
@RequestMapping(value="/account")
public class AccountController {

    private Map<Long, Account> accounts = new ConcurrentHashMap<Long, Account>();
   
    @RequestMapping(method=RequestMethod.GET)
    public String getCreateForm(Model model) {
        model.addAttribute(new Account());
        return "account/createForm";
    }
   
    @RequestMapping(method=RequestMethod.POST)
    public String create(@Valid Account account, BindingResult result) {
        if (result.hasErrors()) {
            return "account/createForm";
        }
        this.accounts.put(account.assignId(), account);
        return "redirect:/account/" + account.getId();
    }
   
    @RequestMapping(value="{id}", method=RequestMethod.GET)
    public String getView(@PathVariable Long id, Model model) {
        Account account = this.accounts.get(id);
        if (account == null) {
            throw new ResourceNotFoundException(id);
        }
        model.addAttribute(account);
        return "account/view";
    }

}
 看到了吧,Spring提供了RestFul方式,簡單的讓開發人員根本不用動腦了。

若是你想了解所有的信息,請去Spring官方網站,那裏應有盡有。

 

svn info https://src.springframework.org/svn/spring-samples/mvc-basic/trunk

相關文章
相關標籤/搜索