内容简介:基于Maven的Spring + Spring MVC + Mybatis的环境搭建项目开发,先将环境先搭建起来。上次做了一个Spring + Spring MVC + Mybatis + Log4J + JUnit Test的环境搭建,这次也差不多,不过就是基于了Maven,同时也添加了事务管理。首先,可以去了解一下maven,个人觉得这个东西就是JAR包管理方便,不用自己一个个去写,直接添加dependence就行了,不过有时候要注意哟,有可能重复的包含了某个JAR包,会报冲突的哟,亲!因为只有一个P
基于Maven的Spring + Spring MVC + Mybatis的环境搭建项目开发,先将环境先搭建起来。上次做了一个Spring + Spring MVC + Mybatis + Log4J + JUnit Test的环境搭建,这次也差不多,不过就是基于了Maven,同时也添加了事务管理。
首先,可以去了解一下maven,个人觉得这个东西就是JAR包管理方便,不用自己一个个去写,直接添加dependence就行了,不过有时候要注意哟,有可能重复的包含了某个JAR包,会报冲突的哟,亲!因为只有一个POM文件里指定JAR包,所以整个项目都很小的,一般就几MB,只有你在将该项目打成WAR包的时候,maven会自动的把三方JAR包放进项目,然后你就可以去部署到Tomcat的webapp下面了,放进去,重启Tomcat就OK。
1.开始搭建我的环境吧。首先,IDE我用的是eclipse的JEE版本。要保证装上了Maven哟,可以使用eclipse的Install New Software, URL地址是http://m2eclipse.sonatype.org/sites/m2e/, 然后一步步走下去,安装好了过了会重启一次。给一个忠告哟,安装好了maven后,不要使用IDE里面的了,而是去官方下载一个,解压,然后让IDE的Maven指向你下载安装的,如图:
2.maven安装成功了,我们用Maven创建一个新的WEB项目。File—> New—> Other—>Maven Project. 选默认,下一步。在Select an Archetype里面种找到如下图所示
3.然后next,输入groupId:net.yuanmomo;artifactId:Test,然后finish,稍微等待一下,就创建好了。下面的是创建好了的一个初始的项目:
4.但是这个并不是默认的maven项目的标准结构.我们需要进行一些改动. (1).在项目下创建一个Source Folder. Folder Name:src/main/java 如下图所示:
(当然,还可以添加用于junit测试的src/test/java和src/test/resources 不过在此就不添加了.) (2).在src/main/java中创建3个包(maven标准推荐是3层包结构) (3).如果装的JDK是1.6的,更改JRE System Libary为1.6版本的. (4).就src/main/webapp文件夹看做一个的WebRoot,然后创建js,css,jsp等文件夹。 这样.一个标准的maven web项目创建成功.
5.大家一看上面的项目结构,很熟悉吧。maven的项目结构路径有点讨厌,有点让人很烦。maven打WAR包的时候提取的东西是src/main/webapp下面的文件,然后打成一个WAR的WEB项目就可以部署了,但是,但是,我们在开发的时候,在使用eclipse里面的Tomcat调试的时候,tomcat却不是把src/main/webapp下面的文件部署到服务器。此时,如果你打开Server,然后add and remove,你在左边是找不到Test项目的,如下:
原因是因为Tomcat默认回去Test项目的路径下面去找WebRoot—>WEB-INF–>web.xml(WebRoot文件夹的名字可以不一样,可以使其它的,但是WEB-INF–>web.xml这两个名字不能变),但是当前就找不到这几个目录。这个时候有两个解决办法:
(5.1). 在Test项目的路径下面,按照路径规则创建WebRoot,WEB-INF等文件夹,然后把上面的web.xml拷贝到新建的WEB-INF中去。放心吧,我上一个项目就是这样做的,不过这种方式打死都不可取的。你修改JSP的时候改的是下面的,maven打包的时候用的上面的。你还得拷贝过来,拷过去,麻烦,如果再有svn管理,累死你,晕死你,我们经常是调试编写的时候再下面做,最后提交的时候还得一个个拷贝上去,还出很多问题。所以建议采用第二种方式。 (5.2).转换该项目: (1)在Test工程名上右键–>Properties–>Project Facets–>Convet to faceted form,
(2)勾上Dynamic Web Module,选择2.4版本。同时点击下方的further configuration available
(3)将默认的WebContent改成src/main/webapp
(4)一路点OK..此时在server视图中的tomcat server上点右键–>Add and Remove,就能看到该项目于,然后部署啦。
至此,我们已经创建好了一个合格的基于Maven的项目,也可以在Tomcat中部署。 接下来,我们开始整合我们的J2EE框架。
6.先给出数据库的创建脚本,方便测试搭建是否成功。
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; — — 数据库: `timesheet` — CREATE DATABASE `timesheet` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE `timesheet`; — ——————————————————– — — 表的结构 `testtable` — CREATE TABLE IF NOT EXISTS `testtable` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_bin DEFAULT NULL, `date` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ; 复制代码
7.在pom文件中添加必要的jar包的dependence,可以从两个地方查询:
mvnrepository.com/ search.maven.org/ 添加后的pom文件如下:
<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>net.yuanmomo</groupId> <artifactId>Test</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Test Maven Webapp</name> <url>http://maven.apache.org</url> <!– 设置 Spring 的版本 –> <properties> <org.springframework.version>3.0.0.RELEASE</org.springframework.version> </properties> <dependencies> <!– 此处开始就是Spring 所有的jar了,spring3.0的jar包拆分了,所以很多 –> <!– Core utilities used by other modules. Define this if you use Spring Utility APIs (org.springframework.core.*/org.springframework.util.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Expression Language (depends on spring-core) Define this if you use Spring Expression APIs (org.springframework.expression.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Bean Factory and JavaBeans utilities (depends on spring-core) Define this if you use Spring Bean APIs (org.springframework.beans.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Aspect Oriented Programming (AOP) Framework (depends on spring-core, spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Application Context (depends on spring-core, spring-expression, spring-aop, spring-beans) This is the central artifact for Spring’s Dependency Injection Container and is generally always defined –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Various Application Context utilities, including EhCache, JavaMail, Quartz, and Freemarker integration Define this if you need any of these integrations –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Transaction Management Abstraction (depends on spring-core, spring-beans, spring-aop, spring-context) Define this if you use Spring Transactions or DAO Exception Hierarchy (org.springframework.transaction.*/org.springframework.dao.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <!– JDBC Data Access Library (depends on spring-core, spring-beans, spring-context, spring-tx) Define this if you use Spring’s JdbcTemplate API (org.springframework.jdbc.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, and iBatis. (depends on spring-core, spring-beans, spring-context, spring-tx) Define this if you need ORM (org.springframework.orm.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX, Castor, XStream, and XML Beans. (depends on spring-core, spring-beans, spring-context) Define this if you need OXM (org.springframework.oxm.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Web application development utilities applicable to both Servlet and Portlet Environments (depends on spring-core, spring-beans, spring-context) Define this if you use Spring MVC, or wish to use Struts, JSF, or another web framework with Spring (org.springframework.web.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Spring MVC for Servlet Environments (depends on spring-core, spring-beans, spring-context, spring-web) Define this if you use Spring MVC with a Servlet Container such as Apache Tomcat (org.springframework.web.servlet.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Spring MVC for Portlet Environments (depends on spring-core, spring-beans, spring-context, spring-web) Define this if you use Spring MVC with a Portlet Container (org.springframework.web.portlet.*) –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${org.springframework.version}</version> </dependency> <!– Support for testing Spring applications with tools such as JUnit and TestNG This artifact is generally always defined with a ‘test’ scope for the integration testing framework and unit testing stubs –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <!– 上面的都是Spring的jar包,可以选择性的添加 –> <!– Mybatis 开发包 –> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <!– Mybatis 和Spring的 整合包,是mybatis出的–> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <!– tomcat servlet开发包 –> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!– JSTL标签库 –> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <!– mysql的数据库驱动包 –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!– 日志打印 log4j包 –> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> <scope>runtime</scope> </dependency> <!– 下面两个包 commons-dbcp,commons-pool 是配置数据源的包–> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.4</version> </dependency> <!– 日志记录依赖包,很多都依赖此包,像log4j,json-lib等等 –> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>1.1</version> </dependency> <!– Spring 文件上传的包 –> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!– Spring 文件上传的依赖包 –> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!– dom4j 解析 XML文件的包 –> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!– 下面的三个包是在配置事务的时候用到的 spring的依赖包 –> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <!– JSON lib 开发包 以及它的依赖包 –> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <classifier>jdk15</classifier> <version>2.4</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.5</version> </dependency> <!– junit 测试包 –> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>Test</finalName> </build> </project> 复制代码
修改pom文件后,保存,maven会自动的去download这些jar包到本地。等待的时间可能会很长。上面我把所有我这次项目用到的包都罗列出来了,如果你用不到的,可以自行删除。 下载完成过后,点开项目左侧的Maven Dependencies,你就能看到很多的下载的JAR包了。
8. 修改web.xml,配置Spring,spring MVC,log4j,乱码处理等。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!– Spring context startup Spring的初始化–> <context-param> <param-name>contextConfigLocation</param-name> <param-value><!– Spring的配置文件 –> classpath:/com/comverse/timesheet/config/ApplicationContext.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!– Spring character filter 处理乱码–> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!– Configuration of Log4j log4j的配置 –> <context-param> <param-name>log4jConfigLocation</param-name> <param-value><!– log4j.properties文件路径 –> classpath:/com/comverse/timesheet/config/log4j.properties </param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <!– Spring MVC Configuration Spring MVC的配置–> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value><!– dispatcher-servlet.xml文件路径 –> classpath:/com/comverse/timesheet/config/dispatcher-servlet.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> 复制代码
修改后保存该文件。
9.添加 log4j.properties,jdbc.properties等配置文件:
路径位置:
各个配置文件的内容如下: (1). log4j.properties: log4j的配置
#配置了控制台和文本记录两种方式 log4j.rootLogger=DEBUG,CONSOLE,FILEOUT log4j.addivity.org.apache=true# CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.Threshold=DEBUG log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout #log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d – %c -%-4r [%t] %-5p %c %x – %m%n log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n# # FILEOUT log4j.appender.FILEOUT=org.apache.log4j.RollingFileAppender log4j.appender.FILEOUT.File=${catalina.home}\\file.log log4j.appender.fileout.MaxFileSize=100000KB # default is true,append to the file; if false, the replace the log file whenever restart system log4j.appender.FILEOUT.Append=true #RollingFileAppender没有DatePattern这个属性 log4j.appender.FILEOUT.layout=org.apache.log4j.PatternLayout #log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d – %c -%-4r [%t] %-5p %c %x – %m%n log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%n 复制代码
(2). jdbc.properties: 数据库连接信息的配置
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/timesheet user=root password=root 复制代码
(3). ApplicationContext.xml: Spring的配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!– jdbc.properties文件路径 –> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:/com/comverse/timesheet/config/jdbc.properties" /> </bean> <!– 数据源的配置 –> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${user}" /> <property name="password" value="${password}" /> <!– data source configuration –> <property name="initialSize" value="60" /><!– initial connections –> <property name="maxActive" value="100" /><!– MAX connections –> <property name="maxIdle" value="50" /><!– MAX idle connections –> <property name="minIdle" value="10" /><!– MIN idle connections –> <!– 处理 mysql 8小时自动断开连接的问题 –> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="validationQuery" value="select 1" /> <property name="timeBetweenEvictionRunsMillis" value="20000" /> <property name="numTestsPerEvictionRun" value="100" /> </bean> <!–====事务相关控制==–> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="userTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pc" expression="execution(* com.comverse.timesheet.web.business.*.*(..))" /> <!– 把事务控制在Business层 –> <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" /> </aop:config> <!– MyBatis sqlSessionFactory 配置 mybatis–> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:/com/comverse/timesheet/mybatis/SqlMapConfig.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!– business AND implementation beans 包含ImplAndBusinessBeans.xml文件 –> <import resource="ImplAndBusinessBeans.xml" /> </beans> 复制代码
(4). dispatcher-servlet: Spring MVC的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 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-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <!– 把标记了@Controller注解的类转换为bean –> <context:component-scan base-package="com.comverse.timesheet.web.controller" /> <!– 启动Spring MVC的注解功能,完成请求和注解POJO的映射 –> <bean class="org.springframework.web.servlet.mvc. annotation.AnnotationMethodHandlerAdapter" /> <!– 视图 beans –> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <!– Controller 跳转的JSP页面路径 和 文件的后缀 –> <!– 文件上传 –> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!– set the max upload size100MB –> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>1024000</value> </property> </bean> </beans> 复制代码
(5). ImplAndBusinessBeans.xml: 这个文件主要放置implementation 和 Business的 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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!– 这两个类的具体实现会在后面给出来–> <bean id="ITestTableDAOImpl" class="com.comverse.timesheet.web.impl.ITestTableDAOImpl"> <property name="session" ref="sqlSession" /> </bean> <bean id="TestBusiness" class="com.comverse.timesheet.web.business.TestBusiness"> <property name="testDAO" ref="ITestTableDAOImpl" /> </bean> </beans> 复制代码
此时,几个主要的配置文件我们已经加进来了,只有mybatis还有几个配置文件没有加进来。
10. 创建包,用于开发系统:
bean : 放pojo, java bean business : 放业务层 conroller : 放控制层,主要负责接受请求和调用business,返回视图结果 dao : 放每个bean对应的接口 impl : dal 接口的具体实现 interceptor: 过滤器 resource : 资源包,比如文件路径,配置文件呀 test : 测试包 util : 工具包 web : 是装样子的哟,不是我这次要用的,是个空包。
10. 创建本次测试的 java 文件
(1). bean : TestTable.java:
package com.comverse.timesheet.web.bean;import java.util.Date;public class TestTable { private int id; private String name; private Date birthday; //setter and getter …………….} 复制代码
(2). dao : ITestTableDAO.java
package com.comverse.timesheet.web.dao;import com.comverse.timesheet.web.bean.TestTable;public interface ITestTableDAO { public boolean add(TestTable test) throws Exception; } 复制代码
(3). impl : ITestTableDAOImpl:
package com.comverse.timesheet.web.impl;import com.comverse.timesheet.web.bean.TestTable; import com.comverse.timesheet.web.dao.ITestTableDAO; import com.comverse.timesheet.web.util.BasicSqlSupport;public class ITestTableDAOImpl extends BasicSqlSupport implements ITestTableDAO { @Override public boolean add(TestTable test) throws Exception { boolean flag=false; int count=this.session.insert("com.comverse.timesheet.web.mapper.Test.add",test); if(count>0){ flag=true; } return flag; } } 复制代码
(4). business: TestBusiness.java
package com.comverse.timesheet.web.business;import java.util.Date;import javax.annotation.Resource;import org.springframework.transaction.annotation.Transactional;import com.comverse.timesheet.web.bean.TestTable; import com.comverse.timesheet.web.dao.ITestTableDAO;public class TestBusiness { private ITestTableDAO testDAO=null; public ITestTableDAO getTestDAO() { return testDAO; } public void setTestDAO(ITestTableDAO testDAO) { this.testDAO = testDAO; } public void add() throws Exception{ TestTable test=new TestTable(); test.setName("yuanmomo6"); test.setBirthday(new Date()); try { testDAO.add(test); } catch (Exception e) { // TODO Auto-generated catch block throw e; } } } 复制代码
(5). Controller : ResultController
package com.comverse.timesheet.web.controller;import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping;import com.comverse.timesheet.web.business.TestBusiness;@Controller @RequestMapping("/result.do") public class ResultController { //将spring 配置文件中的bean 通过setter注入进来 @Resource(name="TestBusiness") private TestBusiness testBusiness=null; public void setTestBusiness(TestBusiness testBusiness) { this.testBusiness = testBusiness; } @RequestMapping public String viewUser(HttpServletRequest request, ModelMap modelMap) throws Exception { System.out.println("$$$$$$$$$$$$$$$$$$$$$you want to check the result.jsp+++++++++++++"); System.out.println("$$$$$$$$$$$$$$$$$$$$$ ready to insert +++++++++++++"); testBusiness.add(); System.out.println("$$$$$$$$$$$$$$$$$$$$$ insert completed +++++++++++++"); return "result"; } } 复制代码
(6). util : BasicSqlSupport.java所有的implementation类都会继承这个类,在ImplAndBusinessBeans.xml文件中注册的bean,都会注入一个sqlsession。例如上面的implementation就是继承了这个类。
package com.comverse.timesheet.web.util;import org.apache.ibatis.session.SqlSession;public class BasicSqlSupport{ protected SqlSession session; public SqlSession getSession() { return session; } public void setSession(SqlSession session) { this.session = session; } } 复制代码
-
加入mybatis的配置文件: (1). 为 TestTable bean 创建mapper文件,路径为com/comverse/timesheet/mybatis/mapper/Test.xml: Test.xml
INSERT INTO testtable (NAME,DATE) VALUES(#{name},#{birthday})
(1). 加入Mybatis的配置文件:在上面的ApplicationContext.xml文件中我们已经包含了SqlMapConfig.xml文件。在/com/comverse/timesheet/mybatis/下创建 SqlMapConfig.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <typeAliases> <!– Entities 参数实体 –> <!– com.comverse.timesheet.web.bean 包中的 所有Bean, 取个别名 –> <!– 比如TestTable类就用Test来表示–> <typeAlias type="com.comverse.timesheet.web.bean.TestTable" alias="Test" /> </typeAliases> <mappers> <!– 对应Bean类的xml配置文件的路径信息 –> <mapper resource="com/comverse/timesheet/mybatis/mapper/Test.xml" /> </mappers> </configuration> 复制代码
- 框架的整合完成,项目的目录结构如下:
- 编写一个测试页面,这个页面的路径在dispatcher-servlet.xml中已经确定—/WEB-INF/jsp/: 文件名在controller中已经定义–result, 后缀是 .jsp, 所以就是 result.jsp。
(1). result.jsp:
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1> 你插入数据成功了!!!</h1> </body> </html> 复制代码
14.至此,我们的项目完成了,部署。
部署之前检查一下problem框,看有没有问题。这次我突然遇到一个问题,我上个星期五的时候都没有遇到,今天就奇了怪了。不过没事,问题来就想办法解决它。 (1).在problem处发现这个问题
Description: Classpath entry org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER will not be exported or published. Runtime ClassNotFoundExceptions may result. 如果部署了项目,启动,会报找不到类异常。
(2).问题的原因参考 Loose classpath web libraries support 在项目上右键–>properties—>deployment Assembly–>add,选择 java build path entries,然后选中Maven dependencies–>finish–>OK,就能解决问题啦。
14. 一点小插曲过后,我们再次的部署项目,重新启动,看日志,项目成功的启动起来啦。
打开浏览器:访问 http://localhost:8080/Test/,看到HelloWord先查看数据的信息,没有数据,返回0行。
接着访问, http://localhost:8080/Test/result.do 看到结果了,高兴哇!!再看数据库
数据插入成功,至此,我们的项目搭建完整的完成了!!!如有错别字,请原谅,因为打字太痛苦啦!!谢谢大家!!
-
检查一下我们的日志信息:
[DEBUG] 2012-08-13 18:10:34 :DispatcherServlet with name ‘dispatcher’ determining Last-Modified value for [/Test/result.do] [DEBUG] 2012-08-13 18:10:34 :Mapping [/result.do] to handler ‘com.comverse.timesheet.web.controller.ResultController@7056d5’ [DEBUG] 2012-08-13 18:10:34 :Last-Modified value for [/Test/result.do] is: -1 [DEBUG] 2012-08-13 18:10:34 :DispatcherServlet with name ‘dispatcher’ processing GET request for [/Test/result.do] [DEBUG] 2012-08-13 18:10:34 :Invoking request handler method: public java.lang.String com.comverse.timesheet.web.controller.ResultController.viewUser(javax.servlet.http.HttpServletRequest,org.springframework.ui.ModelMap) throws java.lang.Exception $$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$ ready to insert +++++++++++++ [DEBUG] 2012-08-13 18:10:34 :Creating new transaction with name [com.comverse.timesheet.web.business.TestBusiness.add]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-java.lang.Exception [DEBUG] 2012-08-13 18:10:34 :Acquired Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] for JDBC transaction [DEBUG] 2012-08-13 18:10:34 :Switching JDBC Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] to manual commit [DEBUG] 2012-08-13 18:10:34 :Creating a new SqlSession [DEBUG] 2012-08-13 18:10:34 :Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :JDBC Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] will be managed by Spring [DEBUG] 2012-08-13 18:10:34 :ooo Using Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] [DEBUG] 2012-08-13 18:10:34 :==> Preparing: INSERT INTO testtable (NAME,DATE) VALUES(?,?) [DEBUG] 2012-08-13 18:10:34 :==> Parameters: yuanmomo6(String), 2012-08-13 18:10:34.122(Timestamp) [DEBUG] 2012-08-13 18:10:34 :Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :Initiating transaction commit [DEBUG] 2012-08-13 18:10:34 :Committing JDBC transaction on Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] [DEBUG] 2012-08-13 18:10:34 :Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@177e6b4] [DEBUG] 2012-08-13 18:10:34 :Releasing JDBC Connection [jdbc:mysql://localhost:3306/timesheet, UserName=root@localhost, MySQL-AB JDBC Driver] after transaction [DEBUG] 2012-08-13 18:10:34 :Returning JDBC Connection to DataSource $$$$$$$$$$$$$$$$$$$$$ insert completed +++++++++++++ [DEBUG] 2012-08-13 18:10:34 :Invoking afterPropertiesSet() on bean with name ‘result’ [DEBUG] 2012-08-13 18:10:34 :Rendering view [org.springframework.web.servlet.view.JstlView: name ‘result’; URL [/WEB-INF/jsp/result.jsp]] in DispatcherServlet with name ‘dispatcher’ [DEBUG] 2012-08-13 18:10:34 :Forwarding to resource [/WEB-INF/jsp/result.jsp] in InternalResourceView ‘result’ [DEBUG] 2012-08-13 18:10:34 :Successfully completed request [DEBUG] 2012-08-13 18:10:34 :Returning cached instance of singleton bean ‘sqlSessionFactory’
可以看出我们的事务也添加成功。
Spring MVC的流程: request–>controller–>business–>implementation–>mysql
GitHub项目地址:暂无
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Hyperledger Fabric环境搭建及环境测试(Mac环境)
- CV 环境很重要,各种环境搭建大全
- Openstack Queens 环境搭建(一)环境准备
- Python 环境搭建
- 1 - 搭建开发环境
- 搭建 Android 内核环境
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数据结构(C语言版)
严蔚敏、吴伟民 / 清华大学出版社 / 2012-5 / 29.00元
《数据结构》(C语言版)是为“数据结构”课程编写的教材,也可作为学习数据结构及其算法的C程序设计的参数教材。 本书的前半部分从抽象数据类型的角度讨论各种基本类型的数据结构及其应用;后半部分主要讨论查找和排序的各种实现方法及其综合分析比较。其内容和章节编排1992年4月出版的《数据结构》(第二版)基本一致,但在本书中更突出了抽象数据类型的概念。全书采用类C语言作为数据结构和算法的描述语言。 ......一起来看看 《数据结构(C语言版)》 这本书的介绍吧!