开始时间:2022-01-28
课程链接:springmvc从入门到精通
SSM: SpringMVC + Spring + MyBatis.
SpringMVC:视图层,界面层,负责接收请求,显示处理结果的。
Spring:业务层,管理service,dao,工具类对象的。
MyBatis:持久层, 访问数据库的
用户发起请求–SpringMVC接收–Spring中的Service对象–MyBatis处理数据
整合中有容器。
1.第一个容器SpringMVC容器, 管理Controller控制器对象的。
2.第二个容器Spring容器,管理Service,Dao,工具类对象的
我们要做的把使用的对象交给合适的容器创建,管理。 把Controller还有web开发的相关对象
交给springmvc容器, 这些web用的对象写在springmvc配置文件中
service,dao对象定义在spring的配置文件中,让spring管理这些对象。
springmvc容器和spring容器是有关系的,关系已经确定好了
springmvc容器是spring容器的子容器, 类似java中的继承。 子可以访问父的内容
在子容器中的Controller可以访问父容器中的Service对象, 就可以实现controller使用service对象
实现步骤
实现步骤:
-
使用springdb的mysql库, 表使用student(id auto_increment, name, age)
-
新建maven web项目
-
加入依赖
springmvc,spring,mybatis三个框架的依赖,jackson依赖,mysql驱动,druid连接池
jsp,servlet依赖 -
写web.xml
1)注册DispatcherServlet ,目的:1.创建springmvc容器对象,才能创建Controller类对象。
2.创建的是Servlet,才能接受用户的请求。2)注册spring的监听器:ContextLoaderListener,目的: 创建spring的容器对象,才能创建service,dao等对象。
3)注册字符集过滤器,解决post请求乱码的问题
-
创建包, Controller包, service ,dao,实体类包名创建好
-
写springmvc,spring,mybatis的配置文件
1)springmvc配置文件
2)spring配置文件
3)mybatis主配置文件
4)数据库的属性配置文件 -
写代码, dao接口和mapper文件, service和实现类,controller, 实体类。
-
写jsp页面
示例:学生注册和浏览系统
总体结构如下
1.新建表
2.新建maven web项目
idea里面直接用maven建一个webapp项目即可
3.加入依赖
SpringMVC依赖
<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>
mybatis依赖
<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>
Jackson依赖
<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>
mysql驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
servlet依赖
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
jsp依赖
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
druid连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
再添加build用于扫描组件
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>15</source>
<target>15</target>
</configuration>
</plugin>
</plugins>
</build>
4.写web.xml
在web.xml中注册DispatcherServlet
1.创建springmvc容器对象,才能创建Controller类对象。
2.创建的是Servlet,才能接受用户的请求。
<!--注册中央调度器-->
<servlet>
<servlet-name>myweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<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>myweb</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</beans>
在web.xml中注册spring监听器
创建spring的容器对象,才能创建service,dao等对象。
<!--注册spring的监听器-->
<context-param>
<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>
在web.xml中注册字符集过滤器
解决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>
<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.写springMVC spring mybatis的配置文件
- 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.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="BUPT.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven />
<!--
1. 响应ajax请求,返回json
2. 解决静态资源访问问题。
-->
</beans>
- 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">
<!--spring配置文件: 声明service,dao,工具类等对象-->
<context:property-placeholder location="classpath:conf/jdbc.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}" />
</bean>
<!--SqlSessionFactoryBean创建SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:conf/mybatis.xml" />
</bean>
<!--声明mybatis的扫描器,创建dao对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="BUPT.dao" />
</bean>
<!--声明service的注解@Service所在的包名位置-->
<context:component-scan base-package="BUPT.service" />
<!--事务配置:注解的配置, aspectj的配置-->
</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>
<!--name:实体类所在的包名(不是实体类的包名也可以)-->
<package name="BUPT.entity"/>
</typeAliases>
<!-- sql mapper(sql映射文件)的位置-->
<mappers>
<!--
name:是包名, 这个包中的所有mapper.xml一次都能加载
使用package的要求:
1. mapper文件名称和dao接口名必须完全一样,包括大小写
2. mapper文件和dao接口必须在同一目录
-->
<package name="BUPT.dao"/>
</mappers>
</configuration>
- 数据库属性配置文件
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/springdb?serverTimezone=UTC
jdbc.username=root
jdbc.password=333
6.创建包
Controller
StudentController
完成两个功能,注册和查询
package BUPT.controller;
import BUPT.entity.Student;
import BUPT.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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("/student")
public class StudentController {
@Resource
private StudentService service;
//注册学生
@RequestMapping("/addStudent.do")
public ModelAndView addStudent(Student student) {
ModelAndView mv = new ModelAndView();
String tips = "注册成功";
//调用service处理Student
int nums = service.addStudent(student);
if (nums > 0) {
//注册成功
tips = "学生【" + student.getName() + "】注册成功";
}
//添加数据
mv.addObject("tips", tips);
//指定结果页面
mv.setViewName("result");
return mv;
}
//查询学生
@RequestMapping("/queryStudent.do")
@ResponseBody
public List<Student> queryStudent() {
List<Student> students = service.findStudent();
return students;
}
}
service包
service包中先写StudentService的接口,用于对应上面两种请求
package BUPT.service;
import BUPT.entity.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
List<Student> findStudent();
}
然后是对应的执行方法
package BUPT.service;
import BUPT.dao.StudentDao;
import BUPT.entity.Student;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int nums=studentDao.insertStudent(student);
return nums;
}
@Override
public List<Student> findStudent() {
return studentDao.selectStudents();
}
}
这里可以发现还需要dao的配合
dao类
StudentDao
package BUPT.dao;
import BUPT.entity.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
以及mapper文件StudentDao.xml存放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="BUPT.dao.StudentDao">
<select id="selectStudents" resultType="BUPT.entity.Student">
select id,name,age from student order by id desc
</select>
<insert id="insertStudent">
insert into student(name,age) values(#{name},#{age})
</insert>
</mapper>
还需要写一个实体类
Student为类名,三个属性id,name,age以及对应的get set方法
jsp页面
三个页面
主页面
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>
<img src="images/图片示例.jpeg"/>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
</tr>
<tr>
<td><a href="listStudent.jsp">浏览学生</a></td>
</tr>
</table>
</div>
</body>
</html>
主界面中因为链接了其他的图片,所以也需要放到
webapp目录下
注册页面
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.do" method="post">
<table>
<tr>
<td>姓名:</td>
<!--这里的name包括下面的age,都是保证和Student里面的参数一致-->
<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" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath() + "/";
%>
<html>
<head>
<title>查询学生ajax</title>
<base href="<%=basePath%>"/>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function () {
//页面dom加载了,调用该方法
loadStudentData();
})
function loadStudentData() {
$.ajax({
url: "student/queryStudent.do",
type: "get",
dataType: "json",
success: function (data) {
//清除原来数据
$("#info").html("");
//增加新的数据
$.each(data, function (i, n) {
$("#info").append("<tr>")
.append("<td>" + n.id + "</id>")
.append("<td>" + n.name + "</id>")
.append("<td>" + n.age + "</id>")
.append("</tr>")
})
}
})
}
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
</div>
</body>
</html>
这里用到了jQuery,所以需要在包里面引入进来
结束时间:2022-01-31