java使用idea搭建ssm+maven框架项目,单model,精简配置
前言:最近跟着Gerry老师学习了使用idea搭建ssm+maven框架项目,学完后才发现以前自己使用eclipse搭建的ssm+maven框架有多么乱,至于配置等等更不用说,大都不怎么理解,只知道在网上百度复制粘贴,至于为啥这么配不知道,所以这次重新学习了搭建这个框架感觉收获挺大的,整个配置都是老师手敲的,原理也大都说明了,高手就是不一样。。
注意:我这里搭建的只是一个简单demo,就创建了一个model,多model后面再来。需要下载demo请到最后处。
这里可以是一个完整的ssm框架小demo。
目录
- 创建空mavenweb项目
- 修改pom.xml,添加依赖
- 创建数据库配置文件
- 创建spring+springmvc配置文件
- 创建mybatis配置文件
- 修改web.xml配置文件
- 创建项目包
- 使用mybatis工具生成tk通用模板代码
- 测试
整个项目的目录结构
这里就直接贴配置了,为啥这么配置有注释,其他没解释的其他途径学习,原理的话也不好说了。。
1、创建空mavenweb项目
参考:idea创建空mavenweb项目,从创建项目到创建model,再到tomcat发布测试
2、修改pom.xml,添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<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.gx.ssm</groupId>
<artifactId>ssmdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssmdemo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring-mvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!--事务管理依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!--使用aop方式管理和控制事务-->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!--mybatis通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
<!--spring-mybatis[把mybatis的mapper接口生成代理实现类交给spring容器统一管理]-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--数据库和数据库连接池-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<!--web-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</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>
<!--mybatis插件-->
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!-- generator 工具配置文件的位置 -->
<configurationFile>src/main/resources/generatorConfiguration.xml</configurationFile>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!--允许覆盖生成的文件 -->
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
3、创建数据库配置文件datasource.properties
# 连接数据库
jdbc.driver_class = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/testdb?useSSL=true
jdbc.username = root
jdbc.password = root
# 配置连接池
# 初始化连接数
initialSize = 4
# 最大连接数
maxActive = 20
# 最小连接数
minIdle = 2
# 等待时间
maxWait = 2000
# 检查连接是否有效
testOnBorrow = true
4、创建spring+springmvc配置文件,这里分多个文件,便于维护
(1)、spring-datasource.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">
<!--加载数据源配置文件-->
<context:property-placeholder location="classpath:datasource/datasource.properties" />
<!--整合数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver_class}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxWait" value="${maxWait}"/>
<property name="testOnBorrow" value="${testOnBorrow}"/>
</bean>
</beans>
(2)、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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--把tk.mybatis中mapper接口生成的代理对象交给spring容器管理-->
<bean id="mapperScanner" class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描需要生成代理对象所有接口的包路径-->
<property name="basePackage" value="com.gx.mapper"/>
</bean>
<!--把mybatis整合到spring容器管理-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--使用数据源dataSource-->
<property name="dataSource" ref="dataSource"/>
<!--把mybatis所有mapper映射配置文件整合到sqlSessionFactory对象中-->
<property name="mapperLocations" value="classpath:mybatis/mappers/*Mapper.xml"/>
<!--插件配置-->
<!--<property name="plugins">
<props>
<prop key=""/>
</props>
</property>-->
</bean>
</beans>
(3)、spring-service.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">
<!--扫描所有的service-->
<context:component-scan base-package="com.gx.service"/>
</beans>
(4)、spring-tx.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务传播性-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--service中的方法命名规范-->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="SUPPORTS"/>
<tx:method name="find*" propagation="SUPPORTS"/>
<tx:method name="list*" propagation="SUPPORTS"/>
<tx:method name="*" read-only="true" propagation="SUPPORTS" rollback-for="com.gx.common.base.exception.BaseBusinessException"/>
</tx:attributes>
</tx:advice>
<!--组装事务传播和切入点-->
<aop:config>
<!--impl包下的所有类所有方法-->
<aop:pointcut id="pcut" expression="execution(* com.gx.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pcut"/>
</aop:config>
</beans>
(5)、spring-context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--用于管理spring容器相关配置文件(有顺序)-->
<import resource="spring-datasource.xml" />
<import resource="spring-mybatis.xml" />
<import resource="spring-service.xml" />
<import resource="spring-tx.xml" />
</beans>
(6)、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"
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包下所有类的实例交给spring管理-->
<context:component-scan base-package="com.gx.controller"/>
<!--开启mvc所有注解配置-->
<mvc:annotation-driven />
<!--配置jsp视图解析器-->
<bean id="viewResoler" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
5、创建mybatis配置文件,这个是工具,生成代码的,使用的是tk通用模板
(1)、mybatisGeneratorinit.properties
# Mybatis Generator configuration
# 数据库连接配置
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/testdb
jdbc_user=root
jdbc_password=root
# 通用生成插件
mapper.plugin=tk.mybatis.mapper.generator.MapperPlugin
# dao类和实体类的根的位置
project=src/main/java
# 生成实体类位置
mapper.entityPackage=com.gx.entity
# mapper-xml文件的位置
resources=src/main/resources/mybatis
# 指定生成的Mapper文件继承的接口
mapper.Mapper=com.gx.common.base.mapper.BaseMapper
# 生成接口mapper位置
mapper.mapperPackage=com.gx.mapper
(2)、generatorConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="mybatisGeneratorinit.properties"/>
<!-- 一个数据库一个context -->
<!--defaultModelType="flat" 大数据字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true" />
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8" />
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<!-- 添加序列化 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!-- 添加toString方法 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 通用mapper插件 -->
<plugin type="${mapper.plugin}">
<property name="mappers" value="${mapper.Mapper}"/>
</plugin>
<!-- 注释 -->
<commentGenerator >
<property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="${mapper.entityPackage}" targetProject="${project}" >
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mappers" targetProject="${resources}" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口mapper -->
<javaClientGenerator targetPackage="${mapper.mapperPackage}" targetProject="${project}" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
<table tableName="tb_book" domainObjectName="Book">
<!-- 数据库表主键 -->
<generatedKey column="bookId" sqlStatement="Mysql" identity="true" />
</table>
</context>
</generatorConfiguration>
6、修改web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--配置编码格式过滤器-->
<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>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--配置路径-->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--指定配置文件位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--当web容器实例化时也实例化spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-context.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
7、创建项目包,以下只是简单创建一部分测试用的包
(1)、BaseBusinessException.java,这个是配置业务异常的
package com.gx.common.base.exception;
/**
* 各个模块中所有自定义业务异常的父类
*/
public class BaseBusinessException extends RuntimeException {
public BaseBusinessException() {
super();
}
public BaseBusinessException(String message) {
super(message);
}
public BaseBusinessException(String message, Throwable cause) {
super(message, cause);
}
public BaseBusinessException(Throwable cause) {
super(cause);
}
protected BaseBusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
(2)、BaseMapper.java,这个是所有mapper接口需要继承的
package com.gx.common.base.mapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.special.InsertListMapper;
public interface BaseMapper<T> extends Mapper<T>,InsertListMapper<T> {
}
(3)、Book.java和BookMapper.java是工具生成的,Book.java我这里使用注解转化了时间格式
@Column(name = "book_date")
@JsonFormat(pattern = "yyyy-MM-dd")
private Date bookDate;
(4)、BookService.java,service接口
package com.gx.service;
import com.gx.entity.Book;
import java.util.List;
public interface BookService {
List<Book> getBooks();
}
(5)、BookServiceImpl.java,service实现类
package com.gx.service.impl;
import com.gx.entity.Book;
import com.gx.mapper.BookMapper;
import com.gx.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public List<Book> getBooks() {
return bookMapper.selectAll();
}
}
(6)、BookController.java,控制器,这里写两个方法,一个是测试跳转页面,一个是获取json数据
package com.gx.controller;
import com.gx.entity.Book;
import com.gx.service.BookService;
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.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/test")
public String test(){
return "test";
}
@RequestMapping("/list")
@ResponseBody
public List<Book> getBooks(){
return bookService.getBooks();
}
}
8、使用mybatis工具生成tk通用模板代码,确认数据库,生成包路径等等配置都没问题后,双击一下即可生成代码,
需要注意:得先mysql数据库创建表,表名啊,字段什么的随便定义啦。
生成的文件有下面3处,我这里是就生成一个表的
9、测试,至于怎么发布到tomcat上,在上面创建空mavenweb项目那个博客已经说明。
在WEB-INF目录下创建了个jsp文件夹,再创建了个test.jsp页面。
运行项目后
(1)、在Chrome地址栏输入:http://localhost:8080/book/list,查看到json数据
(2)、在Chrome地址栏输入:http://localhost:8080/book/test,查看到跳转到了test.jsp页面,这个是放在WEN-INF目录jsp文件夹下的
ok,以上就是我的搭建过程。