学习资源:动力节点的2020最新SpringMVC教程【IDEA版】-springmvc从入门到精通
目录
SSM 整合,即 SpringMVC + Spring + MyBatis 整合,MyBatis 管理持久层,Spring 管理业务层,SpringMVC 管理视图层,SSM 是当前最为流行的 JavaEE 开发技术架构。SSM 整合的实质,仅仅就是将 MyBatis整合入 Spring,因为 SpringMVC 原本就是 Spring的一部分,不用专门整合。
SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式。
SSM 整合,其内部有两个容器:
- Spring 容器:管理 Service ,Dao,工具类对象
- SpringMVC 容器:管理 Controller 控制器对象
SpringMVC 容器是 Spring 容器的子容器, 类似java中的继承。 子可以访问父的内容,在子容器中的 Controller 对象可以访问父容器中的 Service对象, 这样就可以实现 Controller 对象使用 Service 对象。
整合步骤:
- 建表 student
- maven 依赖
- 配置 web.xml
- 注册 DispatcherServlet,用于创建springmvc容器、创建 servlet 处理用户请求
- 注册spring的监听器,用于在 web 启动时创建 spring 容器
- 注册字符集过滤器,解决 post 请求乱码问题
- 创建包,controller包、service包、dao包、实体类包
- 创建配置文件
- 数据库属性配置文件,db.properties
- springmvc 配置文件,springmvc.xml
- spring 配置文件,applicationContext.xml
- mybatis 配置文件
- 创建 dao 接口和 mappe r文件, service 和实现类,controller, 实体类
- 创建 jsp 页面
1、建表 student
2、创建 maven web 工程
3、maven 依赖
<dependencies>
<!--测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--springmvc,包含了spring的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--spring事务-->
<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>
<!--aspectj-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
</dependencies>
4、配置 web.xml
注册中央调度器:
<!-- 注册中央调度器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- springmvc 配置文件的位置 -->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 映射所有请求 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
注册 ContextLoaderListener 监听器:
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- spirng 配置文件的位置 -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
注册字符集过滤器:
<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>
<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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
5、创建目录结构
controller包、service包、dao包、实体类包
6、创建配置文件
6.0、数据库属性配置文件
db.properties
jdbc.url=jdbc:mysql://localhost:3306/库名?useSSL=true&useUnicode=true&characterEncoding=UTF-8
#用户名
jdbc.username=
#用户密码
jdbc.password=
#新版本的MySQL8驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
6.1、springmvc 配置文件
springmvc.xml
<!-- 注解扫描 -->
<context:component-scan base-package="com.chen.controller"/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 静态资源路径 -->
<mvc:resources mapping="/static/**" location="/static/"/>
<!-- 注解驱动:响应ajax请求;解决静态资源访问问题 -->
<mvc:annotation-driven/>
6.2、spring 配置文件
applicationContext.xml
<!-- 注册组件扫描器 -->
<!--声明service的注解@Service所在的包名位置-->
<context:component-scan base-package="com.chen.service"/>
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="filters" value="stat"/>
<property name="maxActive" value="20"/>
<property name="initialSize" value="1"/>
<property name="maxWait" value="60000"/>
<property name="minIdle" value="1"/>
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxOpenPreparedStatements" value="20"/>
<property name="asyncInit" value="true"/>
</bean>
<!-- 声明 SqlSessionFactoryBean,创建 SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 创建 dao 动态代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.chen.dao"/>
</bean>
<!-- 声明事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 声明事务注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- aspectj事务 -->
6.3、mybatis 配置文件
mybatis-config.xml
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 给pojo起别名 -->
<typeAliases>
<package name="com.chen.pojo"/>
</typeAliases>
<!-- sql映射文件的位置 -->
<mappers>
<package name="com.chen.dao"/>
</mappers>
7、创建类等源文件
7.1、实体类 Student
package com.chen.pojo;
public class Student {
private Integer id;
private String name;
private Integer age;
// 有参、无参
// set、get、toString、
}
7.2、Dao 接口和 sql 映射文件
package com.chen.dao;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
<mapper namespace="com.chen.dao.StudentDao">
<insert id="insertStudent">
insert into student(name,age) values(#{name},#{age})
</insert>
<select id="selectStudents" resultType="student">
select id, name, age from student order by id desc
</select>
</mapper>
7.3、Service 接口和实现类
package com.chen.service;
public interface StudentService {
int add(Student student);
List<Student> queryStudents();
}
package com.chen.service.impl;
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao dao;
@Override
public int add(Student student) {
return dao.insertStudent(student);
}
@Override
public List<Student> queryStudents() {
return dao.selectStudents();
}
}
7.4、控制器
package com.chen.controller;
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService service;
@RequestMapping("/addStudent")
public ModelAndView addStudent(Student student){
ModelAndView modelAndView = new ModelAndView();
int res = service.add(student);
if(res>0){
modelAndView.addObject("msg", student.getName()+"注册成功");
}
else {
modelAndView.addObject("msg", student.getName()+"注册失败");
}
modelAndView.setViewName("result");
return modelAndView;
}
@RequestMapping("/queryStudents")
@ResponseBody
public List<Student> listStudents(){
List<Student> students = service.queryStudents();
return students;
}
}
8、创建视图
8.1、首页文件 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>
<base href="<%=basePath%>" />
</head>
<body>
<div align="center">
<p>SSM整合</p>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
</tr>
<tr>
<td><a href="listStudents.jsp">浏览学生信息</a></td>
</tr>
</table>
</div>
</body>
</html>
8.2、注册学生页面 addStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>注册学生</title>
<base href="<%=basePath%>" />
</head>
<body>
<div align="center">
<form action="student/addStudent" method="post">
<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>
8.3、注册结果页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
result.jsp 结果页面,注册结果: ${msg}
</body>
</html>
8.4、浏览学生页面 listStudent.jsp
页面加载完毕和点击按钮就会发起 ajax 请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>查询学生ajax</title>
<base href="<%=basePath%>" />
<script type="text/javascript" src="static/js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function(){
//在当前页面dom对象加载后,执行loadStudentData()
loadStudentData();
$("#btnLoader").click(function(){
loadStudentData();
})
})
function loadStudentData(){
$.ajax({
url:"student/queryStudents",
type:"get",
dataType:"json",
success:function(data){
//清除旧的数据
$("#info").html("");
//增加新的数据
$.each(data,function(i,n){
$("#info").append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.name+"</td>")
.append("<td>"+n.age+"</td>")
.append("</tr>")
})
}
})
}
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
<input type="button" id="btnLoader" value="查询数据">
</div>
</body>
</html>