前言
SSM 编程,即 SpringMVC + Spring + MyBatis 整合,是当前最为流行的 JavaEE 开发技术架构。其实 SSM 整合的实质,仅仅就是将 MyBatis整合入 Spring。因为 SpringMVC原本就是Spring的一部分,不用专门整合。
SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式。
一、搭建 SSM 开发环境
Maven pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
用来定义除了 .java 文件之外,其他资源文件位置,放在 <bulid/>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
配置 web.xml
- 注册 ContextLoaderListener 监听器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
注册 ServletContext 监听器的实现类 ContextLoaderListener,用于创建 Spring 容器及将创建好的 Spring 容器对象放入到 ServletContext 的作用域中。
<filter>
<filter-name>charaterEncodingFilter</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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>charaterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注册字符集过滤器,用于解决请求参数中携带中文时产生乱码问题。
配置中央调度器时需要注意,SpringMVC 的配置文件名与其它 Spring 配置文件名不相同。这样做的目的是 Spring 容器创建管理 Spring 置文件中的 bean, SpringMVC 容器中负责视图层 bean 的初始化。
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcherServlet.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>
二、SSM 整合注解式开发
项目:ssm
需求:完成学生注册和信息浏览
建表
建立 student 表
定义包、组织程序的结构
jsp文件
编写配置文件
JDBC 属性配置文件 db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
user=root
password=aszhuo123
Spring 配置文件 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">
<context:component-scan base-package="com.fancy.service"></context:component-scan>
<context:property-placeholder location="db.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${url}"></property>
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="mybatis.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.fancy.dao"></property>
</bean>
</beans>
Springmvc 配置文件 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.alibaba.com/schema/stat"
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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">
<context:component-scan base-package="com.fancy.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven/>
</beans>
MyBatis 配置文件 mybatis.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>
<package name="com.fancy.domain"/>
</typeAliases>
<mappers>
<package name="com.fancy.dao"/>
</mappers>
</configuration>
定义 web.xml
分为以下四步
1)注册 ContextLoaderListener 2)注册 DisatcherServlet 3)注册字符集过滤器 4)同时创建 Spring 的配置文件和 SpringMVC 的配置文件
我们之前已经定义好了
实体类 Student
package com.fancy.domain;
public class Student {
private Integer id;
private String name;
private int age;
public Student() {
}
public Student(Integer id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
定义 Dao 接口 与 sql 映射文件
Dao 接口
package com.fancy.dao;
import com.fancy.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectAllStudents();
}
sql 映射文件
<?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="com.fancy.dao.StudentDao">
<insert id="insertStudent">
insert into student(name, age) values(#{name}, #{age})
</insert>
<select id="selectStudentByPage" resultType="Student">
select id, name, age from student order by id desc
</select>
</mapper>
定义 Service 接口与实现类
Service 接口
package com.fancy.service;
import com.fancy.domain.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
List<Student> findStudents();
}
Service 实现类
package com.fancy.service;
import com.fancy.dao.StudentDao;
import com.fancy.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "studentService")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao stuDao;
@Override
public int addStudent(Student student) {
return stuDao.insertStudent(student);
}
@Override
public List<Student> findStudents(){
return stuDao.selectAllStudents();
}
}
处理器定义
package com.fancy.controller;
import com.fancy.domain.Student;
import com.fancy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/addStudent.do")
public ModelAndView addStudent(Student student) {
ModelAndView mv = new ModelAndView();
int rows = studentService.addStudent(student);
if (rows > 0) {
mv.addObject("msg", "注册成功");
mv.setViewName("success");
} else {
mv.addObject("msg", "注册失败");
mv.setViewName("fail");
}
return mv;
}
}
定义视图-首页文件 — index.jsp
指定路径
<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %>
指定base标签
<base href="<%=basePath%>">
页面总代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %>
<html>
<head>
<base href="<%=basePath%>">
<title>Title</title>
</head>
<body>
<div align="center">
<p>SSM整合开发 -- 实现 student 表的操作</p>
<img src="images/ssm.jpg">
<table cellpadding="0" cellspacing="0">
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><a href="listStudent.jsp">查询学生</a></td>
</tr>
</table>
</div>
</body>
</html>
注册学生页面 — addStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div align="center">
<p>学生注册界面</p>
<form action="/MyWeb/student/addStudent.do">
<table>
<tr>
<td>姓名: </td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>年龄: </td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="注册"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
浏览学生页面 — listStudent.jsp
页面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div align="center">
<p>查询学生数据</p>
<table>
<thead>
<tr>
<td>id</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="stubody"></tbody>
</table>
</div>
</body>
</html>
引入 JQuery
js 发起 ajax
<script type="text/javascript">
$(function (){
stuinfo();
})
function stuinfo() {
$.ajax({
url:"student/queryStudent.do",
type:"post",
dataType:"json",
success:function (resp) {
$("#stubody").html("");
$.each(resp, function(i, n){
$("#stubody").append("<tr>").append("<td>" + n.id + "</td>").append("<td>" + n.name + "</td>").append("<td>" + n.age + "</td>").append("</tr>")
})
}
})
}
</script>
注册成功与失败界面
view 目录下的页面结构
success.jsp 页面
fail.jsp 页面
三、测试
首页 注册界面 注册结果 查询界面
如果出现 500 错误,检查 maven 依赖是否冲突
无红线即没有冲突
|