话说:
各位读者盆友,晚上好!很早之前用普通Web项目总结过SSM整合流程(Spring+SpringMVC+MyBatis),当时的jar包是手动添加进去的;
今天总结用Maven整合SSM框架。
但是最终部署Tomcat出了个大大的bug,搞不定~所以下一篇博客专门悬赏处理这个Bug哈,欢迎评论留言,感激不尽。
目录
1)新建Maven项目 整体结构
2)完善依赖pom.xml
3)配置文件
4)后端代码
pojo dao controller service
5)测试
测试后端
测试前端
6)总结
难度系数:★★★☆☆
建议用时:1H
1)新建Maven项目 整体结构
2)完善依赖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.0modelVersion>
<groupId>com.hmc.demogroupId>
<artifactId>p2pFront2artifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>p2pFront2 Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<spring.version>4.3.14.RELEASEspring.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.10.0version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.45version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>javax.servlet.jsp.jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
dependencies>
<build>
<finalName>p2pFront2finalName>
build>
project>
3)配置文件
spring.xml
连接数据库
把连接数据库和mapper.xml交给工厂管理
orm配置
springmvc.xml
扫描包及视图控制器
mybatis *.mapper.xml
写SQL语句
web.xml
把Spring交给web管理(Listener)
springMVC核心
log4j.properties
## %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
## %r 输出自应用启动到输出该log信息耗费的毫秒数
## %c 输出所属的类目,通常就是所在类的全名
## %t 输出产生该日志事件的线程名
## %n 输出一个回车换行符,Windows平台为“rn”,Unix平台为“n”
## %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921
## %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java:10)
### 设置###
log4j.rootLogger = debug,stdout
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = INFO
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=d://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = d://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=d://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =d\://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
### mybatis 显示SQL语句部分
log4j.logger.org.mybatis=DEBUG
#log4j.logger.cn.tibet.cas.dao=DEBUG
#log4j.logger.org.mybatis.common.jdbc.SimpleDataSource=DEBUG#
#log4j.logger.org.mybatis.common.jdbc.ScriptRunner=DEBUG#
#log4j.logger.org.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG#
#log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_p2p
jdbc.username=root
jdbc.password=119913
spring.xml
<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:component-scan base-package="com.hmc">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller "/>
context:component-scan>
beans>
spring-db.xml
<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:db.properties"/>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}">property>
<property name="url" value="${jdbc.url}">property>
<property name="username" value="${jdbc.username}">property>
<property name="password" value="${jdbc.password}">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource">property>
<property name="mapperLocations" value="classpath:mybatis/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
<property name="basePackage" value="com.hmc.dao">property>
bean>
beans>
springmvc.xml
<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">
<mvc:annotation-driven/>
<context:component-scan base-package="com.hmc.controller">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
bean>
beans>
UserMapper.xml
这个放在后端代码比较合适
web.xml
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring.xml,classpath:spring-db.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
4)后端代码
pojo dao controller service
pojo -User
package com.hmc.pojo;
import org.springframework.stereotype.Repository;
/**
*
*2018年3月10日
*User:Meice
*下午7:13:45
*/
public class User {
/**
* userId varchar(50),
userName varchar(50) not null,
userNick varchar(50)comment '昵称',
password varchar(50),
phone varchar(50),
status int,
type int,
registerTime datetime,
lastLoginTime datetime,
detail int comment '用户信息详情',
property int comment '用户资产关联表'
*/
private String userId;
private String userName;
private String userNick;
private String password;
public User() {}
public User(String userId, String userName, String userNick, String password) {
super();
this.userId = userId;
this.userName = userName;
this.userNick = userNick;
this.password = password;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserNick() {
return userNick;
}
public void setUserNick(String userNick) {
this.userNick = userNick;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", userNick=" + userNick + ", password=" + password
+ "]";
}
}
dao
package com.hmc.dao;
/**
*
*2018年3月10日
*User:Meice
*下午7:15:51
*/
import java.util.List;
import com.hmc.pojo.User;
public interface UserDao {
//查询用户列表
List userList ();
}
UserMapper.xml
<mapper namespace="com.hmc.dao.UserDao">
<sql id="column_name">userId,userName,userNick,passwordsql>
<sql id="table_name">usersql>
<select id="userList" resultMap="userMap">
SELECT
<include refid="column_name"/>
FROM
<include refid="table_name"/>
select>
<resultMap type="com.hmc.pojo.User" id="userMap">
<id column="userId" property="userId" javaType="String"/>
<result column="userName" property="userName" javaType="String"/>
<result column="userNick" property="userNick" javaType="String"/>
resultMap>
mapper>
service
package com.hmc.service;
import java.util.List;
import com.hmc.pojo.User;
/**
*
*2018年3月10日
*User:Meice
*下午7:30:10
*/
public interface UserService {
//查询用户列表
List userList ();
}
serviceImpl
package com.hmc.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hmc.dao.UserDao;
import com.hmc.pojo.User;
/**
*
*2018年3月10日
*User:Meice
*下午7:30:33
*/
@Service("userService")
public class UserServiceImpl implements UserService {
//调用Dao层方法
@Autowired
public UserDao userDao;
public List userList() {
return userDao.userList();
}
}
controller
package com.hmc.controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import com.hmc.pojo.User;
import com.hmc.service.UserService;
/**
*
*2018年3月11日
*User:Meice
*上午2:44:52
*/
@Controller
public class UserController {
public Logger log = Logger.getLogger(this.getClass());
@Resource(name="userService")
public UserService userService;
public String userList(Model model) {
List userList = userService.userList();
model.addAttribute("userList", userList);
log.info("前台查询数据为:"+userList);
return "userList";
}
}
5)测试
测试后端
测试前端
测试后端-TestUserList
package p2pFront2;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hmc.pojo.User;
import com.hmc.service.UserService;
/**
*
*2018年3月10日
*User:Meice
*下午7:13:26
*/
//查询用户列表 单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:spring.xml","classpath:spring-db.xml"})
public class TestUserList {
public Logger log = Logger.getLogger(this.getClass());
@Resource(name="userService")
public UserService userService;
@Test
public void testUserList() {
log.info("=-=====测试用户列表================");
List userList = userService.userList();
log.info("用户列表为:"+userList);
}
/**
* 测试结果:
* [INFO ] 2018-03-11 02:26:35,339 method:p2pFront2.TestUserList.testUserList(TestUserList.java:40)
用户列表为:[User [userId=b5ccf611-66a6-4f6a-b65c-7a5e24a79d11, userName=user1, userNick=用户1, password=111111], User [userId=e042d140-b90a-4193-8295-6d2109fc80af, userName=user
*/
}
测试成功!But….前端出了问题…
测试前端
Tomcat启动报错....
ERROR SqlExceptionHelper Cannot create PoolableConnectionFactory (Unknown database 'meice_blog')
ERROR ContextLoader Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'blogAction':
下一篇博客专门悬赏处理这个bug,以为我的项目根本不存在这个meice_blog?太古怪了!!
6)总结
1.不用记住怎么配置,关键是配置之间的关系;
2.maven单元测试报java.lang.IllegalStateException: Failed to load ApplicationContext
casued by cannot create bean “”,”“’
表明spring工厂创建有问题,原因很多,主要看caused by .一般caused by 原因也一大串,怎么办?一般有以下原因:
1)配置文件有问题:applicationConfig.xml mapper.xml
1)查看凡是这里面的name属性,要完全按照你引用的类中定义的属性来写!不能自作主张,因为你用人家的类,就要乖乖用人家命名好的属性。怎么查看属性?直接双击打开类,查找即可。有继承关系的,继续往上找;
2)
加载文件的,要用classpath:把路径写对
3)mapper.xml 中要写对。
中的namespace要指定,确保唯一的方法;
手动映射时候: 数据库列;pojo属性及javaType或者jdbcType;如果是一对多,用ofType不要遗漏。
2)文件路径找不到 classpath:spring.xml
如果是多个文件:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:spring.xml","classpath:spring-db.xml"})
未完待续……下一篇悬赏处理前端部署Tomcat的Bug~
晚安~~ . 再会!