林炳文Evankaka原創做品。轉載請註明出處http://blog.csdn.net/evankakahtml
摘要:本文主要講了如何使用Maven來搭建Spring+Mybatis+SpringMVC+MySql的搭建實例,文章寫得很詳細,有代碼有圖片,最後也帶有運行的效果。java
本文工程免費下載mysql
1、準備工做
1. 首先建立一個表:web
- CREATE TABLE `t_user` (
- `USER_ID` int(11) NOT NULL AUTO_INCREMENT,
- `USER_NAME` char(30) NOT NULL,
- `USER_PASSWORD` char(10) NOT NULL,
- `USER_EMAIL` char(30) 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, USER_EMAIL) VALUES (1, '林炳文', '1234567@', 'ling20081005@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'evan', '123', 'fff@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'kaka', 'cadg', 'fwsfg@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (4, 'simle', 'cscs', 'fsaf@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (5, 'arthur', 'csas', 'fsaff@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (6, '小德', 'yuh78', 'fdfas@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (7, '小小', 'cvff', 'fsaf@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (8, '林林之家', 'gvv', 'lin@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (9, '林炳文Evankaka', 'dfsc', 'ling2008@126.com');
- INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (10, 'apple', 'uih6', 'ff@qq.com');
2、工程建立
一、Maven工程建立spring
(1)新建sql
(2)選擇快速框架數據庫
(3)輸出項目名,包,記得選war(表示web項目,之後能夠spingMVC連起來用)apache
(4)建立好以後 api
目錄以下:瀏覽器
(5)檢查下
這三個地方JDK的版本必定要同樣!!!!
3、sping+mybatis配置
一、整個工程目錄以下:
二、POM文件
三、java代碼-------src/main/java
目錄以下:
(1)User.java
對應數據庫中表的字段,放在src/main/java下的包com.lin.domain
- package com.lin.domain;
-
- public class User {
- private Integer userId;
- private String userName;
- private String userPassword;
- private String userEmail;
-
- 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;
- }
-
- public String getUserEmail() {
- return userEmail;
- }
-
- public void setUserEmail(String userEmail) {
- this.userEmail = userEmail;
- }
-
- @Override
- public String toString() {
- return "User [userId=" + userId + ", userName=" + userName
- + ", userPassword=" + userPassword + ", userEmail=" + userEmail
- + "]";
- }
-
- }
(2)UserDao.java
Dao接口類,用來對應mapper文件。放在src/main/java下的包com.lin.dao,內容以下:
- package com.lin.dao;
-
-
- import com.lin.domain.User;
-
- public interface UserDao {
-
- public User selectUserById(Integer userId);
-
- }
(2)UserService.java和UserServiceImpl.java
service接口類和實現類,放在src/main/java下的包com.lin.service,內容以下:
UserService.java
- package com.lin.service;
-
- import org.springframework.stereotype.Service;
-
- import com.lin.domain.User;
-
- public interface UserService {
- User selectUserById(Integer userId);
-
- }
UserServiceImpl.java
- package com.lin.service;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import com.lin.dao.UserDao;
- import com.lin.domain.User;
-
- @Service
- public class UserServiceImpl implements UserService{
- @Autowired
- private UserDao userDao;
-
- public User selectUserById(Integer userId) {
- return userDao.selectUserById(userId);
-
- }
-
- }
(4)mapper文件
用來和dao文件對應,放在src/main/java下的com.lin.mapper包下
- <?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.lin.dao.UserDao">
- <resultMap id="BaseResultMap" type="com.lin.domain.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" />
- <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
- </resultMap>
-
- <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
- SELECT * FROM t_user WHERE USER_ID = #{userId}
- </select>
- </mapper>
四、資源配置-------src/main/resources
目錄以下:
(1)mybatis配置文件
這裏沒有什麼內容,由於都被放到application.xml中去了,放在src/main/resources下的mybatis文件夾下
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>
(2)數據源配置jdbc.properties
放在src/main/resources下的propertiesy文件夾下
- jdbc_driverClassName=com.mysql.jdbc.Driver
- jdbc_url=jdbc:mysql://localhost:3306/learning
- jdbc_username=root
- jdbc_password=christmas258@
(3)Spring配置
這是最重要的: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">
-
-
- <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">
-
- <!-- <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="christmas258@" /> -->
-
- <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>
-
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage"
- value="com.lin.dao" />
- </bean>
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>
- <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
- <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
- /> -->
- </bean>
-
-
- <context:component-scan base-package="com.lin.service" />
-
- </beans>
(4)日誌打印log4j.properties
就放在src/main/resources
- log4j.rootLogger=DEBUG,Console,Stdout
-
- #Console
- log4j.appender.Console=org.apache.log4j.ConsoleAppender
- log4j.appender.Console.layout=org.apache.log4j.PatternLayout
- log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
-
- log4j.logger.java.sql.ResultSet=INFO
- log4j.logger.org.apache=INFO
- log4j.logger.java.sql.Connection=DEBUG
- log4j.logger.java.sql.Statement=DEBUG
- log4j.logger.java.sql.PreparedStatement=DEBUG
-
- log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.Stdout.File = E://logs/log.log
- log4j.appender.Stdout.Append = true
- log4j.appender.Stdout.Threshold = DEBUG
- log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
- log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
4、單元測試
上面的配置無缺,接下來就是測驗成功
整個目錄 以下:
(1)測試基類
- package com.lin.baseTest;
-
- import org.junit.runner.RunWith;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- @ContextConfiguration(locations = { "classpath:application.xml" })
- @RunWith(SpringJUnit4ClassRunner.class)
- public abstract class SpringTestCase extends AbstractJUnit4SpringContextTests{
- protected Logger logger = LoggerFactory.getLogger(getClass());
- }
(2)測試類
- package com.lin.service;
-
- import org.apache.log4j.Logger;
- import org.junit.Test;
- import org.springframework.beans.factory.annotation.Autowired;
-
- import com.lin.baseTest.SpringTestCase;
- import com.lin.domain.User;
-
- public class UserServiceTest extends SpringTestCase {
- @Autowired
- private UserService userService;
- Logger logger = Logger.getLogger(UserServiceTest.class);
-
- @Test
- public void selectUserByIdTest(){
- User user = userService.selectUserById(10);
- logger.debug("查找結果" + user);
- }
-
-
- }
選中selectUserByIdTest,而後右鍵以下運行
輸出結果:
重要打印的結果
這裏
- 2015-09-28 15:20:15,129 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==> Preparing: SELECT * FROM t_user WHERE USER_ID = ?
- 2015-09-28 15:20:15,160 [main] DEBUG [com.lin.dao.UserDao.selectUserById] - ==> Parameters: 10(Integer)
- 2015-09-28 15:20:15,160 [main] DEBUG [org.mybatis.spring.SqlSessionUtils] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6b64bff9]
- 2015-09-28 15:20:15,160 [main] DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
- 2015-09-28 15:20:15,160 [main] DEBUG [com.lin.service.UserServiceTest] - 查找結果User [userId=10, userName=apple, userPassword=uih6, userEmail=ff@qq.com]
數據庫:
程序成功運行,而且結果正確!
到這裏配置好spring+mybatis+mysql!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
=====================================================
這裏開始添加spirngMVC,並轉換maven工程爲web項目
5、轉換web工程
接上面的工程接着說,此時要加spingMVC以前,工程得再稍微轉換下
此時webapp下的結果尚未顯示出來,由於此時咱們尚未配置此的項目爲web項目
再次進去Properties配置,以下圖所示:若是沒有顯示以下,那就先把dynamic web module的√給去掉,而後從新再打開 這個
進入,而後輸入以下內容
肯定OK以後,webapp下面就會自動生成一些文件,以下
6、配置SpringMVC
(1)修改POM文件,增長了一此內容,新的POM文件以下:
-
- <dependency>
- <groupId>javax</groupId>
- <artifactId>javaee-api</artifactId>
- <version>6.0</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>javax</groupId>
- <artifactId>javaee-web-api</artifactId>
- <version>6.0</version>
- <scope>provided</scope>
- </dependency>
(2) 在src/main/resource中添加springmvc文件夾,而後添加文件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">
-
-
- <context:component-scan base-package="com.lin.controller"/>
-
-
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
- </beans>
(3)配置web,xml
目錄以下 :
這裏是關鍵,web.xml是用來起動sping、spingMVC
放在src/main/webapp/WEB-INF下。內容以下:
- <?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">
- <display-name>Archetype Created Web Application</display-name>
-
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:application.xml</param-value>
- </context-param>
-
- <context-param>
- <param-name>webAppRootKey</param-name>
- <param-value>springmvc.root</param-value>
- </context-param>
-
-
-
- <filter>
- <filter-name>SpringEncodingFilter</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>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>SpringEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
-
- <context-param>
-
- <param-name>log4jConfigLocation</param-name>
- <param-value>classpath:log4j.properties</param-value>
- </context-param>
- <context-param>
-
- <param-name>log4jRefreshInterval</param-name>
- <param-value>6000</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
-
- <servlet>
- <servlet-name>dispatcherServlet</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
-
- <param-value>classpath:springmvc/spring-mvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>dispatcherServlet</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
-
-
- <error-page>
-
- <error-code>404</error-code>
- <location>/WEB-INF/errorpage/404.jsp</location>
- </error-page>
- <error-page>
-
- <error-code>405</error-code>
- <location>/WEB-INF/errorpage/405.jsp</location>
- </error-page>
- <error-page>
-
- <error-code>500</error-code>
- <location>/WEB-INF/errorpage/500.jsp</location>
- </error-page>
- </web-app>
(4)添加index.jsp
在src/main/webapp/WEB-INF下新建一個文件夾view,添加一個index.jsp,內容以下:
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <html>
- <body>
- <h2>Hello World!</h2>
- ${user.userId}<br>
- ${user.userName}<br>
- ${user.userPassword}<br>
- ${user.userEmail}<br>
- </body>
- </html>
(5)最後就是controller的書寫了
在src/main/java下新建一個包com.lin.controller.而後新建一個類UserController.java,其內容以下:
- package com.lin.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.lin.domain.User;
- import com.lin.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;
- }
- }
(6)最後的運行!
最後,就是成果了,已經所有都配置好了。咱們能夠開始以web工程運行了!
而後一路next
接下來控制檯就會打印日誌出來了!以下
打印瀏覽器,輸入網址:http://localhost:8088/ssm_project/
from: http://blog.csdn.net/evankaka/article/details/48785513