环境: jdk1.8 maven3.4
- new 一个project,这里我们选择最普通的maven项目这里我打算将此工程作为一个父项目来处理,也就是说我们只需要它的一个大体的框架和相关依赖,因此删除它的src目录
父项目搭建完成 - 引入相关依赖文件,直接复制粘贴进去
<!-- 规范使用jar包的版本 -->
<properties>
<spring.version>5.1.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- springwebmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring 整合Jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring-test spring测试包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring面向切面编程 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 返回json字符串的支持 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- 处理文件上传 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!--MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- MyBatis整合Spring的适配包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--引入pageHelper分页插件 PageInfo -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!-- 阿里巴巴 数据源 druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- jstl jsp标签库包 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- servlet api包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- junit 测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 日志包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- 阿里巴巴的fastjson json和java 快速转换工具包-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- excel 批量的导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
<!--build中配置resources,防止资源导出失败-->
<build>
<resources>
<resource>
<directory>src/main/reources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
确保我们的文件能够正确载入
- 在父项目的基础上新建子模块,在原工程上右键new module
还是最简单的maven项目
完成 - 但很显然这算不上一个web项目,于是我们载入支持。
但项目还缺少lib目录,我们去右上角给它建立lib目录
5.紧接着去项目的src目录,我们发现resources目录不符合规范,手动将其配置成资源目录。
配置完成后我们建立对应的结构,已知项目下需要spring配置,mybatis配置,springmvc配置,日志,properties文件,而且还希望mapper的xml在这里,所以我们需要建立三个文件夹,两个文件。
然后我们建立一个config.properties文件,内容如下,数据库和密码需要填写自己的。
内容:
#############################\u6570\u636E\u6E90\u76F8\u5173\u914D\u7F6E########################################
url:jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
driverClassName:com.mysql.jdbc.Driver
jdbc_username:root
jdbc_password:root
filters:stat
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
timeBetweenEvictionRunsMillis:60000
minEvictableIdleTimeMillis:300000
validationQuery:SELECT 'x'
testWhileIdle:true
testOnBorrow:false
testOnReturn:false
maxOpenPreparedStatements:20
removeAbandoned:true
removeAbandonedTimeout:1800
logAbandoned:true
再按照刚才的步骤建立log4j.properties文件,内容如下:
# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
接下来本应该配置spring一系列,但考虑到配置的时候要装载上包扫描,所以我们先把对应的搭建结构整出来。
接下来我么建立spring配置文件,在spring 文件夹下,这里取为beans_core.xml
内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<!-- 开启注解模式 -->
<context:annotation-config/>
<!-- 扫描注解包 @Service @Repository @Comment -->
<context:component-scan base-package="com.ssm">
<!-- 忽略扫描@Controller注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<!-- 数据库连接池对象 -->
<context:property-placeholder location="classpath:config.properties"></context:property-placeholder>
<!--
阿里 druid数据库连接池
c3p0 dbcp .... 任意选择连接池技术
Connnection con
-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 数据库基本信息配置 -->
<property name="url" value="${url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<property name="driverClassName" value="${driverClassName}" />
<property name="filters" value="${filters}" />
<!-- 最大并发连接数 -->
<property name="maxActive" value="${maxActive}" />
<!-- 初始化连接数量 -->
<property name="initialSize" value="${initialSize}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${maxWait}" />
<!-- 最小空闲连接数 -->
<property name="minIdle" value="${minIdle}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="${removeAbandoned}" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="${logAbandoned}" />
</bean>
<!--
spring 整合mybatis 使用的工具类
将其他的技术加载到spring框架上 ,完成业务开发
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds"></property>
<!-- 扫描我们制定目录下的mapper.xml文件
EmployeeMapper.xml
DeptMpper.xml
-->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property>
<!-- mybatis 提供的分页插件的配置 引入pagehelper分页插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
helperDialect=mysql
reasonable=true
supportMethodsArguments=true
params=count=countSql
autoRuntimeDialect=true
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- 加载我们的mapper xml 和 mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- setBasePackage(String) -->
<property name="basePackage" value="com.ssm.mapper"></property>
</bean>
<!-- 引入spring提供的事务管理 -->
<bean id="tm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<tx:annotation-driven transaction-manager="tm"/>
</beans>
如果刚才建立的包结构跟我的是不一样的,需要在第20行和第100行将包扫描修改成自己的。
同时建立springmvc文件夹下的springmvc.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:p="http://www.springframework.org/schema/p"
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-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- 扫描哪些包 @Controller -->
<context:component-scan base-package="com.ssm.controller" />
<!-- 开启springmvc的注解操作 -->
<mvc:annotation-driven/>
<!-- 将dispatcherServlet 不能处理的请求推给 默认servlet执行 -->
<mvc:default-servlet-handler />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 注意:CommonsMultipartResolver的id是固定不变的,一定是multipartResolver,不可修改 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 如果上传后出现文件名中文乱码可以使用该属性解决 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 单位是字节,不设置默认不限制总的上传文件大小,这里设置总的上传文件大小不超过10M(10*1024*1024) -->
<property name="maxUploadSize" value="10485760"/>
<!-- 跟maxUploadSize差不多,不过maxUploadSizePerFile是限制每个上传文件的大小,而maxUploadSize是限制总的上传文件大小 -->
<property name="maxUploadSizePerFile" value="10485760"/>
</bean>
</beans>
如果包不一样记得修改:
接着是mybatis文件夹,文件夹下建立一个mapper文件夹用来存xml文件,再建立一个mybatis配置文件,这里叫sqlMapConfig.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>
同时别忘记去修改web.xml文件。
内容如下,直接粘贴进去:
<!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/beans_core.xml</param-value>
</context-param>
<!-- 监听我们加载的配置文件是否有异常问题 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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:springmvc/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring 提供了一个字符编码过滤器 Filter -->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
这样一来大体的文件配置就完成了。
- 然后根据数据库去配置实体类和接口等,java目录下的结构如下
实体类:
package com.ssm.pojo;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String name;
private String pwd;
public User() {
super();
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
Controller:
package com.ssm.controller;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/selectUser")
@ResponseBody
public List<User> selectUser(){
List<User> users = userService.selectUser();
return users;
}
}
Service接口:
package com.ssm.service;
import com.ssm.pojo.User;
import java.util.List;
public interface UserService {
public List<User> selectUser();
}
ServiceImpl实现类:
package com.ssm.service;
import com.ssm.mapper.UserMapper;
import com.ssm.pojo.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> selectUser() {
return userMapper.selectUser();
}
}
mapper接口:
package com.ssm.mapper;
import com.ssm.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectUser();
}
resources下mapper文件夹建立mapper.xml文件
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.ssm.mapper.UserMapper">
<select id="selectUser" resultType="com.ssm.pojo.User">
select * from mybatis.user
</select>
</mapper>
这算完整的配置好了项目。
- 于是我们准备一下配置好tomcat跑项目。
最后访问我们的接口,出现数据。