近期整合了一下SSM框架,在整合的过程参考的不少别人的博客,但是遇到了不少的坑,在整合的过程中还要感谢Chinack
的大牛指点才顺利整合完,今天将整合的过程遇到的坑和整合成功的代码和经历分享出来,新人可以学习,高手请指点,最后附上源码。
我个人比较喜欢用IDEA开发工具开,开发工具不关事,看个人喜欢。
在IDEA新建一个maven项目,项目默认会有一个webapp的目录,java、resources目录需要手动新建上去,整体项目目录结构如下。
在pom.xml添加依赖,省去了添加jar包的麻烦,直接用IDEA打开会自动下载所有的jar包。
<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.wip.ssmgroupId>
<artifactId>ssmartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>ssm Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
<spring.version>4.0.2.RELEASEspring.version>
<mybatis.version>3.2.6mybatis.version>
<slf4j.version>1.7.7slf4j.version>
<log4j.version>1.2.17log4j.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-oxmartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.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>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.36version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.1.41version>
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>org.codehaus.jacksongroupId>
<artifactId>jackson-mapper-aslartifactId>
<version>1.9.13version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.9version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.7version>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.0.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.7.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.20.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.0version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
首先明白一点javaweb项目都是基于一个叫web.xml的文件作为入口文件,我们先来分析这个文件,一般会在EWB-INF目录下。
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>SSM Web Applicationdisplay-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
context-param>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<async-supported>trueasync-supported>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-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>
<error-page>
<error-code>404error-code>
<location>/error/404location>
error-page>
<error-page>
<error-code>400error-code>
<location>/error/400location>
error-page>
<error-page>
<error-code>500error-code>
<location>/error/500location>
error-page>
web-app>
<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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<import resource="spring-mybatis.xml"/>
<context:component-scan base-package="com.wip"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/static/image/**" location="/static/image/" />
<mvc:resources mapping="/static/css/**" location="/static/css/" />
<mvc:resources mapping="/static/js/**" location="/static/js/" />
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8value>
list>
property>
bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
list>
property>
bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
<property name="resolveLazily" value="true"/>
bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
配置到这里springMVC差不整合完毕,能够正常通过请求返回jsp页面。以及静态文件的使用。当我在web.xml文件上加入spring-mybatis.xml文件的时候一直加载不进去,最后发现放到web.xml文件中加载spring-mybatis.xml没有加载到。
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mybatis.xmlparam-value>
context-param>
具体的错误信息如下
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userController': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could
not autowire field: private com.wip.service.UserService
com.wip.controller.UserController.userService; nested exception
is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userServiceImpl': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could
not autowire field: private com.wip.dao.UserDao
com.wip.service.impl.UserServiceImpl.userDao; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException
: No qualifying bean of type [com.wip.dao.UserDao] found for
dependency: expected at least 1 bean which qualifies as
autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
错误的意思就是说创建bean的时候发生异常。
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
contextConfigLocation
classpath:spring-mybatis.xml
<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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxWait" value="${maxWait}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wip.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
beans>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java_test
username=root
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
到此SSM框架基本上算是搭建完成。
首先创建一张用户表,用户表可以自定义,看自己喜欢。
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '邮箱',
`is_active` tinyint(4) NOT NULL DEFAULT 1 COMMENT '是否激活',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `username`(`username`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
在model包里面创建一个用户model,每个属性必须以数据表里的字段一样,否则获取的时候会出问题。
public class UserModel {
private Integer id;
private String username;
private String password;
private String email;
private String is_active;
// get set省略
}
创建用户dao接口
import com.wip.model.UserModel;
import java.util.List;
public interface UserDao {
/**
* 获取所有用户
* @return
*/
List<UserModel> findUserList();
}
用户mapper层映射文件
<mapper namespace="com.wip.dao.UserDao">
<sql id="BASE_TABLE">
t_user
sql>
<select id="findUserList" resultType="com.wip.model.UserModel">
SELECT
*
FROM
<include refid="BASE_TABLE"/>
select>
mapper>
用户服务层service接口
import com.wip.model.UserModel;
import java.util.List;
public interface UserService {
/**
* 获取所有用户信息
* @return
*/
List<UserModel> getUserList();
}
用户service接口实现类,注意实现类需要加上@Service注解,注入给bean。
import com.wip.dao.UserDao;
import com.wip.model.UserModel;
import com.wip.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<UserModel> getUserList() {
return userDao.findUserList();
}
}
用户controller层
import com.wip.model.UserModel;
import com.wip.service.UserService;
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.bind.annotation.ResponseBody;
import java.util.*;
@Controller
@RequestMapping(value = "/index")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "")
public String index() {
return "index";
}
@RequestMapping(value = "/json", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> json() {
Map<String, Object> map = new HashMap<>();
List<UserModel> users = userService.getUserList();
map.put("success", "返回成功");
map.put("code", 200);
map.put("data",users);
return map;
}
}
最后运行项目访问地址: http://localhost:8080/index/。
源码 github:https://github.com/caozongpeng/ssm
如果此项目可以帮到你请帮忙Star
虽然磕磕绊绊整合也差不多两天,在整合的过程中确实可以发现不少的问题。只有动手做了才知道到底是正确的还是错误,虽然看着别人的代码感觉整合也就这样,但是真正做起来就会遇到很多很多问题。不踩坑永远不知道这些东西是正确的还是对的,虽然是整合成功了,但是很多原理也根本不知道是怎么回事,不卑不亢,继续加油。