这篇文章主要讲解在eclipse环境下SpringMVC+Maven+Mybatis+MySQL的项目搭建过程。
- 创建Maven工程。
右击-->New->Other
点击->Manven Porject
点击->勾选快速框架
输入项目名,包(Packaging,如果只是普通的项目,选jar就好了,如果是web项目就选war,这里是web项目,所以选择war)
右击项目->Properties->Java Build Path->选择Libraries->点击选中 JRE System Library->Edit
选择默认JRE,注:必须系统安装了JDK。
点击Project Facets 去掉勾选 Dynamic Web Module 再把 Java 改为系统设置版本。
再打开Project Facets ->勾选 Dynamic Web Module 选择3.0版本时,下面有个 Further configuration available... ->点击
,
输入 content directory 地址: src/main/webapp
创建好的目录如下:
- 配置Spring MVC
添加包的依赖,编辑pom.xml文件添加如下依赖:(因为我的JDK版本是1.8所以Spring 版本必须为4.0以上)
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.liaoze</groupId> <artifactId>stockmgt_maven_project</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <!-- spring版本号 --> <spring.version>4.1.5.RELEASE</spring.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <!-- junit版本号 --> <junit.version>4.10</junit.version> <!-- mybatis版本号 --> <mybatis.version>3.2.1</mybatis.version> </properties> <dependencies> <!-- 添加Spring依赖 --> <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.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</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>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!--spring单元测试依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!--mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency> <!-- mysql驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> </dependencies> </project>
加入配置文件
jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://localhost:3306/stockmgt jdbc_username=root jdbc_password=123456
application.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:context="http://www.springframework.org/schema/context" 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.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 引入jdbc配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/*.properties</value> <!--要是有多个配置文件,只需在这里继续添加即可 --> </list> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!-- 不使用properties来配置 --> <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/learning" /> <property name="username" value="root" /> <property name="password" value="[email protected]" /> --> <!-- 使用properties来配置 --> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> </bean> <!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.liaoze.stockmgt.dao" /> </bean> <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" /> --> </bean> <!-- 自动扫描注解的bean --> <context:component-scan base-package="com.liaoze.stockmgt.service" /> </beans>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <mvc:annotation-driven /> <!-- 扫描controller(controller层注入) --> <context:component-scan base-package="com.liaoze.stockmgt.controller"/> <!-- 对模型视图添加前后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp"/> </beans>
userMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.liaoze.stockmgt.dao.UserDao"> <!--设置domain类和数据库中表的字段一一对应,注意数据库字段和domain类中的字段名称不致,此处一定要!--> <resultMap id="BaseResultMap" type="com.liaoze.stockmgt.model.User"> <id column="USER_ID" property="userId" jdbcType="INTEGER" /> <result column="USER_NAME" property="userName" jdbcType="CHAR" /> <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" /> </resultMap> <!-- 查询单条记录 --> <select id="selectUserById" parameterType="int" resultMap="BaseResultMap"> SELECT * FROM t_user WHERE USER_ID = #{userId} </select> </mapper>
进入mysql 数据库:
/*新建数据库*/ CREATE DATABASE IF NOT EXISTS stockmgt DEFAULT CHARSET utf8; /*新建表*/ COLLATE utf8_general_ci; CREATE TABLE `t_user` ( `USER_ID` INT(11) NOT NULL AUTO_INCREMENT, `USER_NAME` CHAR(30) NOT NULL, `USER_PASSWORD` CHAR(10) NOT NULL, PRIMARY KEY (`USER_ID`), KEY `IDX_NAME` (`USER_NAME`) ) ENGINE=INNODB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; /*插入测试数据*/ INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD) VALUES (1, ‘张三‘, ‘123456‘); INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD) VALUES (2, ‘李四‘, ‘123456‘);
编写java类:
User.java
package com.liaoze.stockmgt.model; public class User { private Integer userId; private String userName; private String userPassword; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } }
UserDao.java
package com.liaoze.stockmgt.dao; import com.liaoze.stockmgt.model.User; public interface UserDao { /** * @param userId * @return User */ public User selectUserById(Integer userId); }
UserService.java
package com.liaoze.stockmgt.service; import com.liaoze.stockmgt.model.User; public interface UserService { User selectUserById(Integer userId); }
UserServiceImpl.java
package com.liaoze.stockmgt.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.liaoze.stockmgt.dao.UserDao; import com.liaoze.stockmgt.model.User; import com.liaoze.stockmgt.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public User selectUserById(Integer userId) { return userDao.selectUserById(userId); } }
编写测试类JUnit4进行单元测试:
SpringTestCase.java
package com.liaoze.stockmgt.test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //指定bean注入的配置文件 @ContextConfiguration(locations = { "classpath:application.xml" }) //使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner @RunWith(SpringJUnit4ClassRunner.class) public class SpringTestCase extends AbstractJUnit4SpringContextTests { }
UserServiceTest.java
package com.liaoze.stockmgt.test.service; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.liaoze.stockmgt.model.User; import com.liaoze.stockmgt.service.UserService; import com.liaoze.stockmgt.test.SpringTestCase; public class UserServiceTest extends SpringTestCase { @Autowired private UserService userService; @Test public void selectUserByIdTest(){ User user = userService.selectUserById(1); System.out.println(user.getUserName() + ":" + user.getUserPassword()); } }
选中方法名->右击->Run As -> 点击 JUnit Test
显示测试运行成功!
控制台输出如下:
新建Controller:
新建UserController.java
package com.liaoze.stockmgt.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.liaoze.stockmgt.model.User; import com.liaoze.stockmgt.service.UserService; @Controller public class UserController { @Resource private UserService userService; @RequestMapping("/") public ModelAndView getIndex(){ ModelAndView mav = new ModelAndView("index"); User user = userService.selectUserById(1); mav.addObject("user", user); return mav; } }
添加jsp 页面:在src/main/webapp/WEB-INF/新建view文件夹
再新建index.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> <body> <h2>Hello World!</h2> 用户名: ${user.userName}<br> 密码:${user.userPassword}<br> </body> </html>
运行!
浏览器输入地址:http://127.0.0.1:8080/stockmgt_maven_project/
无乱码!成功!
参考:http://www.open-open.com/lib/view/open1453195087105.html