Springmvc基础及应用


SpringMVC简介和环境搭建

SpringMVC简介 

       Spring 为展现层提供的基于 MVC 设计理念的优秀的Web 框架,是目前最主流的 MVC 框架之一。在Spring3.0 后全面超越 Struts2,成为最优秀的 MVC 框架,通过一套 MVC 注解,让 POJO 成为处理请求的控制器,而无须实现任何接口。支持 REST 风格的 URL 请求。采用了松散耦合可插拔组件结构,比其他 MVC 框架更具扩展性和灵活性。

与Struts2比较

  • springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过虑器。
  • springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。
  • Struts采用值栈存储请求和响应的数据,通过OGNL存取数据,springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过reques域传输到页面。Jsp视图解析器默认使用jstl。

SpringMVC环境搭建

  •  web.xml配置

<servlet>
  <servlet-name>springMvcservlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
  
  <init-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:SpringMvc.xmlparam-value>
  init-param>
  
  <load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
  <servlet-name>springMvcservlet-name>
  
  <url-pattern>*.actionurl-pattern>
servlet-mapping>


<filter>
  <filter-name>encodingFilterfilter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
  <init-param>
    <param-name>encodingparam-name>
    <param-value>UTF-8param-value>
  init-param>
  
  <init-param>
    <param-name>forceEncodingparam-name>
    <param-value>trueparam-value>
  init-param>
filter>

<filter-mapping>
  <filter-name>encodingFilterfilter-name>
  <url-pattern>/*url-pattern>
filter-mapping>
  • Spring-mvc.xml配置

<mvc:annotation-driven/>

<context:component-scan base-package=“com.yuan.test” />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />


<bean name="/test1/multi" class="com.yuan.test.MultiController">
  <property name="methodNameResolver">
    <ref bean="paramMethodResolver"/>
  property>
bean>

<bean id="paramMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
  <property name="paramName" value="a">property>
bean>
访问url:http://localhost:8080/test/multi?a=methodName


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding" value="utf-8" />
  <property name="maxUploadSize" value="100000" />
  <property name="maxInMemorySize" value="960" />
bean>

<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
    
    <property name="order" value="100">property>
bean>


<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="i18n">property>    
bean>


<mvc:view-controller path="/success" view-name="success"/>

SpringMVC架构流程

  • 用户发送请求至前端控制器DispatcherServlet
  • DispatcherServlet收到请求调用HandlerMapping处理器映射器。
  • 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
  • DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
  • 执行处理器(Controller,也叫后端控制器)。
  • Controller执行完成返回ModelAndView
  • HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
  • DispatcherServlet将ModelAndView传给ViewReslover视图解析器
  • ViewReslover解析后返回具体View
  • DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
  • DispatcherServlet响应用户

SpringMVC组件说明

  • DispatcherServlet:前端控制器

用户请求到达前端控制器,它就相当于mvc模式中的c,dispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet的存在降低了组件之间的耦合性。

  • HandlerMapping:处理器映射器

HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式@RequestMaping等。

  • Handler:处理器

Handler 是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。
由于Handler涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发Handler。

  • HandlAdapter:处理器适配器

通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行,如对标记@ResquestMapping的方法进行适配。

  • View Resolver:视图解析器

View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。

  • View:视图

springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

springmvc web项目在idea中配置

  • 配置Project Structure

 

  •  配置Tomcat

Springmvc示例 

文件上传示例

/**上传单个文件*/
public String uploadOne(@RequestParam("file") CommonsMultipartFile file) throws IOException{
  if(!file.isEmpty()){
    try {
      /**将文件存入D盘并重新命名*/
      FileOutputStream fileOutputStream = new FileOutputStream("D:/" + new Date().getTime() + file.getOriginalFilename());
      InputStream inputStream = file.getInputStream();
      int byte = 0;
      while((byte=inputStream.read()) != -1){
        fileOutputStream.write(byte);
      }
      fileOutputStream.flush();
      fileOutputStream.close();
      inputStream.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  return "/success";
}
/**一次性上传多个文件*/
public String uploadMore(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
  CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
  if(multipartResolver.isMultipart(request)){
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
    Iterator iter = multiRequest.getFileNames();
    while(iter.hasNext()){
      MultipartFile file = multiRequest.getFile((String)iter.next());
      if(file != null){
        String fileName = "upload" + file.getOriginalFilename();
        String path = "D:/" + fileName;
        File localFile = new File(path);
        file.transferTo(localFile);
      }
    }
  }
  return "/success";
}

与其他框架集成

与Spring集成

web.xml中添加
<listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath*:config/spring-*.xmlparam-value> context-param>

与Hibernate集成

<beans>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.MySQL"/>
        <property name="url" value="jdbc:XXXXXXX"/>
        <property name="username" value=""/>
        <property name="password" value=""/>
    bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialectprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop> 
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hiberante.format_sql">trueprop>
            props>
        property>
        <property name="configLocations">
            <list>
                <value>
                    classpath*:com/yuan/web/controller/hibernate/hibernate.cfg.test.xml
                value>
            list>
        property>
    bean>
    
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory">property>
    bean>
    
    <bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
        <property name="transactionManager" ref="transactionManager">property>
        <property name="transactionAttributes">
            <props>
                <prop key="add*">PROPAGATION_REQUIRED,-Exceptionprop>
                <prop key="update*">PROPAGATION_REQUIRED,-Exceptionprop>
                <prop key="insert*">PROPAGATION_REQUIRED,-Exceptionprop>
                <prop key="modify*">PROPAGATION_REQUIRED,-Exceptionprop>
                <prop key="delete*">PROPAGATION_REQUIRED,-Exceptionprop>
                <prop key="get*">PROPAGATION_NEVERprop>
            props>
        property>
    bean>

    <bean id="userDao" class="com.yuan.web.controller.dao.UserDAO">
        <property name="sessionFactory" ref="sessionFactory">property>
    bean>

    <bean id="userManagerBase" class="com.yuan.web.controller.service.UserManager">
        <property name="userDao" ref="userDao">property>
    bean>

    <bean id="userManager" parent="transactionBase">
        <property name="target" ref="userManagerBase">property>
    bean>

beans>

 与mybatis集成

sqlMapConfig.xml

<?xmlversion="1.0"encoding="UTF-8"?>
DOCTYPEconfiguration
PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
configuration>

applicationcontext-dao.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    
    <context:property-placeholderlocation="classpath:db.properties"/>
    
    <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <propertyname="driverClassName"value="${jdbc.driver}"/>
        <propertyname="url"value="${jdbc.url}"/>
        <propertyname="username"value="${jdbc.username}"/>
        <propertyname="password"value="${jdbc.password}"/>
        <propertyname="maxActive"value="10"/>
        <propertyname="maxIdle"value="5"/>
    bean>
    
    
    <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <propertyname="dataSource"ref="dataSource"/>
        
        <propertyname="configLocation"value="classpath:mybatis/SqlMapConfig.xml"/>
    bean>
    
    <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <propertyname="basePackage"value="cn.itcast.springmvc.mapper"/>
    bean>

beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

applicationcontext-service.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <context:component-scanbase-package="com.yuan.springmvc.service"/>

beans>

applicationcontext-transaction.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    
    <beanid="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <propertyname="dataSource"ref="dataSource"/>
    bean>
    
    <tx:adviceid="txAdvice"transaction-manager="transactionManager">
        <tx:attributes>
            
            <tx:methodname="save*"propagation="REQUIRED"/>
            <tx:methodname="insert*"propagation="REQUIRED"/>
            <tx:methodname="delete*"propagation="REQUIRED"/>
            <tx:methodname="update*"propagation="REQUIRED"/>
            <tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>
            <tx:methodname="get*"propagation="SUPPORTS"read-only="true"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:advisoradvice-ref="txAdvice"
            pointcut="execution(* com.yuan.springmvc.service.*.*(..))"/>
    aop:config>
beans>