创建web工程
用eclipse或idea创建一个web工程,在这里演示使用idea,项目命名为ssm
建立工程目录框架
根据习惯,简历包目录,分别为
config
在其中创建两个子包mybatis和spring,分别用来放置spring、mybatis配置文件 mapper
用来放置mybatis的mapper接口和mapper.xml service
service层的javabean controller
controller的javabean pojo
简单的POJO类

在WEB-INF下建立两个目录
lib
jar包目录 views
jsp视图目录

导入jar包
一共需要如下jar包
spring所有包 mybatis spring-mybatis整合包 aspectj jstl log4j c3p0 mysql

百度云下载 链接:http://pan.baidu.com/s/1dDB8cxV 密码:3cqp
添加mybatis配置文件
在config.mybatis下创建mybatis.xml配置文件,SSM整合和mybatis在不需要二级缓存等配置时,mybatis配置文件只需要一个框架,不需要书写具体内容,框架如下
添加spring和springmvc配置文件
springmvc
在config.spring下创建springmvc.xml文件,用来配置springmvc
applicationContext-dao.xml
在config.spring下创建applicationContext-dao.xml文件,用来配置DAO层的内容,在这里连接数据库的数据源使用C3P0,所以在这之前先在config中添加db.properties来指定数据库连接信息
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = root
applicationContext-dao.xml内容:
applicationContext-service.xml
在config.spring中添加applicationContext-service.xml,用来把service层的javabean注入到IOC容器中
applicationContext-transtion.xml
在config.spring中添加applicationContext-transtion.xml,用来配置AOP事务
添加log4j配置文件
为了方便mybatis的调试,使用log4j作为日志输出,在src根目录中添加log4j.properties
log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
修改web.xml文件
web.xml需要实现三个功能
配置spring文件
contextConfigLocation
classpath:cn/elinzhou/OrderSpringMVC/config/spring/applicationContext-*.xml
org.springframework.web.context.ContextLoaderListener
配置springmvc中的前端控制器
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:cn/elinzhou/OrderSpringMVC/config/spring/springmvc.xml
1
dispatcher
/
解决post乱码问题
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
CharacterEncodingFilter
/*
创建pojo类
这里使用一张用户表做示例,表结构如下
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`sex` char(1) default NULL COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
根据表结构建立POJO类
package cn.elinzhou.OrderSpringMVC.pojo;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
}
创建mapper