SSM
SSM 应用搭建
1. 部署 Spring + Spring MVC
- 导入包
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql-connector-java</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
- 配置Spring MVC的前端控制器 web.xml:
<servlet>
<description></description>
<display-name>DispatcherServlet</display-name>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Spring 配置文件存在conf 文件夹中,并且其文件名符合spring-*.xml 规则。
- 添加数据库连接参数文件 conf/db.properties
url=jdbc:mysql://localhost:3306/tedustore
driver=com.mysql.jdbc.Driver
user=root
password=root
initsize=1
maxsize=5
- 添加数据库连接池配置文件 spring-db.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- conf/spring-db.xml 用于管理数据库的连接 -->
<!-- 读取conf/db.properties -->
<util:properties id="dbConfig"
location="classpath:conf/db.properties" />
<!-- 配置DBCP所需的Bean -->
<!-- 各property中的name以类中的set方法名称为准 -->
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="#{dbConfig.driver}"/>
<property name="url"
value="#{dbConfig.url}"/>
<property name="username"
value="#{dbConfig.user}"/>
<property name="password"
value="#{dbConfig.password}"/>
<property name="initialSize"
value="#{dbConfig.initsize}"/>
<property name="maxActive"
value="#{dbConfig.maxsize}"/>
</bean>
</beans>
- 添加 Spring MVC 配置文件 spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- conf/spring-mvc.xml 用于管理MVC的配置 -->
<context:component-scan
base-package="cn.tedu.spring" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
- 部署测试...
2. 部署 Spring MyBatis
-
导入包(略)
-
添加Spring MyBatis配置文件 spring-mybatis.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- conf/spring-mybatis.xml 用于管理MVC的配置 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds"/>
<!--
<property name="mapperLocations"
value="classpath:mapping/*.xml"/> -->
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory"
ref="sqlSessionFactory"/>
<property name="basePackage"
value="cn.tedu.store.dao"/>
</bean>
</beans>
其中mapperLocations属性被临时注释掉了,再以后有Mapper文件以后打开。
- 利用 JUnit 进行离线测试:
public class MyBatisTest {
ClassPathXmlApplicationContext ctx;
@Before
public void init() {
ctx = new ClassPathXmlApplicationContext("conf/spring-db.xml","conf/spring-mybatis.xml");
}
@Test
public void testSqlSession() {
SqlSessionFactory factory = ctx.getBean("sqlSessionFactory", SqlSessionFactory.class);
SqlSession session = factory.openSession();
System.out.println(session);
session.close();
}
}
实现用户列表功能
原理:
![](https://img.haomeiwen.com/i4623185/faad12b1015b6adc.png)
1. 数据层
实现步骤:
- 数据表结构:
desc user;
+-------------+-------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(20) | YES | | NULL | |
| password | varchar(30) | YES | | NULL | |
| email | varchar(20) | YES | | NULL | |
| mobile | varchar(20) | YES | | NULL | |
| create_time | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+-------------+------+-----+-------------------+-----------------------------+
- 添加实体类 User
public class User implements Serializable {
private static final long serialVersionUID = -7291170424207323214L;
private Integer id;
private String username;
private String password;
private String mobile;
private String email;
private Date createTime;
public User() {
}
public User(Integer id, String username, String password, String mobile, String email, Date createTime) {
super();
this.id = id;
this.username = username;
this.password = password;
this.mobile = mobile;
this.email = email;
this.createTime = createTime;
}
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;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", mobile=" + mobile
+ ", email=" + email + ", createTime=" + createTime + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
- 声明Dao接口
public interface UserDao {
/**
* 查询全部的用户信息
* @return 用户信息列表
*/
List<User> findAllUsers();
}
- 添加映射配置文件 mapping/userMapper.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="cn.tedu.store.dao.UserDao">
<!-- mapping/userMapper.xml 映射文件 -->
<!--
result: 结果
parameter: 参数
type: 类型
resultType: 用于声明方法的返回结果元素的类型
parameterType: 参数的类型,当方法只有一个参数时候使用!
如果有更多个参数建议使用 @Param 注解标注
-->
<select id="findAllUsers"
resultType="cn.tedu.store.bean.User">
select
id,
username,
password,
mobile,
email,
create_time as createTime
from
user
</select>
</mapper>
-
更新db.properties
url=jdbc:mysql://localhost:3306/tedustore
-
更新 spring-mybatis.xml
<property name="mapperLocations" value="classpath:mapping/*.xml"/>
- 利用JUnit进行离线测试
public class UserDaoTest {
ClassPathXmlApplicationContext ctx;
UserDao dao;
@Before //在全部测试案例之前执行的方法
public void init(){
ctx = new ClassPathXmlApplicationContext(
"conf/spring-db.xml",
"conf/spring-mybatis.xml");
dao = ctx.getBean("userDao",UserDao.class);
}
@After //全部测试案例执行之后执行 destory方法
public void destory(){
ctx.close();
}
@Test
public void testFindAllUsers(){
List<User> list=dao.findAllUsers();
for (User user : list) {
System.out.println(user);
}
}
}
2. 业务层
步骤
- 声明业务层接口
public interface UserService {
/**
* 获取全部用户信息
* @return 用户信息
*/
List<User> list();
}
- 实现业务层
@Service("userService") //当前类是业务层组件
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public List<User> list() {
//调用数据层处理业务
return userDao.findAllUsers();
}
}
- 添加配置文件 spring-service.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- conf/spring-service.xml 用于管理业务层 -->
<context:component-scan base-package="cn.tedu.store.service" />
</beans>
- 测试:
public class UserServiceTest {
ClassPathXmlApplicationContext ctx;
UserService service;
@Before
public void init(){
ctx=new ClassPathXmlApplicati onContext(
"conf/spring-service.xml",
"conf/spring-mybatis.xml",
"conf/spring-db.xml");
service = ctx.getBean("userService",
UserService.class);
}
@After
public void destory(){
ctx.close();
}
@Test
public void testList(){
List<User> list=service.list();
for (User user : list) {
System.out.println(user);
}
}
}
3. 控制器 和 界面
- 添加控制器类
/**
* 控制器,用于处理用户有关的业务功能
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/users.do")
public String users(ModelMap map){
//访问业务层获取全部用户信息
List<User> list=userService.list();
map.put("users", list);
//System.out.println(list);
//转发到JSP页面,显示结果
return "user/list";
}
}
- 重用Servlet项目的界面
![](https://img.haomeiwen.com/i4623185/fe878576d83af04d.png)
- 测试
![](https://img.haomeiwen.com/i4623185/27d6e27b2730411b.png)
翻页功能
原理:
1. 重构数据层
- 重构Dao接口, 添加翻页参数和行数统计方法
/**
* 查询全部的用户信息
* @return 用户信息列表
*/
List<User> findAllUsers(
@Param("start") int start,
@Param("size") int size);
/**
* 统计用户的数量
*/
int countUsers();
- 在 userMapper.xml 中声明SQL
<select id="findAllUsers"
resultType="cn.tedu.store.bean.User">
select
id,
username,
password,
mobile,
email,
create_time as createTime
from
user
limit #{start},#{size}
</select>
<select id="countUsers" resultType="int">
select
count(*)
from
user
</select>
SQL 语句需要使用 resultType="int" 声明返回值,DML语句不需要声明返回值类型,会自动返回int值。
- 测试
@Test
public void testFindAllUsers(){
List<User> list=dao.findAllUsers(4,4);
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testCountUsers(){
int n = dao.countUsers();
System.out.println(n);
}
2. 重构业务层
- 重构业务层方法 UserService
/**
* 获取全部用户信息
* @return 用户信息
*/
List<User> list(Integer page);
/**
* 获取用户信息的页数
*/
int listPages();
- 实现方法 UserServiceImpl
public List<User> list(Integer page) {
if(page==null){
page=1;
}
//计算页面范围
int size = 8;
int start = (page-1)*size;
//调用数据层处理业务
return userDao.findAllUsers(start, size);
}
public int listPages() {
int rows = userDao.countUsers();
int size = 8;
int pages = rows/size;
if(rows%size==0){
return pages;
}
return pages+1;
}
- 测试
@Test
public void testList(){
List<User> list=service.list(null);
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testListPages(){
int n = service.listPages();
System.out.println(n);
}
3. 重构控制器
@RequestMapping("/users.do")
public String users(ModelMap map,
@RequestParam(
required=false,
value="page") Integer page){
//访问业务层获取全部用户信息
List<User> list=userService.list(page);
int pages = userService.listPages();
map.put("users", list);
map.put("pages", pages);
//System.out.println(list);
//转发到JSP页面,显示结果
return "user/list";
}
-
JSP页面重用即可
-
测试...
实现添加用户功能
原理:
![](https://img.haomeiwen.com/i4623185/c013bf2d7ab79a8c.png)
1. 显示添加界面
- 在控制器中添加方法,显示添加页面
/**
* 在控制器中添加方法,显示添加页面
*/
@RequestMapping("/add.do")
public String add(){
return "user/add";
}
- 测试
2. 实现保存功能
- 添加dao方法
int insertUser(User user);
- 添加SQL
<insert id="insertUser"
parameterType="cn.tedu.store.bean.User"
useGeneratedKeys="true"
keyProperty="id">
insert into user(
id,
username,
password,
mobile,
email,
create_time
)values(
null,
#{username},
#{password},
#{mobile},
#{email},
#{createTime}
)
</insert>
- 测试
@Test
public void testInsertUser(){
User user=new User(null, "Andy",
"123", "119", "110@tom.com", new Date());
int n = dao.insertUser(user);
System.out.println(n);
}
3. 业务层
- 添加业务层方法
User save(String username,String password,String mobile,String email);
- 实现业务层方法
public User save(String username,
String password, String mobile,
String email) {
User user=new User(null,
username, password, mobile,
email, new Date());
int n = userDao.insertUser(user);
if(n!=1){
throw new RuntimeException("添加失败!");
}
return user;
}
- 测试
@Test
public void testSave() {
User user = service.save("Wang", "123", "12345678", "wang@tom.com");
System.out.println(user);
}
4. 控制器
- 添加控制器方法
@RequestMapping("/save.do")
public String save(String username,
String password, String mobile,
String email){
User user=userService.save(
username, password, mobile, email);
return "redirect:users.do";
}
- 测试
作业
- 利用SSM实现用户信息的管理。
网友评论