Spring3.0.4 学习与问题总结系列 - 2 MVC

记得在3年前使用的是 Struct2 与Spring结合的框架开发。当时是用Structs2来进行MVC管理,使用Spring对BO与DAO的Bean管理。还是一个新人的我,懵懂的做了3年。

因为很长时间已经没有接触过这样的框架了,目前我使用的全部都是SpringFrameWork,我不敢妄加评论,但我觉得一体化的方便与框架一致性,完整性带来的好处使我用起来很爽。

下面我就介绍一下Spring3的MVC架构与使用方法。(我会尽量详细的举出各例,以及支持的场景,但是不保证全面)

Spring-3.0.4 MVC:

使用过Spring的人都应该知道,在SpringMVC中使用的是listener-class是
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

使用的MVC中的C是

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

 

那么在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">

    <!-- 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>

    <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

你可能感兴趣的:(Spring3.0.4 学习与问题总结系列 - 2 MVC)