SSM,即SpringMVC+Spring+MyBatis+Maven,因为之前创建过一些Spring的小demo,相关的软件环境已经搭建完成,本以为搭建一个入门级的SSM项目应该不难,谁曾想这个过程中遇到了不少千奇百怪的问题,从开始创建到成功运行花了我整整一个下午的时间(我的午觉啊~~~·),最后项目成功跑起来的时候我长出了一口气,为了以后不在类似的事情上折腾,特此写下这篇文章记录一下搭建过程。
先准备好搭建项目的基本环境
Intellij IDEA:2018.1.1
JDK:1.8
Maven:3.6.0
Tomcat:7.0及以上
下载安装好软件后,在idea软件设置里做好JDK、Maven和Tomcat的相关环境配置,这方面网上的资料很多,本文就不介绍了。
搭建好环境后,打开idea,点击New - Project
找到Maven一栏,因为要搭建的SpringMvc项目,所以选择webapp模板
填写好GroupId和ArtifactId后,一步步next,最后finish完成
创建成功后,可以看到项目是这样的目录结构
除了配置相关依赖的pom.xml,目录中还有一个文件夹src,src的main目录提供了一个webapp文件夹,webapp文件夹下有一个WEB-INF文件夹,放置的是前端页面的文件,以及web.xml文件。
除了模版提供的目录结构,为了后面项目能成功运行,我们还需要添加一些文件夹,让项目的目录结构变成这样:
首先,先准备好数据库文件,并初始化一条记录
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`email` varchar(255) NOT NULL COMMENT '用户邮箱',
`username` varchar(255) NOT NULL COMMENT '用户昵称',
`role` varchar(255) NOT NULL COMMENT '用户身份',
`mobile` varchar(50) DEFAULT '' COMMENT '手机号码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf-8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '[email protected]', 'xjt', 'root', '15678635432');
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.0modelVersion>
<groupId>com.xjtgroupId>
<artifactId>mvcDemoartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>mvcDemo Maven Webappname>
<properties>
<srping.version>4.0.2.RELEASEsrping.version>
<mybatis.version>3.2.8mybatis.version>
<slf4j.version>1.7.12slf4j.version>
<log4j.version>1.2.17log4j.version>
<druid.version>1.0.9druid.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-oxmartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-expressionartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${srping.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.35version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.2version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
plugins>
build>
project>
注:以下四个配置文件都是放置在resources文件夹下
#日志输出级别
log4j.rootLogger=debug,stdout,D,E
#设置stdout的日志输出控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#输出日志到控制台的方式,默认为System.out
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,SSS} -[%p] method:[%c (%rms)] - %m%n
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
#数据库的用户名
username=root
#数据库的密码,别像我一样不设置
password=
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
这是Spring的核心配置文件,包括Spring结合Mybatis和数据源的配置信息
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.xjt.model"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.xjt.dao"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
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-3.0.xsd">
<context:component-scan base-package="com.xjt"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
该文件不是放在resources,而是webapp的WEB-INF文件夹下,文件内容如下:
<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>mvcDemodisplay-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
上面的配置文件编写好之后,其实我们就可以尝试着启动项目了,启动项目前先把applicationContext.xml的内容都注释了,然后就可以创建运行环境了。
点击idea右上角的 Edit Configurations...
选择Tomcat Server - Local,
编辑好项目的启动信息,包括项目名,jdk版本,tomcat以及端口
选择Deployment,添加Atifact,选择第二项,否则Tomcat运行会报错
保存后,启动项目,成功后在浏览器输入http://localhost:8080,返回结果如下:
这是index.jsp文件中的内容,因为index.jsp是启动页,所以项目启动后返回的结果是启动页的内容
<html>
<body>
<h2>Hello World!h2>
body>
html>
项目能跑起来,说明我们前端控制器的配置是成功的,接下来要做的是测试能否访问数据库。首先,把基本的类文件创建并编写好代码。
实体类:User.java
package com.xjt.model;
public class User {
private long id;
private String email;
private String mobile;
private String username;
private String role;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
dao文件:IUserDao
package com.xjt.dao;
import com.xjt.model.User;
public interface IUserDao {
User selectUser(long id);
}
mapper文件:UserDao.xml
位于resources - mapper文件夹下
xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.xjt.dao.IUserDao">
<select id="selectUser" resultType="User" parameterType="long">
SELECT * FROM user WHERE id = #{id}
select>
mapper>
service接口:IUserService
package com.xjt.service;
import com.xjt.model.User;
public interface IUserService {
public User selectUser(long userId);
}
UserServiceImpl
package com.xjt.service.impl;
import com.xjt.dao.IUserDao;
import com.xjt.model.User;
import com.xjt.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
public User selectUser(long userId) {
return userDao.selectUser(userId);
}
}
controller文件:UserController
package com.xjt.controller;
import com.xjt.model.User;
import com.xjt.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.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/select")
public ModelAndView selectUser() throws Exception {
ModelAndView mv = new ModelAndView();
User user = userService.selectUser(1);
mv.addObject("user", user);
mv.setViewName("user");
return mv;
}
}
UserController定义了一个方法selectUser
,读取id为1的User信息,并返回user.jsp页面,访问的路径是/user/select,user.jsp位于 WEB-INF 的 jsp 文件夹下,代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>usertitle>
head>
<body>
id:${requestScope.user.id}<br/>
email:${requestScope.user.email}<br/>
username:${requestScope.user.username}<br/>
role:${requestScope.user.role}<br/>
mobile:${requestScope.user.mobile}<br/>
body>
html>
都编写完毕以后,撤销applicationContext.xml文件的注释符号,然后开启项目,成功后在浏览器输入http://localhost:8080/user/select
页面成功的返回了User信息,说明,我们成功访问到了数据库的内容。
至此,SSM项目的搭建大功告成