前一篇: 04-SpringMVC的注解开发https://blog.csdn.net/fsjwin/article/details/109562810
ssm整合是几个基本的技能,这里对ssm整合做整合,使用xml和注解的方式,如果想把xml消灭掉,可以看我的spring的博客
,可以使用@Configuration即配置bean可以做到。
1. 导入ssm的依赖、mysql依赖、jackson依靠 等
2. 配置文件
spring配置文件:applicationContext.xml
springmvc配置文件:dispatcherServlet.xml(可以消灭)
抽取的小配置文件:jdbc.properties(卡哇伊,可爱型)
mybatis配置文件:mybatis.xml(可以消灭,详见spring相关博客)
3. web.xml 配置spring和springmvc的基础配置
4. 业务代码的开发
1. 需求
首页:
点击【注册学生】跳转到下面页面:
点击提交,可以把数据存入数据库:
在首页点击【浏览学生】展示如下:
当然点击【查询学生列表】也可以重新查询列表
需求比较简单。
2.建表:
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`age` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
3.构建项目:
- 创建maven-web项目
- 目录结果如下:
4.构建项目:
4.1pom文件
<?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">
<parent>
<artifactId>springmvc20201109</artifactId>
<groupId>com.yuhl</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ssm</artifactId>
<packaging>war</packaging>
<name>ssm Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<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>
<!--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>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--jackson两个-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--msql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
</dependencies>
<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>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.2配置文件
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--springmvc中央调度器conf/dispatcherServlet.xml创建springmvc的容器,其实spirng容器的子容器-->
<servlet>
<servlet-name>springmvc</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>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--spring的监听器使用conf/applicationContext.xml创建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>
<!--字符集过滤器-->
<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>
</web-app>
- 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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--property的本地路径-->
<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="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--mybatis的sqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" 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="sqlSessionFactoryBean"/>
<property name="basePackage" value="com.yuhl.dao"/>
</bean>
<!--扫描service-->
<context:component-scan base-package="com.yuhl.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>
<!-- 实体别名-->
<package name="com.yuhl.domain"/>
</typeAliases>
<mappers>
<!--注册 mapper.xml 到 mybatis-->
<package name="com.yuhl.dao"/>
</mappers>
</configuration>
- 小配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/yuhl?useSSL=false&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
- 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">
<!--注解开发需要注解扫描包-->
<context:component-scan base-package="com.yuhl.controller"/>
<!--视图解析器-->
<bean id="internalResourceViewResolver" 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>
4.3Dao层
- StudentDao
package com.yuhl.dao;
import com.yuhl.domain.Student;
import java.util.List;
/**
* @author yuhl
* @Date 2020/11/10 21:26
* @Classname StudentService
* @Description TODO
*/
public interface StudentDao {
public int insertStudent(Student student);
public List<Student> selectStudent();
}
- StudentDao.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="com.yuhl.dao.StudentDao"> <!--接口名-->
<insert id="insertStudent">
insert into student(name,age) values(#{name},#{age})
</insert>
<select id="selectStudent" resultType="Student">
select id,name,age from student order by id desc
</select>
</mapper>
4.4service层
- StudentService
package com.yuhl.service;
import com.yuhl.domain.Student;
import java.util.List;
/**
* @author yuhl
* @Date 2020/11/10 21:53
* @Classname UserService
* @Description TODO
*/
public interface StudentService {
public int insertStudent(Student student);
public List<Student> selectStudent();
}
- StudentServiceImpl
package com.yuhl.service.impl;
import com.yuhl.dao.StudentDao;
import com.yuhl.domain.Student;
import com.yuhl.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author yuhl
* @Date 2020/11/10 21:53
* @Classname UserServiceImpl
* @Description TODO
*/
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
StudentDao studentDao;
@Override
public int insertStudent(Student student) {
return studentDao.insertStudent(student);
}
@Override
public List<Student> selectStudent() {
return studentDao.selectStudent();
}
}
4.5controller层StudentController
package com.yuhl.controller;
import com.yuhl.domain.Student;
import com.yuhl.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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.xml.transform.Result;
import java.util.List;
/**
* @author yuhl
* @Date 2020/11/10 21:55
* @Classname StudentController
* @Description TODO
*/
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping("/addStudent.do")
public ModelAndView addStudent(Student student) {
ModelAndView modelAndView = new ModelAndView();
String tips = "添加失败";
int i = studentService.insertStudent(student);
if (i > 0) {
tips = "添加成功:"+student;
}
modelAndView.addObject("tips", tips);
modelAndView.setViewName("result"); //视图
return modelAndView;
}
/**
* 查询学生列表
* @return 学生列表
*/
@RequestMapping("/listStudent.do")
@ResponseBody
public List<Student> listStudent(){
List<Student> students = studentService.selectStudent();
return students;
}
}
4.6实体层Student
package com.yuhl.domain;
import java.io.Serializable;
/**
* @author yuhl
* @Date 2020/11/10 21:25
* @Classname Student
* @Description TODO
*/
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
4.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>
<h2>SSM整合</h2>
<div align="center">
<p>SSM整合</p>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
</tr>
<tr>
<td><a href="listStudent.jsp">浏览学生</a></td>
</tr>
</table>
</div>
</body>
</html>
4.8新增页面
- 新增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</title>
<base href="<%=basePath%>" />
</head>
<body>
<h2>SSM整合</h2>
<div align="center">
<form action="student/addStudent.do" 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" name="注册"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
- 新增成功result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${tips}
</body>
</html>
4.9查询列表页面listStudent.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="static/js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
loadLlistStudents();//页面加载后先自动调用一次。
$("#listStudentBtn").click(function () {
//alert("button click");
loadLlistStudents();//抽取出去的方法。
});
});
function loadLlistStudents() {
$.ajax({
//相对路径
url: "student/listStudent.do", //页面的地址栏:http://localhost:8080/springmvc/returnvoid_ajax.do
type:"get",
dataType:"json",
success:function (data) {
$("#info").html("");
//遍历解决list
$.each(data,function (i,n) {
$("#info").append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.name+"</td>")
.append("<td>"+n.age+"</td>")
.append("</td>")
});
}
});
}
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
<%--存放查询出来的数据--%>
</tbody>
</table><br/>
<button id="listStudentBtn" type="button">查询学生列表</button>
</div>
</body>
</html>
5.总结
此篇是对ssm的整合,整合完成后功能一切正常。
需要掌握整合的方法论,不要陷入细节,写框架的大佬已经为我问提供了各种准备,我们仅需要傻瓜式使用就可以了。
希望大家变得更强(王骁,哈哈哈 )