Intellij Idea创建基于Maven的SpringMVC+MyBatis项目

时间:2021-12-18 09:54:22

前言:SpringMVC是一款轻量级的Web开发框架,非常有利于新手上手,对于持久化层,目前可选择的是Hibernate和Mybatis,而Mybatis的学习曲线较为平整,因此本文介绍了利用Intellij Idea创建基于Maven的SpringMVC/MyBatis的项目,该项目实现了简单的用户插入和导出,其实什么项目无所谓,主要目的还是供大家掌握MyBatis和SpringMVC的实现过程。

完成本文的项目创建,你需要以下软件的支持:

软件 版本
JDK 1.6+
Tomcat 7+
Maven 2+
Mysql 5+
Intellij Idea 14.+

一 新建项目

在你的某一个project下:

File->New->Module

然后如下图所示,选中Maven支持:
Intellij Idea创建基于Maven的SpringMVC+MyBatis项目
点击Next到下一步,并填写项目名:
Intellij Idea创建基于Maven的SpringMVC+MyBatis项目
再下一步:
Intellij Idea创建基于Maven的SpringMVC+MyBatis项目
选择Maven的版本,一般使用默认的版本即可!
一路点击Next即可,第一次建立Maven项目需要等待IDE创建,不如去喝杯水!

二 配置文件

等待项目创建完毕,目前整个项目结构如下:
Intellij Idea创建基于Maven的SpringMVC+MyBatis项目

然后开始创建文件夹和项目的配置文件。
1. 首先再main下创建java文件夹,并标记位源文件目录(Sources Root):
Intellij Idea创建基于Maven的SpringMVC+MyBatis项目
在java目录下创建四个package:

com.zhaoyh.controller
com.zhaoyh.storage
com.zhaoyh.service
com.zhaoyh.model
  1. 在resources文件夹下新建mapper,spring文件夹和application.properties,mybatis-config.xml两个文件。
    并在spring文件夹下面新建三个配置文件:
spring-service.xml
spring-storage.xml
spring-web.xml
  1. 删除WEB-INF下面的index.jsp,新建VM文件夹,并在VM文件夹下面新建index.vm模版文件。
  2. 此时整个项目的目录结构如下:
    Intellij Idea创建基于Maven的SpringMVC+MyBatis项目

三 文件内容和Java方法

  1. model包下新建User.java
package com.zhaoyh.model;

/**
* Created by zhaoyh on 2017/5/26.
*/

public class User {

private long id;
private String name;
private String phone;

public User() {
}

public User(String name, String phone) {
this.name = name;
this.phone = phone;
}

public User(long id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}
}
  1. storage下新建UserStorage.java接口,内容如下:
package com.zhaoyh.storage;

import com.zhaoyh.model.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
* Created by zhaoyh on 2017/5/26.
*/

public interface UserStorage {

/**
* 插入用户
* @param userName
* @param phone
*/

void addUser(@Param("name") String userName, @Param("phone") String phone);

/**
* 查询用户列表
* @param phone
* @return
*/

List<User> queryUserByPhone(@Param("phone") String phone);

}
  1. 在service包下新建IUserServe.java,UserService.java两个文件,内容分别是:
package com.zhaoyh.service;

import com.zhaoyh.model.User;

import java.util.List;

/**
* Created by zhaoyh on 2017/5/26.
*/

public interface IUserService {

void addUser(User user);

List<User> getUserByPhone(String phone);
}
package com.zhaoyh.service;

import com.zhaoyh.model.User;
import com.zhaoyh.storage.UserStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* Created by zhaoyh on 2017/5/26.
*/

@Service
public class UserService implements IUserService {

@Autowired
private UserStorage userStorage;

public void addUser(User user) {
userStorage.addUser(user.getName(), user.getPhone());
}

public List<User> getUserByPhone(String phone) {
return userStorage.queryUserByPhone(phone);
}
}
  1. controller包下新建MainController.java和BaseController.java文件,内容分别是:
package com.zhaoyh.controller;

import com.zhaoyh.model.User;
import com.zhaoyh.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

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

/**
* Created by zhaoyh on 2017/5/26.
*/

@Controller
public class MainController extends BaseController {

@Autowired
private IUserService userService;

public static final String INDEX = "index";

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {

User user = new User("zhaoyh", "18811721028");
userService.addUser(user);

List<User> userList = userService.getUserByPhone("18811721028");
System.out.println("......" + userList.size());

return innerCreateModelAndView(INDEX);
}


}
package com.zhaoyh.controller;

import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
* Created by zhaoyh on 2017/5/26.
*/

public class BaseController {

/**
* 生成视图,用于继承
* @param view
*/

protected ModelAndView innerCreateModelAndView (String view, Object... objects) {
assert (objects.length % 2) == 0;
Map<String, Object> modelMap = new HashMap<String, Object>();
for (int i = 0; i < objects.length; i++) {
String name = (String) objects[i++];
modelMap.put(name, objects[i]);
}
return new ModelAndView(view, modelMap);
}
}
  1. mapper文件夹下新建UserStorage.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.zhaoyh.storage.UserStorage">

<select id="queryUserByPhone" resultType="com.zhaoyh.model.User">
SELECT *
FROM user
WHERE
phone= #{phone}
</select>


<insert id="addUser">
INSERT INTO user (name,phone)
VALUES (#{name},#{phone})
</insert>

</mapper>
  1. 在你的数据库中增加user表,插入语句如下:
create table user
(
id bigint auto_increment
primary key,
name varchar(50) null,
phone varchar(20) null
);

此时完整的项目结构如图:

Intellij Idea创建基于Maven的SpringMVC+MyBatis项目

四 配置编译运行

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

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.3.RELEASE</spring.version>
</properties>

<dependencies>

<!--common start -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.5</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.4</version>
</dependency>

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
<!--common end -->

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

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</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-expression</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-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring end -->

<!--springmvc 控制层 start -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

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

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<!--springmvc end -->

<!--mybatis 数据访问层 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>

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

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.4.RELEASE</version>
</dependency>

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>
</dependency>

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>
</dependency>
<!--mybatis 数据访问层 end -->

</dependencies>

<build>
<finalName>MyBatisProject</finalName>

<resources>
<resource>
<!--directory: 资源所在的位置 -->
<directory>src/main/resources</directory>

<!--filtering: 是否替换资源中的属性placehold -->
<filtering>true</filtering>
</resource>
</resources>

</build>

</project>
  1. 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 xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">

<display-name>Archetype Created Web Application</display-name>

<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!--配置DispatcherServlet -->
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置SpringMVC需要加载的配置文件 spring-xxx.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<!--默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>


</web-app>
  1. index.vm中增加简单的显示语句即可:
<h2>SSM Test</h2>
  1. myatis-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>
<!--配置全局属性-->
<settings>
<!--使用jdbc的getGeneratekeys获取自增主键值-->
<setting name="useGeneratedKeys" value="true"/>

<!--使用列别名替换别名  默认true-->
<setting name="useColumnLabel" value="true"/>

<!--开启驼峰命名转换Table:create_time到 Entity(createTime)-->
<setting name="mapUnderscoreToCamelCase" value="true"/>

</settings>
</configuration>
  1. application.properties文件中配置数据库链接属性:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://XXX:3306/databaseName?useUnicode=true&characterEncoding=utf8
jdbc.username=XXX
jdbc.password=XXX

druid.pool.size.max=20
druid.pool.size.min=3
druid.pool.size.init=1
  1. spring-web.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:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>


<!--扫描web相关的controller-->
<context:component-scan base-package="com.zhaoyh.controller"/>

<!--简化配置:
1、自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
2、提供一系列:数据绑定,数字和日期的format,@NumberFormat,@DataTimeFormat,xml,json默认读写支持
-->

<mvc:annotation-driven/>

<!--静态资源默认servlet配置
1、加入对静态资源的处理:js,css,gif,png
2、允许使用"/"做整体映射
-->

<mvc:default-servlet-handler/>

<!--配置VM 显示ViewResolver-->
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/VM/" />
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="directive.foreach.counter.name">velocityCount</prop>
<prop key="directive.foreach.counter.initial.value">1</prop>
</props>
</property>
</bean>

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".vm" />
<property name="contentType"><value>text/html;charset=UTF-8</value></property>
</bean>


</beans>
  1. 在spring-storage.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"
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"
>


<!--1、配置数据库相关参数-->
<context:property-placeholder location="classpath:application.properties" ignore-unresolvable="true"/>

<!--2.数据源druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">

<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="${druid.pool.size.init}" />
<property name="minIdle" value="${druid.pool.size.min}" />
<property name="maxActive" value="${druid.pool.size.max}" />

<!-- 配置监控统计拦截的filters,wall用于防止sql注入,stat用于统计分析 -->
<property name="filters" value="wall,stat" />
</bean>

<!--3、配置SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>

<!--配置mybatis全局配置文件:mybatis-config.xml-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>

<!--扫描model包,使用别名,多个用;隔开-->
<property name="typeAliasesPackage" value="com.zhaoyh.model"/>

<!--扫描sql配置文件:mapper需要的xml文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>

</bean>

<!--4、配置扫描Storage接口包,动态实现Storage接口,注入到spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描的Storage接口-->
<property name="basePackage" value="com.zhaoyh.storage"/>
</bean>

</beans>
  1. 在spring-service.xml中配置service的一些属性:
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
>


<!--扫描service包(包含子包)下所有使用注解的类型-->
<context:component-scan base-package="com.zhaoyh.service"/>

<!--配置事务管理器(mybatis采用的是JDBC的事务管理器)-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!--配置基于注解的声明式事务,默认使用注解来管理事务行为-->
<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

Idea配置Tomcat并运行项目的过程可参考:[点我]
(http://blog.csdn.net/zyh920521/article/details/50596820)

至此完成了整个项目的创建和配置,下面就是你发挥的时间啦!

新版个人博客,已迁移至 zhaoyh’s blog,还请大家多多关照!