intelliJ-idea-使用maven创建springspringMVCmybatisSSM

35次阅读

共计 15018 个字符,预计需要花费 38 分钟才能阅读完成。

ssm demo github : https://github.com/rongyaya10…

配置 pom 用到的框架和版本:
spring 5.0.5.RELEASE
mybatis 3.4.0
mysql 5.1.35
log4j 1.2.17
mybatis-spring 1.3.2
jdk 1.8

1、配置 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>org.ssmdemo</groupId>
  <artifactId>ssmdemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ssmdemo</name>
  <url>http://maven.apache.org</url>
  <properties>
    <junit.version>4.12</junit.version>
    <mybatis-spring.version>1.3.2</mybatis-spring.version>
    <mybatis.version>3.4.0</mybatis.version>
    <mysql.version>5.1.35</mysql.version>
    <spring.version>5.0.5.RELEASE</spring.version>
    <druid.version>1.0.19</druid.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>

    <!-- junit -->
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- 数据库 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis-spring.version}</version>
    </dependency>

    <!-- spring 核心依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring ioc 依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>

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

    <!-- spring 扩展依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--spring dao 层依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring web 相关依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring test 相关依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- spring 依赖  end-->

    <dependency>
      <groupId>com.fengwenyi</groupId>
      <artifactId>JavaLib</artifactId>
      <version>0.0.9</version>
    </dependency>

    <!--springfox 依赖的 jar 包;如果你的项目中已经集成了无需重复 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>

    <!-- Log -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>ssmdemo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

import change -> ok

2、在 src->main 下新建 resources,右键 make directory as -> Resources Root

3、resources -> 新建 applicationContent.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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
">

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

    <!-- 2. 扫描的包路径,这里不扫描被 @Controller 注解的类 -->
    <!-- 使用 <context:component-scan/> 可以不在配置 <context:annotation-config/> -->
    <context:component-scan base-package="com.zgr">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <import resource="classpath:spring-mybatis.xml" />

</beans>

4、resources -> 新建 spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="
       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
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!-- 扫描 controller(controller 层注入)-->
    <context:component-scan base-package="com.zgr.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:annotation-driven />

    <!-- 内容协商管理器  -->
    <!--1、首先检查路径扩展名(如 my.pdf);2、其次检查 Parameter(如 my?format=pdf);3、检查 Accept Header-->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 扩展名至 mimeType 的映射, 即 /user.json => application/json -->
        <property name="favorPathExtension" value="true"/>
        <!-- 用于开启 /userinfo/123?format=json 的支持 -->
        <property name="favorParameter" value="true"/>
        <property name="parameterName" value="format"/>
        <!-- 是否忽略 Accept Header -->
        <property name="ignoreAcceptHeader" value="false"/>

        <property name="mediaTypes"> <!-- 扩展名到 MIME 的映射;favorPathExtension, favorParameter 是 true 时起作用  -->
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            </value>
        </property>
        <!-- 默认的 content type -->
        <property name="defaultContentType" value="text/html"/>
    </bean>


    <!-- 当在 web.xml 中   DispatcherServlet 使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
    <mvc:default-servlet-handler />
    <!-- 静态资源映射 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>


    <!-- 对模型视图添加前后缀 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>

</beans>

5、resources -> 新建 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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- 3. 配置数据源,使用的 alibba 的数据库 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name="driverClassName" value="${jdbc_driverClassName}"/>
        <property name="url" value="${jdbc_url}"/>
        <property name="username" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="10"/>
        <property name="minIdle" value="10"/>
        <property name="maxActive" value="50"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打开 PSCache,并且指定每个连接上 PSCache 的大小  如果用 Oracle,则把 poolPreparedStatements 配置为 true,mysql 可以配置为 false。-->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置监控统计拦截的 filters -->
        <property name="filters" value="wall,stat" />
    </bean>



    <!-- spring 和 MyBatis 完美整合,不需要 mybatis 的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 扫描 entity 包 使用别名 -->
        <property name="typeAliasesPackage" value="com.zgr.domain" />
        <!-- 自动扫描 mapping.xml 文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>


    <!-- DAO 接口所在包名,Spring 会自动查找其下的类 , 自动扫描了所有的 XxxxMapper.xml 对应的 mapper 接口文件, 只要 Mapper 接口类和 Mapper 映射文件对应起来就可以了 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zgr.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

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

    <!--======= 事务配置 End =================== -->
    <!-- 配置基于注解的声明式事务 -->
    <!-- enables scanning for @Transactional annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" />


</beans>

6、resources -> 新建 log4j.properties

# Root logger option
#ALL<DEBUG<INFO<WARN<ERROR<FATAL<OFF
log4j.rootLogger=INFO, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Rirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/logs/log4j.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

log4j.logger.org.springframework=ERROR

7、resources -> 新建 jdbc.properties

jdbc_driverClassName =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/ssmdemo?useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=root

环境搭建好了,可以写个 demo 试试看

  • UserController.java
package com.zgr.controller;

import com.zgr.domain.User;
import com.zgr.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value="/showname",method= RequestMethod.GET)
    public String getUserById (@RequestParam("uid") int id,
                               Model model) {if (id > 0) {User user = userService.getUserById(id);
            model.addAttribute("name", user.getName());
            return "user/info";
        }
        return "user/error";
    }
}
  • IUserDao.java
package com.zgr.dao;

import com.zgr.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface IUserDao {List<User> getUsers();

    User getUserById(@Param("id") Integer id);

    /*List<User> getUserByPage(Integer pageCurr, Integer pageSize);*/

    Integer insert (@Param("user") User user);

    Integer update (@Param("user") User user);

    Integer delete (@Param("id") Integer id);

}
  • User.java
package com.zgr.domain;

public class User {
    private Integer id;
    private String name;
    private Integer age;

    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;}

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • IUserService.java
package com.zgr.service;

import com.zgr.domain.User;

import java.util.List;

public interface IUserService {List<User> getUsers();

    User getUserById(Integer id);

    Integer insert (User user);

    Integer update (User user);

    Integer delete (Integer id);

}
  • UserService.java
package com.zgr.service.impl;

import com.zgr.dao.IUserDao;
import com.zgr.domain.User;
import com.zgr.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {

    @Autowired
    private IUserDao userDao;

    public List<User> getUsers () {List<User> users = userDao.getUsers();
        if (users != null)
            return users;
        return null;
    }
}
  • 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.zgr.dao.IUserDao">

    <!-- List<User> getUsers(); -->
    <select id="getUsers" resultType="User">
        SELECT <include refid="column" />
        FROM <include refid="tName"/>
    </select>

    <!--User getUserById(@Param("id") Integer id);-->
    <select id="getUserById" resultType="User">
        SELECT <include refid="column" />
        FROM <include refid="tName"/>
        <where>
            id = #{id}
        </where>
    </select>

    <!--List<User> getUserByPage(Integer pageCurr, Integer pageSize);-->

    <!--Integer insert (@Param("user") User user);-->
    <insert id="insert">
        INSERT INTO <include refid="tName"/> (name, age)
        VALUE (#{user.name}, #{user.age})
    </insert>

    <!--Integer update (@Param("user") User user);-->
    <update id="update">
        UPDATE <include refid="tName"/>
        <set>
            <if test="user.name != null">
                name = #{user.name},
            </if>
            <if test="user.age != null and user.age > 0">
                age = #{user.age}
            </if>
        </set>
        WHERE id = #{user.id}
    </update>

    <!--Integer delete (@Param("id") Integer id);-->
    <delete id="delete">
        DELETE FROM <include refid="tName"/>
        WHERE id = #{id}
    </delete>

    <sql id="tName">
        user
    </sql>

    <sql id="column">
        id, name, age
    </sql>
</mapper>

正文完
 0