SSM整合开发
SSM编程,即SpringMVC + Spring + MyBatis 整合,是当前最为流行的 JavaEE 开发技术架构。其实SSM整合的实质,仅仅就是将MyBatis整合融入Spring。因为SpringMVC原本就是Spring的一部分,不用专门整合。
SSM整合的实现方式可分为两种
- 基于XML配置方式
- 基于注解方式
一、措建SSM开发环境
1、maven pom.xml
<?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.0</modelVersion>
<groupId>cn.edu.huat</groupId>
<artifactId>ch05-ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--阿里巴巴数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!--mybatis和spring集成的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--springmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--spring事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--Jackson依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<!--目的是把src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中-->
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<!--指定jdk的版本-->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、配置web.xml
(1)注册ContextLoaderListener
<!--注册监听器ContextLoaderListener
监听器被创建对象后,会读取/WEB INF/spring.xml
为什么要读取文件:因为在监听器中要创建ApplicationContext对象,需要加载配置文件。
/WEB-INF/applicationContext.xml就是监听器默认读取的spring配置文件路径
可以修改默认的文件位置,使用context-param重新指定文件的位置
配置监听器:目的是创建容器对象,创建了容器对象,就能把spring.xml配置文件中的所有对象都创建好。
用户发起请求就可以直接使用对象了-->
<context-param>
<!--contextConfigLocation:表示配置文件的路径-->
<param-name>contextConfigLocation</param-name>
<!--自定义配置文件的路径-->
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(2)注册字符集过滹器
<!--注册声明过滤器,解决post请求乱码问题-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--设置项目中使用的字符编码-->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<!--强制请求对象(HttpServletRequest)使用encoding编码的值-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制应答对象(HttpServletResponse)使用encoding编码的值-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!-- /*:表示强制所有的请求先通过过滤器处理 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
(3)配置中央调度器
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--自定义springmvc读取的配置文件的位置-->
<init-param>
<!--springmvc的配置文件的位置属性-->
<param-name>contextConfigLocation</param-name>
<!--指定自定义文件的位置-->
<param-value>classpath:conf/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
二、SSM整合注解开发
1、定义包,组织程序的结构
2、编写配置文件
(1)applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--把数据库的配置信息,写在一个独立的文件,编译修改数据库的配置内容
spring知道jdbc.properties文件的位置-->
<context:property-placeholder location="classpath:conf/jdbc.properties" />
<!--声明数据源DataSource,作用是连接数据库-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!--set注入给DruidDataSource提供连接数据库信息-->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!--配置最大连接数量-->
<property name="maxActive" value="${maxActive}" />
</bean>
<!--声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建qlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入,把数据库连接池付给了DataSource属性-->
<property name="dataSource" ref="dataSource" />
<!--mybatis主配置文件的位置
configLocation属性是Resource类型,读取配置文件
它的赋值,使用value,指定文件的路径,使用classpath:表示文件的位置-->
<property name="configLocation" value="classpath:conf/mybatis-config.xml" />
</bean>
<!--声明mybatis的扫描器,创建dao对象,使用SqlSession的getMapper(userDao.class)
MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定SqlSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!--指定包名,包名是dao接口所在的包名。
MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行一次getMapper()方法,得到每个接口的dao对象。
创建好的dao对象放入到spring的容器中。dao对象的默认名称是接口名首字母小写-->
<property name="basePackage" value="cn.edu.huat.dao" />
</bean>
<!--声明service的注解@Service所在的包名位置-->
<context:component-scan base-package="cn.edu.huat.service" />
</beans>
(2)dispatcherServlet.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: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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--springmvc配置文件, 声明controller和其它web相关的对象-->
<context:component-scan base-package="cn.edu.huat.controller" />
<!--声明SpringMVC框架中的视图解析器,帮助开发人员设置视图文件的路径-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀:视图文件的路径-->
<property name="prefix" value="/WEB-INF/jsp/" />
<!--后缀:视图文件的扩展名-->
<property name="suffix" value=".jsp" />
</bean>
<!--响应ajax请求,返回json。解决静态资源访问问题。-->
<mvc:annotation-driven />
</beans>
(3)mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置别名-->
<typeAliases>
<!--name:实体类所在的包名-->
<package name="cn.edu.huat.domain"/>
</typeAliases>
<!--sql mapper(sql映射文件)的位置-->
<mappers>
<!--name:包名,这个包中的所有mapper.xml一次都能加载-->
<package name="cn.edu.huat.dao"/>
</mappers>
</configuration>
3、实体类User
package cn.edu.huat.domain;
public class User {
private Integer userId;
private String username;
private String password;
private String sex;
private String email;
//无参构造
//带参构造
//setting and getting方法
}
4、Dao接口和sql映射文件
(1)UserDao
package cn.edu.huat.dao;
import cn.edu.huat.domain.User;
import java.util.List;
public interface UserDao {
//注册用户
int insertUser(User user);
//查询用户
List<User> selectUsers();
}
(2)UserDao.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.edu.huat.dao.UserDao">
<select id="selectUsers" resultType="User">
select userId,username,password,sex,email from users order by userId desc
</select>
<insert id="insertUser">
insert into users(username,password,sex,email) values(#{username},#{password},#{sex},#{email})
</insert>
</mapper>
5、Service接口和实现类
(1)UserService
package cn.edu.huat.service;
import cn.edu.huat.domain.User;
import java.util.List;
public interface UserService {
int addUser(User user);
List<User> findUsers();
}
(2)UserServiceImpl
package cn.edu.huat.service.impl;
import cn.edu.huat.dao.UserDao;
import cn.edu.huat.domain.User;
import cn.edu.huat.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
//引用类型自动注入
@Resource
private UserDao userDao;
@Override
public int addUser(User user) {
int nums = userDao.insertUser(user);
return nums;
}
@Override
public List<User> findUsers() {
return userDao.selectUsers();
}
}
6、处理器定义
package cn.edu.huat.controller;
import cn.edu.huat.domain.User;
import cn.edu.huat.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
//注册用户
@RequestMapping("/addUser.do")
public ModelAndView addUser(User user){
ModelAndView modelAndView = new ModelAndView();
String tips = "注册失败";
int nums = userService.addUser(user);
if (nums > 0){
tips = "用户【" + user.getUsername() + "】注册成功";
}
//添加数据
modelAndView.addObject("tips",tips);
//指定结果页面
modelAndView.setViewName("result");
return modelAndView;
}
//查询用户
@RequestMapping("/findUsers.do")
@ResponseBody
public List<User> findUsers(){
List<User> userList = userService.findUsers();
return userList;
}
}
7、定义视图首页文件(index.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>" />
</head>
<body>
<a href="addUser.jsp">注册用户</a>
<a href="findUsers.jsp">查询用户</a>
</body>
</html>
8、注册学生页面(addUser.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>" />
</head>
<body>
<form action="user/addUser.do" method="post">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
性别:<input type="radio" name="sex" value="男" />男
<input type="radio" name="sex" value="女" />女<br>
邮箱:<input type="text" name="email" /><br>
<input type="submit" value="注册" />
<input type="reset" value="重置" />
</form>
</body>
</html>
9、浏览学生页面(listUser.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>" />
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
//在当前页面dom对象加载后,执行loadUserData()
loadUserData();
//鼠标单击事件,点击按钮查询数据
$("#btnLoader").click(function () {
loadUserData();
})
})
function loadUserData() {
$.ajax({
url:"user/findUsers.do",
type:"get",
dataType:"json",
success:function (data) {
//清除旧数据
$("#info").html("");
//增加新数据
$.each(data,function (i,n) {
$("#info").append("<tr>")
.append("<td>" + n.userId + "</td>")
.append("<td>" + n.username + "</td>")
.append("<td>" + n.password + "</td>")
.append("<td>" + n.sex + "</td>")
.append("<td>" + n.email + "</td>")
.append("</tr>")
})
}
})
}
</script>
</head>
<body>
<table align="center">
<thead>
<tr>
<td>编号</td>
<td>用户名</td>
<td>密码</td>
<td>性别</td>
<td>邮箱</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
<input type="button" id="btnLoader" value="查询数据" />
</body>
</html>
10、注册结果页面(result.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
result.jsp 结果页面,注册结果:${tips}
</body>
</html>