MAVEN+SPRINGMVC+SPRINGJDBC Build Web Project FAQ

Source: Internet
Author: User
Tags aop

MAVEN+SPRINGMVC+SPRINGJDBC Build Web Project FAQ
3.1WEB Project BASIC Structure
As specified in the Java EE specification, a typical Web application has four parts:
1. Public catalogue
2. web-inf/web.xml file, publish descriptor (required)
3. Web-inf/classes directory, compiled Java class file (optional)
4. Web-inf/lib directory, Java class library file (*.jar) (optional)
The classic structure:

Note: The application server refers to the Web-inf directory, that is, directly in the browser can not be directly accessed by the servlet access.
3.2web Project Startup Order
1. When starting a Web project, the Web container reads its configuration file Web.xml, reads, and two nodes.

2. Urgently, the container creates a ServletContext (servlet context) in which all parts of the Web project will share this context.

3, the container will be converted to the key value pairs, and handed to ServletContext.

4, the class instance in the container creation, creates the listener.

Web.xml loading order is: ServletContext-> context-param-> listener-> filter-> servlet
The order of the actual program calls between the same type is invoked according to the order of the corresponding mapping.

3.3Eclipse Create MAVEN Web project considerations
See Documentation: Eclipse Creation Mavenwebproject.doc
3.4MAVEN+SPRINGMVC+SPRINGJDBC Configuration
Key point: The contract is greater than the configuration
Key configuration: Web.xml application.xml spring-servlet.xml Pom.xml
3.4.1web.xml configuration (configuration file for Web container)
1. Configure Context-param

<!--applicationcontext Context-param start-->
<context-param>
    <param-name> Contextconfiglocation</param-name>
    <param-value>classpath:applicationcontext.xml</
context-param start--> of param-value> </context-param> <!--applicationcontext

Note: Once deployed to Tomcat, the configuration files in the SRC directory in eclipse will be automatically copy to the classes directory of the application, as in the class file, and of course this deploy path is configurable and defaults to the classes directory.
Classpath: will only go to your class path to find the file;
Classpath*: Includes not only the class path, but also the jar file (the class path) for lookup.
2. Configure Listener

  <!--applicationcontext Listener configuration  start-->
  <listener>
       <listener-class> org.springframework.web.context.contextloaderlistener</listener-class>
  </listener>
  <!-- ApplicationContext Listener Configuration Method  end-->

3. Configure Filter

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

4. Configure the Spring MVC Servlet

<!--springmvc  start-->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- Customize the configuration file name and path for spring MVC-->
    <init-param>
      <param-name>contextconfiglocation</param-name >
      <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
    <! --Custom boot order, let this servlet start with the servlet container-->
    <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 Configuration (core configuration file for spring)
With spring IOC, the corresponding bean is typically used in this file
For example, a JDBC-related 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 HT 
       Tp://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 HT Tp://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 "> <!--load jdbc configuration file--> <context:property-placeholder location=" Classpath:jdbc.properties "/&gt

    ;
    <!--scans the class pack, automatically converts the class that marks the spring annotation to the bean, and completes the bean injection--> <context:component-scan base-package= "Com.service"/> <context:component-scan base-package= "Com.dao"/> <!--configuration data source--> <bean id= "DataSource" com.
            Mchange.v2.c3p0.ComboPooledDataSource "destroy-method=" Close "> <property name=" Driverclass "> <value>${jdbc.driverClassName}</value> </property> <property name= "Jdbcurl" &G
            T <value>${jdbc.url}</value> </property> <property name= "user" > <valu e>${jdbc.username}</value> </property> <property name= "password" > <value >${jdbc.password}</value> </property> <!--the minimum number of connections retained in the connection pool.
        --> <property name= "minpoolsize" > <value>5</value> </property> <!--The maximum number of connections retained in the connection pool. Default:15--> <property name= "maxpoolsize" > <value>30</value> </prop Erty> <!--The number of connections obtained when initializing, the value should be between Minpoolsize and Maxpoolsize. Default:3--> <property name= "initialpoolsize" > <value>10</value> </p roperty> <!--maximum idle time, not used within 60 seconds, the connection is discarded. If 0, it will never be discarded. default:0--> <property name= "MaxIdleTime" > <value>60</value> </prope Rty> <!--The number of simultaneous connections c3p0 one at a time when connections in the connection pool are depleted. Default:3--> <property name= "Acquireincrement" > <value>5</value> </property> <!--JDBC Standard parameters to control the number of preparedstatements loaded in the data source. However, because the cached statements belong to a single connection instead of the entire connection pool. 
                                    So setting this parameter takes into account many factors. If both maxstatements and maxstatementsperconnection are 0, the cache is closed. default:0--> <property name= "maxstatements" > <value>0</value> </prop Erty> <!--check for free connections in all connection pools every 60 seconds.
        default:0--> <property name= "Idleconnectiontestperiod" > <value>60</value> </property> <!--defines the number of repeated attempts after a new connection has been fetched from the database.
        default:30--> <property name= "acquireretryattempts" > <value>30</value> </property> <!--getting a connection failure will cause all threads waiting to connect to get the connection to throw an exception. However, the data source remains valid and continues to attempt to get the connection the next time you call Getconnection (). If set to True, the data source will be declared disconnected and permanently closed after the attempt to acquire the connection fails. Default:false--> <property name= "Breakafteracquirefailure" > &LT;VALUE&GT;TRUE&LT;/value> </property> <!--because of the high performance, please use it only when you need it. If set to true then the validity is officers transferred Guevara for each connection submission. It is recommended that you use methods such as Idleconnectiontestperiod or automatictesttable to improve the performance of your connection tests. Default:false--> <property name= "Testconnectiononcheckout" > <value>false</value&gt
        ; </property> </bean> <!--configuring JDBC templates--> <bean id= "JdbcTemplate class=" org.springframework . jdbc.core.JdbcTemplate "> <property name=" dataSource "ref=" DataSource "></property> </bean&gt

    ; <!--provides support for LOB fields--> <bean id= "NativeJdbcExtractor class=" org.springframework.jdbc.support.nativejdb C.commonsdbcpnativejdbcextractor "lazy-init= true"/> <!--if the underlying database is DB2, SQL Server, MySQL, and other non-Oracle data Library, you simply configure a defaultlobhandler--> <bean id= "Lobhandler class=" Org.springframework.jdbc.support.lob.Defau Ltlobhandler "lazy-init=" true "/&GT <!--configuration transaction manager--> <bean id= "TransactionManager class=" Org.springframework.jdbc.datasource.DataSourceT 
   Ransactionmanager "p:datasource-ref=" DataSource/> <!--provides transactional enhancements through an AOP configuration, allowing all methods of all beans under the service bundle to have transactions--> <!--<aop:config proxy-target-class= "true" > <aop:pointcut id= "Servicemethod" express ion= "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 Configuration (Spring MVC configuration file)

<!--access to static resource files--> <mvc:resources mapping= "/resources/**" location= "/resources/"/> <!--View Resolution- -> <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <prop

    Erty name= "prefix" value= "/web-inf/views/"/> <property name= "suffix" value= ". jsp"/> </bean> <!--output object to JSON supports--> <bean id= "Jsonconverter class=" Org.springframework.http.converter.json. Mappingjackson2httpmessageconverter "></bean> <!--creates the JSR-303 Validator--> <bean I D= "Validator" class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> <!-- Invokes Spring MVC @Controller methods--> <bean class= "Org.springframework.web.servlet.mvc.annotation.Annotat Ionmethodhandleradapter "> <property name=" Webbindinginitializer "> <!--Configures Spri Ng MVC DataBinder Instances;  <bean class= "Org.springframework.web.bind.support.ConfigurableWebBindingInitializer" > <property Name= "Validator" ref= "validator"/> </bean> </property> <property na Me= "Messageconverters" > <list> <ref bean= "Jsonconverter"/> & Lt;/list> </property> </bean> <!--Configure a multipartresolver, where we use support Commons Fileuplo Commonsmultipartresolver of ad:--> <bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "p:defaultencoding=" Utf-8 "p:maxuploadsize=" 5000000 "/> <!--Global exception configuration start--> <bean id=" Exceptionresolver "class=" Org.springframework.web.ser     
             Vlet.handler.SimpleMappingExceptionResolver "> <property name=" exceptionmappings "> <props> <prop key= "com.exceptIon. Userexception ">errors/error</prop> <prop key=" Java.lang.Exception ">errors/error</prop&     
                 Gt <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> & Lt;/props> </property> <!--set the log output level, and do not define error log information such as warnings--> <p Roperty name= "Warnlogcategory" value= "WARN" ></property> <!--default error page, when the exception corresponding view specified in the mappings above is not found, use This default configuration--> <property name= "Defaulterrorview" value= "Errors/error" ></property> &L t;!   
     --Default HTTP status code--> <property name= "Defaultstatuscode" value= "></property>"</bean> <!--Global exception configuration end-->    

3.4.4pom.xml Configuration (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.vers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.