SpringMVC+Mybatis+Maven+Bonecp+IDEA

来源:互联网 发布:一个暑假变漂亮知乎 编辑:程序博客网 时间:2024/06/06 18:32

springmvc整合mybaits

源代码下载:http://download.csdn.net/detail/paincupid/9141975
git://code.csdn.net/paincupid/springmvc.git
https://gitee.com/paincupid/simple-springmvc

1/ 本文工具:Idea,Maven; spring4.2.0.RELEASE; mybatis3.2.2; 数据库链接池使用Bonecp

idea的pom.xml和eclipse的配置不同,否则会报
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/] in DispatcherServlet with name ‘appServlet’

之类的错误,原因是:

在打包 war 包的时候,普通情况下只会打包src/main/resources下面的资源文件,在开发过程中我们也会把需要的配置文件放在这个目录下。但是有些情况下会和 java文件放在同一个目录下,比如 hibernate 的映射文件 .hbm.xml,还有 mybatis 的 **mapper.xml文件,一般情况都会和对应的 *VO.java 放在同一个目录下。这样利用maven打包时,就需要修改pom.xml文件,来把mapper.xml文件一起打包进jar或者war里了,否则,这些文件不会被打包的。(maven认为src/main/java只是java的源代码路径)。

2/ 工程结构图

3/ pom.xml

<?xml version="1.0" encoding="UTF-8"?><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.paincupid</groupId>    <artifactId>springmvc</artifactId>    <name>springmvc</name>    <packaging>war</packaging>    <version>1.0.0-BUILD-SNAPSHOT</version>    <properties>        <java-version>1.6</java-version>        <org.springframework-version>4.2.0.RELEASE</org.springframework-version>        <org.aspectj-version>1.6.10</org.aspectj-version>        <org.slf4j-version>1.6.6</org.slf4j-version>    </properties>    <dependencies>        <!-- Spring -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${org.springframework-version}</version>            <exclusions>                <!-- Exclude Commons Logging in favor of SLF4j -->                <exclusion>                    <groupId>commons-logging</groupId>                    <artifactId>commons-logging</artifactId>                </exclusion>            </exclusions>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>${org.springframework-version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>${org.springframework-version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-test</artifactId>            <version>${org.springframework-version}</version>            <scope>test</scope>        </dependency>        <!-- AspectJ -->        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjrt</artifactId>            <version>${org.aspectj-version}</version>        </dependency>        <!-- Logging -->        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-api</artifactId>            <version>${org.slf4j-version}</version>        </dependency>        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>jcl-over-slf4j</artifactId>            <version>${org.slf4j-version}</version>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-log4j12</artifactId>            <version>${org.slf4j-version}</version>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.15</version>            <exclusions>                <exclusion>                    <groupId>javax.mail</groupId>                    <artifactId>mail</artifactId>                </exclusion>                <exclusion>                    <groupId>javax.jms</groupId>                    <artifactId>jms</artifactId>                </exclusion>                <exclusion>                    <groupId>com.sun.jdmk</groupId>                    <artifactId>jmxtools</artifactId>                </exclusion>                <exclusion>                    <groupId>com.sun.jmx</groupId>                    <artifactId>jmxri</artifactId>                </exclusion>            </exclusions>            <scope>runtime</scope>        </dependency>        <!-- @Inject -->        <dependency>            <groupId>javax.inject</groupId>            <artifactId>javax.inject</artifactId>            <version>1</version>        </dependency>        <!-- Servlet -->        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>servlet-api</artifactId>            <version>2.5</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>javax.servlet.jsp</groupId>            <artifactId>jsp-api</artifactId>            <version>2.1</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>jstl</artifactId>            <version>1.2</version>        </dependency>        <!-- 数据库oracle & 链接池bonecp -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.30</version>        </dependency>        <dependency>            <groupId>com.jolbox</groupId>            <artifactId>bonecp</artifactId>            <version>0.8.0.RELEASE</version>        </dependency>        <!-- 事务配置依赖的包 -->        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>            <version>1.7.3</version>        </dependency>        <dependency>            <groupId>aopalliance</groupId>            <artifactId>aopalliance</artifactId>            <version>1.0</version>        </dependency>        <dependency>            <groupId>cglib</groupId>            <artifactId>cglib-nodep</artifactId>            <version>3.0</version>        </dependency>        <!-- mybatis -->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.2.2</version>        </dependency>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId>            <version>1.2.0</version>        </dependency>        <!-- 文件上传 -->        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.3</version>        </dependency>        <dependency>            <groupId>commons-io</groupId>            <artifactId>commons-io</artifactId>            <version>2.4</version>        </dependency>        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>            <version>1.1.5</version>        </dependency>        <!-- Test -->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.7</version>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <resources>            <resource>                <directory>src/main/resources</directory>                <includes>                    <include>**/*.properties</include>                    <include>**/*.xml</include>                </includes>                <filtering>false</filtering>            </resource>            <resource>                <directory>src/main/java</directory>                <includes>                    <include>**/*.properties</include>                    <include>**/*.xml</include>                </includes>                <filtering>false</filtering>            </resource>        </resources>        <plugins>            <plugin>                <groupId>org.apache.maven.plugins</groupId>                <artifactId>maven-resources-plugin</artifactId>                <version>2.6</version>                <configuration>                    <encoding>UTF-8</encoding>                </configuration>            </plugin>            <plugin>                <groupId>org.apache.maven.plugins</groupId>                <artifactId>maven-compiler-plugin</artifactId>                <version>2.5.1</version>                <configuration>                    <source>1.6</source>                    <target>1.6</target>                    <compilerArgument>-Xlint:all</compilerArgument>                    <showWarnings>true</showWarnings>                    <showDeprecation>true</showDeprecation>                </configuration>            </plugin>            <plugin>                <groupId>org.codehaus.mojo</groupId>                <artifactId>exec-maven-plugin</artifactId>                <version>1.2.1</version>                <configuration>                    <mainClass>org.test.int1.Main</mainClass>                </configuration>            </plugin>            <plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.4</version>                <dependencies>                    <dependency>                        <groupId>mysql</groupId>                        <artifactId>mysql-connector-java</artifactId>                        <version>5.1.34</version>                    </dependency>                </dependencies>                <configuration>                    <verbose>true</verbose>                    <overwrite>true</overwrite>                </configuration>            </plugin>            <!-- eclipse配置 -->            <!--<plugin>                <artifactId>maven-eclipse-plugin</artifactId>                <version>2.9</version>                <configuration>                    <additionalProjectnatures>                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>                    </additionalProjectnatures>                    <additionalBuildcommands>                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>                    </additionalBuildcommands>                    <downloadSources>true</downloadSources>                    <downloadJavadocs>true</downloadJavadocs>                </configuration>            </plugin>-->        </plugins>    </build></project>

4/ 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">    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->    <context-param>        <param-name>log4jConfigLocation</param-name>        <param-value>/WEB-INF/log4j.xml</param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>    </listener>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/spring/applicationContext.xml</param-value>    </context-param>    <!-- Creates the Spring Container shared by all Servlets and Filters -->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!-- Processes application requests -->    <servlet>        <servlet-name>appServlet</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>appServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>

5/ applicationContext.xml

<?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:jee="http://www.springframework.org/schema/jee"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:util="http://www.springframework.org/schema/util"       xmlns:aop= "http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans                    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd                    http://www.springframework.org/schema/tx                    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd                    http://www.springframework.org/schema/jee                    http://www.springframework.org/schema/jee/spring-jee-3.1.xsd                    http://www.springframework.org/schema/context                    http://www.springframework.org/schema/context/spring-context-3.1.xsd                    http://www.springframework.org/schema/util                    http://www.springframework.org/schema/util/spring-util-3.1.xsd                    http://www.springframework.org/schema/aop                    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd" default-lazy-init="true">    <!-- 扫描service、dao组件 -->    <context:component-scan base-package="com.paincupid.springmvc.service,com.paincupid.springmvc.persistence" />    <!-- 分解配置 jdbc.properites -->    <!--    <context:property-placeholder location="classpath:jdbc.properties" />     -->    <!-- 数据源BoneCP -->    <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">          <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />          <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl" />          <property name="username" value="lee"/>          <property name="password" value="eee"/>          <property name="idleConnectionTestPeriod" value="60"/>          <property name="idleMaxAge" value="240"/>          <property name="maxConnectionsPerPartition" value="30"/>          <property name="minConnectionsPerPartition" value="10"/>          <property name="partitionCount" value="1"/>          <property name="acquireIncrement" value="5"/>          <property name="statementsCacheSize" value="100"/>          <property name="releaseHelperThreads" value="3"/>     </bean>    <!-- sessionFactory 将spring和mybatis整合 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="typeAliasesPackage" value="com.paincupid.springmvc.domain" />    </bean>    <!-- 注册Mapper方式二:也可不指定特定mapper,而使用自动扫描包的方式来注册各种Mapper ,配置如下:-->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="com.paincupid.*.persistence" />    </bean>    <!-- 事务 -->    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" scope="singleton">        <property name="dataSource" ref="dataSource"></property>    </bean>    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="get*" read-only="true" />            <tx:method name="select*" read-only="true" />            <tx:method name ="add*"  isolation= "READ_COMMITTED" rollback-for= "Exception"/>            <tx:method name ="update*"  isolation= "READ_COMMITTED" rollback-for= "Exception"/>            <tx:method name ="delete*"  isolation= "READ_COMMITTED" rollback-for= "Exception"/>        </tx:attributes>    </tx:advice>    <!-- 在service层实现事务控制 -->    <aop:config>        <aop:pointcut expression="execution(* com.paincupid.springmvc.service.*.*(..))"            id="pointCut" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut" />    </aop:config></beans>

6/ servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/mvc"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:beans="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"         default-autowire="byName">    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->    <!-- Enables the Spring MVC @Controller programming model -->    <annotation-driven />    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->    <resources mapping="/resources/**" location="/resources/" />    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <beans:property name="prefix" value="/WEB-INF/views/" />        <beans:property name="suffix" value=".jsp" />    </beans:bean>    <context:component-scan base-package="com.paincupid.springmvc" />    <!-- 支持文件上传 -->    <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    </beans:bean></beans:beans>

7/ PersonController

package com.paincupid.springmvc.controller;import java.util.List;import java.util.UUID;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.mvc.support.RedirectAttributes;import com.paincupid.springmvc.domain.Person;import com.paincupid.springmvc.service.PersonService;@Controller( "personController")@RequestMapping( "/person")public   class  PersonController{    @Autowired    PersonService personService;    @RequestMapping( "/list")      public  String listPerson(Person person, Model model){        List<Person> personList   =  personService.listPerson(person);        model.addAttribute( "personList", personList);        return   "listperson";    }}

8/ PersonService

package com.paincupid.springmvc.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.paincupid.springmvc.domain.Person;import com.paincupid.springmvc.persistence.PersonMapper;@Service(value =  "personService")public class PersonService {    @Autowired    private PersonMapper mapper;    public List<Person> listPerson(Person persion){        List<Person> list = mapper.listPerson(persion);        return list;    }}

9/ PersonMapper.java

package com.paincupid.springmvc.persistence;import java.util.List;import com.paincupid.springmvc.domain.Person;public interface PersonMapper {    List<Person> listPerson(Person persion);}

10/ PersonMapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" ><mapper namespace="com.paincupid.springmvc.persistence.PersonMapper" >    <select id="listPerson" resultType="com.paincupid.springmvc.domain.Person" parameterType="com.paincupid.springmvc.domain.Person">        select t.empid id,t.name from EMPLOYEE t    </select></mapper>

12/ Person.java

package com.paincupid.springmvc.domain;public class Person {    private String id;    private String name;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

13/ listperson.jsp

<%@ page language="java" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><html><head><title>My JSP 'index.jsp' starting page</title><script type="text/javascript"></script></head><body>    <P>The time on the server is ${serverTime}.</P>    <h2>用户列表</h2>    <form name="form1"  id="form1">        <table border="1">            <tr>                <td>name</td>                <td>password</td>            </tr>            <c:forEach items="${personList}" var="row">            <tr>                <td align="center">${row.id}</td>                <td align="center">${row.name}</td>            </tr>            </c:forEach>        </table>    </form></body></html>

14/ 最终效果

访问链接:http://localhost:8080/springmvc/person/list
或者:http://localhost:8080/person/list

15/ 源代码下载:http://download.csdn.net/detail/paincupid/9141975

git://code.csdn.net/paincupid/springmvc.git

https://gitee.com/paincupid/simple-springmvc

解决org.springframework.web.servlet.PageNotFound的方法:
在pom.xml中加入:

<build>        <finalName>paincupid</finalName>        <resources>            <resource>                <directory>src/main/resources</directory>                <includes>                    <include>**/*.properties</include>                    <include>**/*.xml</include>                </includes>                <filtering>false</filtering>            </resource>            <resource>                <directory>src/main/java</directory>                <includes>                    <include>**/*.properties</include>                    <include>**/*.xml</include>                </includes>                <filtering>false</filtering>            </resource>        </resources></build>

或者:利用build-helper-maven-plugin插件

<plugs>   <!--        此plugin可以用        利用此plugin,把源代码中的xml文件,        打包到相应位置,这里主要是为了打包Mybatis的mapper.xml文件        -->            <plugin>                <groupId>org.codehaus.mojo</groupId>                <artifactId>build-helper-maven-plugin</artifactId>                <version>1.8</version>                <executions>                    <execution>                        <id>add-resource</id>                        <phase>generate-resources</phase>                        <goals>                            <goal>add-resource</goal>                        </goals>                        <configuration>                            <resources>                                <resource>                                    <directory>src/main/java</directory>                                    <includes>                                        <include>**/*.xml</include>                                    </includes>                                </resource>                            </resources>                        </configuration>                    </execution>                </executions>            </plugin><plugs>

再或者使用:利用maven-resources-plugin插件

xml
<plugins>
<!--
此plugin可以用
利用此plugin,把源代码中的xml文件,打包到相应位置,
这里主要是为了打包Mybatis的mapper.xml文件
-->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-xmls</id>
<phase>process-sources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
#

转载请注明出处:http://blog.csdn.net/paincupid/article/details/78453848