Maven+SpringMVC+SpringJDBC搭建web项目FAQ

Maven+SpringMVC+SpringJDBC搭建web项目FAQ
3.1Web项目基本结构
按照 Java EE 规范的规定,一个典型的Web 应用程序有四个部分:
1. 公开目录
2. WEB-INF/web.xml 文件,发布描述符(必选)
3. WEB-INF/classes 目录,编译后的Java 类文件(可选)
4. WEB-INF/lib 目录,Java 类库文件(*.jar)(可选)
经典的结构:
这里写图片描述

备注:应用服务器把WEB-INF指为禁访目录,即直接在浏览器里是不能直接访问的;可通过servlet访问。
3.2web项目启动顺序
1、启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取和两个结点。

2、紧急着,容器创建一个ServletContext(servlet上下文),这个web项目的所有部分都将共享这个上下文。

3、容器将转换为键值对,并交给servletContext。

4、容器创建中的类实例,创建监听器。

web.xml 的加载顺序是:ServletContext -> context-param -> listener -> filter -> servlet
而同个类型之间的实际程序调用的时候的顺序是根据对应mapping的顺序进行调用的。

3.3Eclipse创建Maven web项目注意事项
详见文档:eclipse创建MavenWebProject.doc
3.4maven+springMVC+springJDBC配置
关键点:约定大于配置
关键配置:web.xml application.xml spring-servlet.xml pom.xml
3.4.1web.xml配置 (web容器的配置文件)
1.配置Context-param

<!-- ApplicationContext 的Context-param start-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
<!-- ApplicationContext 的Context-param start-->

备注:部署到tomcat后,eclipse中的src目录下的配置文件会和class文件一样,自动copy到应用的 classes目录下,当然这个deploy path是可以配置的,默认为classes目录 。
classpath:只会到你的class路径中查找找文件;
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。
2.配置listener

  <!-- ApplicationContext 的Listener配置方式  start-->
  <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- ApplicationContext 的Listener配置方式  end-->

3.配置filter

 <!-- 过虑器 start --> 
  <filter>
    <filter-name>setcharacter</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>
  </filter>
  <filter-mapping>
    <filter-name>setcharacter</filter-name>
    <url-pattern>/</url-pattern>
  </filter-mapping>
  <!-- 过虑器 end-->

4.配置Spring MVC Servlet

 <!-- springmvc  start-->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 自定义spring mvc的配置文件名称和路径 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
    <!-- 自定义启动顺序,让这个Servlet随Servlet容器一起启动 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 
  <!-- springmvc  end-->

3.4.2 applicationContext.xml配置 (spring的核心配置文件)
使用Spring IOC ,相应的bean一般配在此文件中
例如JDBC相关的bean。

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

    <!-- 加载JDBC配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="com.service" />
    <context:component-scan base-package="com.dao" />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="jdbcUrl">
            <value>${jdbc.url}</value>
        </property>
        <property name="user">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
        <!--连接池中保留的最小连接数。 -->
        <property name="minPoolSize">
            <value>5</value>
        </property>
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize">
            <value>30</value>
        </property>
        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize">
            <value>10</value>
        </property>
        <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime">
            <value>60</value>
        </property>
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement">
            <value>5</value>
        </property>
        <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 
                                    如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
        <property name="maxStatements">
            <value>0</value>
        </property>
        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
        <property name="idleConnectionTestPeriod">
            <value>60</value>
        </property>
        <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
        <property name="acquireRetryAttempts">
            <value>30</value>
        </property>
        <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 
                                    获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
        <property name="breakAfterAcquireFailure">
            <value>true</value>
        </property>
        <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 
                                    等方法来提升连接测试的性能。Default: false -->
        <property name="testConnectionOnCheckout">
            <value>false</value>
        </property>
    </bean>

    <!-- 配置Jdbc模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 提供对lob字段的支持 -->
    <bean id="nativeJdbcExtractor"
        class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"
        lazy-init="true" />

    <!--如果底层数据库是 DB2、SQL Server、MySQL 等非 Oracle 的其它数据库,则只要简单配置一个 DefaultLobHandler-->
    <bean id="lobHandler"
        class="org.springframework.jdbc.support.lob.DefaultLobHandler"
        lazy-init="true" />

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource" />

    <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
   <!--  <aop:config proxy-target-class="true"> 
        <aop:pointcut id="serviceMethod"
            expression=" execution(* com.service..*(..))" />
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice> -->

</beans>

3.4.3 spring-servlet.xml 配置 (Spring MVC配置文件)

<!-- 对静态资源文件的访问  --> 
    <mvc:resources mapping="/resources/**" location="/resources/" />

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

    <!-- 输出对象转JSON支持 -->  
    <bean id="jsonConverter"  
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>  

    <!-- Creates the JSR-303 Validator -->  
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

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

        <property name="messageConverters">  
            <list>  
                <ref bean="jsonConverter" />  
            </list>  
        </property>  
    </bean> 

    <!-- 配置一个MultipartResolver,在这里我们使用支持Commons FileUpload的CommonsMultipartResolver:  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" p:maxUploadSize="5000000"/>

    <!-- 全局异常配置 start -->     
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">     
         <property name="exceptionMappings">     
             <props>     
                 <prop key="com.exception.UserException">errors/error</prop> 
                 <prop key="java.lang.Exception">errors/error</prop>     
                 <prop key="java.lang.Throwable">errors/err</prop>     
             </props>     
         </property>     
         <property name="statusCodes">     
             <props>     
                 <prop key="errors/error">500</prop>     
                 <prop key="errors/404">404</prop>     
             </props>     
         </property>     
         <!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息      -->
         <property name="warnLogCategory" value="WARN"></property>     
         <!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 -->     
         <property name="defaultErrorView" value="errors/error"></property>     
         <!-- 默认HTTP状态码    -->  
         <property name="defaultStatusCode" value="500"></property>   
     </bean>      
     <!-- 全局异常配置 end -->   

3.4.4pom.xml 配置 (maven )

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.typ.spring</groupId>
  <artifactId>maven-springmvc-springjdbc</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>maven-springmvc-springjdbc Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
       <spring.version>4.1.4.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.5</version>
    </dependency>

     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.35</version>
    </dependency>

    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5</version>
    </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

   <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.2.Final</version>
   </dependency>

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>


    <!-- json start-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.13</version>
    </dependency>

    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- json end-->

  </dependencies>
  <build>
    <finalName>maven-springmvc-springjdbc</finalName>

    <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
          <source>1.7</source>
          <target>1.7</target>
          </configuration>
      </plugin>
    </plugins>
  </build>
</project>

当然还有更详细的配置,请自行探索

下一章会把SpringMVC+SpringJDBC搭建的项目Demo传上来= }=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值