转载

IDEA之Maven搭建Spring4 SpringMVC4 Mybatis3

首先打开Mysql的图形界面工具进行建库建表,当然也可以使用cmd黑窗口命令形式进行建库建表。

create database kaoshi;
use kaoshi;

create table k_dept(
   id int(11) auto_increment primary key,
   name varchar(30),
   age int(11),
   birdate date);

INSERT INTO `k_dept` VALUES ('1', '张三', '56', '2017-08-07');
INSERT INTO `k_dept` VALUES ('2', '李四', '47', '2017-09-04');
INSERT INTO `k_dept` VALUES ('3', '王五', '36', '2017-09-05');
IDEA之Maven搭建Spring4 SpringMVC4 Mybatis3

打开IDEA,创建Maven项目。

IDEA之Maven搭建Spring4 SpringMVC4 Mybatis3

pom.xml 文件如下。

<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.zhenqi.kaoshi</groupId>
  <artifactId>kaoshi-ssm</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>kaoshi-ssm Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- spring version -->
    <spring.version>4.3.8.RELEASE</spring.version>
    <mybatis.version>3.2.8</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-context</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-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring aop-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- AspectJ Runtime -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.6</version>
    </dependency>

    <!-- AspectJ Weaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </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.3</version>
    </dependency>

    <!-- Mysql官方驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <!-- 数据库缓存池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.1</version>
    </dependency>

    <!-- jstl 标签库 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!-- Servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</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>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>kaoshi-ssm</finalName>
  </build>
</project>

先把配置文件整理好。 db.properties。位置在resources目录下。

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/kaoshi?useUnicode=true&characterEncoding=UTF-8
user=root
password=root
idleConnectionTestPeriod=60
maxIdleTime=240
initialPoolSize=100
acquireIncrement=5
maxPoolSize=500
minPoolSize=10

日志记录配置文件,log4j.properties。

# DEBUG,INFO,WARN,ERROR,FATAL
LOG_LEVEL=INFO

#C-console, I-INFO, E-ERROR
log4j.rootLogger=${LOG_LEVEL},C,I,E

log4j.appender.C=org.apache.log4j.ConsoleAppender
log4j.appender.C.Threshold = INFO
log4j.appender.C.Encoding=utf-8
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} (%F:%L):%m%n

log4j.appender.I=org.apache.log4j.DailyRollingFileAppender
log4j.appender.I.File=${catalina.base}/logs/eidserver/info/log_daily
#log4j.appender.I.File=c://eidserver/info/log_daily
log4j.appender.I.Threshold = INFO
log4j.appender.I.Append = true
log4j.appender.I.Encoding=utf-8
log4j.appender.I.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.I.layout=org.apache.log4j.PatternLayout
log4j.appender.I.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH/:mm/:ss} (%F/:%L)/:%m%n
log4j.appender.I.MaxFileSize = 50MB
log4j.appender.I.MaxBackupIndex = 7

log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File=${catalina.base}/logs/eidserver/error/log_error
#log4j.appender.E.File=c://eidserver/error/log_error
log4j.appender.E.Append = TRUE
log4j.appender.E.Threshold = ERROR
log4j.appender.E.Encoding=utf-8
log4j.appender.E.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH/:mm/:ss} (%F/:%L)/:%m%n
log4j.appender.E.MaxFileSize = 50MB

spring-mvc.xml 。位置在resources目录下。

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.3.xsd">

    <!-- 注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp" />

    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> -->

    <!-- 注解探测器 -->
    <context:component-scan base-package="com.zhenqi" />
    <mvc:default-servlet-handler/>
</beans>

而后是 spring-mybatis.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:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 引入jdbc配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db.properties" />
    </bean>

    <!--创建jdbc数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
          p:driverClass="${driver}"
          p:jdbcUrl="${jdbcUrl}"
          p:user="${user}"
          p:password="${password}"
          p:idleConnectionTestPeriod="${idleConnectionTestPeriod}"
          p:maxIdleTime="${maxIdleTime}"
          p:initialPoolSize="${initialPoolSize}"
          p:acquireIncrement="${acquireIncrement}"
          p:maxPoolSize="${maxPoolSize}"
          p:minPoolSize="${minPoolSize}"
          p:preferredTestQuery="SELECT 1"
          p:maxConnectionAge="3000" />

    <!-- 创建SqlSessionFactory,同时指定数据源
         spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations">
            <list>
                <value>classpath*:com/zhenqi/dao/*.xml</value>
            </list>
        </property>
    </bean>

    <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="com.zhenqi.dao"
          p:sqlSessionFactoryBeanName="sqlSessionFactory" />

    <!-- ===================================事务的配置================================== -->

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource" />

    <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器  -->
    <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 -->
    <!-- 优先级:如果配置冲突,注解的比xml的高 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 配置事务特性 ,配置add、delete和update开始的方法,事务传播特性为required -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="modify*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="edit*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="login*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="regist*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
            <tx:method name="getAll*" propagation="REQUIRED" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置哪些类的方法进行事务管理 -->
    <aop:config>
        <aop:pointcut id="allManagerMethod" expression="execution (* com.zhenqi.*.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" />
    </aop:config>

</beans>

然后在 web.xml 文件配置。

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <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:spring-mybatis.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>springmvc-dispatcherservlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc-dispatcherservlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置文件整理好了,接下来就可以编写Java代码了。

1、Entity实体对象Dept.java

package com.zhenqi.entity;

import java.util.Date;

/**
 * Created by wuming on 2017/9/8.
 */
public class Dept {
    private Integer id;
    private String name;
    private Integer age;
    private Date birDate;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Date getBirDate() {
        return birDate;
    }
    public void setBirDate(Date birDate) {
        this.birDate = birDate;
    }
}
2、Dao层

而后是Dao接口与Mapper xml文件。

DeptDao.java

package com.zhenqi.dao;
import com.zhenqi.entity.Dept;
import java.util.List;
/**
 * Created by wuming on 2017/9/8.
 */
public interface DeptDao {
    //查找所有内容
    public List<Dept> findAll();
}

Dept.xml 其位置 com/zhenqi/dao目录下。

<?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.zhenqi.dao.DeptDao">

    <resultMap id="deptAll" type="com.zhenqi.entity.Dept" >
        <id property="id" column="IID" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <result property="birDate" column="birdate" />
    </resultMap>
    <!-- 查找 -->
    <select id="findAll"  resultMap="deptAll">
        select * from k_dept
    </select>
</mapper>

3.Service层,也就是处理业务相关的。DeptService.java接口文件如下:

package com.zhenqi.service;
import com.zhenqi.entity.Dept;
import java.util.List;
/**
 * Created by wuming on 2017/9/8.
 */
public interface DeptService {
    //查找所有内容
    public List<Dept> findall();
}

实现类 DeptServiceImpl.java 如下:

package com.zhenqi.service.impl;

import com.zhenqi.dao.DeptDao;
import com.zhenqi.entity.Dept;
import com.zhenqi.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by wuming on 2017/9/8.
 */

@Service("deptService")
public class DeptServiceImpl implements DeptService {
    //注入dao对象
    @Autowired
    private DeptDao deptDao;

    public List<Dept> findall() {
        return deptDao.findAll();
    }
}

4、Controller层,也就是所谓的控制层。DeptController.java文件如下:

package com.zhenqi.controller;

import com.zhenqi.entity.Dept;
import com.zhenqi.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by wuming on 2017/9/8.
 */
@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @RequestMapping("/find")
    public String find(ModelMap model, HttpServletRequest request){
        List<Dept> deptList=deptService.findall();
        //将获取到的数据存入ModelMap中,以便页面取出
        model.addAttribute("depts", deptList);
        return "dept";
    }
}

5、view层,就是jsp或html。dept.jsp文件如下,其位置在 WEB-INF/views/ 目录下。

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page  isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=UTF-8">
    <title>Dept</title>
</head>
<body>
<table>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>生日</th>
    </tr>
    <c:forEach var="dept" items="${depts}">
        <tr>
            <td><c:out value="${dept.id}"/></td>
            <td><c:out value="${dept.name}"/></td>
            <td><c:out value="${dept.age}"/></td>
            <td><c:out value="${dept.birDate}"/></td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

启动Tomcat容器,如果不知怎么在IDEA中部署maven项目到Tomcat上的朋友,可参考文章: IDEA运行Maven项目部署tomcat上

访问浏览器, http://localhost:8080/kaoshi-ssm/dept/find

IDEA之Maven搭建Spring4 SpringMVC4 Mybatis3

至此,maven搭建ssm框架就先告一段落了。

原文  http://blog.csdn.net/coco2d_x2014/article/details/77899085
正文到此结束
Loading...