SSM 编程,即 SpringMVC + Spring + MyBatis 整合,是当前最为流行的 JavaEE 开发技术架构。其实 SSM 整合的实质,仅仅就是将 MyBatis整合入 Spring。因为 SpringMVC原本就是Spring的一部分,不用专门整合。
SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式。
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2.1-b03version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.12version>
dependency>
用来定义除了 .java 文件之外,其他资源文件位置,放在
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
resources>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
注册 ServletContext 监听器的实现类 ContextLoaderListener,用于创建 Spring 容器及将创建好的 Spring 容器对象放入到 ServletContext 的作用域中。
<filter>
<filter-name>charaterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>charaterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
注册字符集过滤器,用于解决请求参数中携带中文时产生乱码问题。
配置中央调度器时需要注意,SpringMVC 的配置文件名与其它 Spring 配置文件名不相同。这样做的目的是 Spring 容器创建管理 Spring 置文件中的 bean, SpringMVC 容器中负责视图层 bean 的初始化。
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:dispatcherServlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
项目: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
<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
<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
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>
分为以下四步
1)注册 ContextLoaderListener
2)注册 DisatcherServlet
3)注册字符集过滤器
4)同时创建 Spring 的配置文件和 SpringMVC 的配置文件
我们之前已经定义好了
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 接口
package com.fancy.dao;
import com.fancy.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectAllStudents();
}
sql 映射文件
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 接口
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 , @Resource, byType | byName
// byType
@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();
// 调用 Service 处理业务, 将结果放入到 ModelAndView 中
int rows = studentService.addStudent(student);
if (rows > 0) {
mv.addObject("msg", "注册成功");
mv.setViewName("success");
} else {
mv.addObject("msg", "注册失败");
mv.setViewName("fail");
}
return mv;
}
}
指定路径
<% 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>Titletitle>
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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
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>
页面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<div align="center">
<p>查询学生数据p>
<table>
<thead>
<tr>
<td>idtd>
<td>姓名td>
<td>年龄td>
tr>
thead>
<tbody id="stubody">tbody>
table>
div>
body>
html>
引入 JQuery
<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("").append("" + n.id + " ").append("" + n.name + " ").append("" + n.age + " ").append(" ")
})
}
})
}
</script>
view 目录下的页面结构
如果出现 500 错误,检查 maven 依赖是否冲突