1.SSM整合开发步骤
总体来说就是 SPringMVC接收用户请求-----Spring中的Service对象-----Mybatis处理数据
ssm整合也叫做ssi,整合中有容器
1.第一容器SpringMVC容器,管理Controller控制器对象。
2.第二个容器Spring容器,管理Service,dao,工具类对象
我们要做的就是把使用的对象交给合适的容器创建,管理。把Controller还有Web开发的相关对象交给Springmvc容器,
这些web用的对象卸载Springmvc(dispatcherServlet)配置文件中。
service,dao对象定义在Spring的配置文件中,让spring管理创建这些对象
3.springmvc容器是spring容器的子容器,在子容器中的Controller可以访问父容器中的Service对象,
就可以实现controller使用service对象。
2.实现步骤
1.建立一个数据库,本人使用的是student的一张表(id,name,age),只有name是String类型,其他两个是Int。
2加入依赖
Springmvc,spring,mybatis三个框架的依赖,jackson依赖,mysql驱动,druid连接池,jsp,servlet依赖
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gaodeng</groupId>
<artifactId>ssm-gao</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<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>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>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>5.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</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>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.写web.xml
(1)注册DispatcherServlet,目的是创建Spring容器对象,之后才能创建Controller类对象;创建Servlet,才能接收用户的请求。
(2)注册spring监听器:ContextLoaderListener,目的是在服务器启动时创建Spring容器对象,才能创建service,dao等对象
(3)注册字符集过滤器,解决post请求乱码的问题。
<?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">
<!--1.-->
<!--注册中央调度器-->
<!--init-param属于一个servlet所有;
context-param属于整个应用程序所有 ,
不仅是在servlet中可以得到,jsp文件中也可以得到,
在jsp中application就相当于这里的servletContext. -->
<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:conf/dispatcherServlet.xml</param-value>
</init-param>
<!--1表示在服务器启动的时候就创建该Servlet,不用等到需要使用再创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--2-->
<!--创建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>
<!--3-->
<!--注册字符集过滤器-->
<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>
<!--设置为/*时,它会覆盖其他所有的servlet,包括servlet容器提供的所有servlet-->
</filter-mapping>
</web-app>
4.创建包,Controller包,service,dao,实体类包名创建好
5.5.写springmvc,spring,mybatis的配置文件 ?1)springmvc配置文件
<?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="com.gaodeng.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>
?2)spring配置文件
<?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:property-placeholder>标签导入才能使用-->
<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="com.gaodeng.dao"/>
</bean>
<!--声明service的注解@Service所在的包名位置-->
<context:component-scan base-package="com.gaodeng.service"/>
<!--事务配置:注解的配置, aspectj的配置-->
</beans>
?3)mybatis主配置文件
<?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>
<!--settings:控制mybatis全局行为-->
<!-- <settings>
<!–设置mybatis输出日志–>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>-->
<!--设置别名-->
<typeAliases>
<!--name:实体类所在的包名(不是实体类的包名也可以)-->
<package name="com.gaodeng.domain"/>
</typeAliases>
<!-- sql mapper(sql映射文件)的位置-->
<mappers>
<!--
name:是包名, 这个包中的所有mapper.xml一次都能加载
使用package的要求:
1. mapper文件名称和dao接口名必须完全一样,包括大小写
2. mapper文件和dao接口必须在同一目录
-->
<package name="com.gaodeng.dao"/>
</mappers>
</configuration>
?4)数据库的属性配置文件
jdbc.url=jdbc:mysql://localhost:3306/gaodeng
jdbc.username=root
jdbc.password=123456
6.写代码, dao接口和mapper文件, service和实现类,controller, 实体类。
按我的意思从简单的开始写,先写实体类,实体类的属性最好与数据库字段名相同,防止后面写的mybatis映射文件要处理别名。
然后就写dao类,service类。最后写controller类。
--------------------------------------------------------------------------包的结构图--------------------------------------------------------------------------------------------------------
?
实体类
package com.gaodeng.domain;
public class Student {
private Integer id;
private String name;
private Integer 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;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
dao类
package com.gaodeng.dao;
import com.gaodeng.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudent();
}
<?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.gaodeng.dao.StudentDao">
<select id="selectStudent" resultType="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>
service类
package com.gaodeng.service;
import com.gaodeng.domain.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
List<Student> findStudent();
}
package com.gaodeng.service.impl;
import com.gaodeng.dao.StudentDao;
import com.gaodeng.domain.Student;
import com.gaodeng.service.StudentService;
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 i = studentdao.insertStudent(student);
return i;
}
@Override
public List<Student> findStudent() {
return studentdao.selectStudent();
}
}
controller类
package com.gaodeng.controller;
import com.gaodeng.domain.Student;
import com.gaodeng.service.StudentService;
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.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService service;
@RequestMapping("/addStudent")
public ModelAndView addStudent(Student student) {
String result = "添加失败";
int num = service.addStudent(student);
if(num>0){
result = "学生:"+student.getName()+"添加数据成功";
}
ModelAndView mv = new ModelAndView();
mv.addObject("key1",result);
//指定跳转jsp视图页面
mv.setViewName("show");
return mv;
}
@RequestMapping("/listStudent")
@ResponseBody
//
public List<Student> listStudent(){
List<Student> student = service.findStudent();
return student;
}
}
7.写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>
<table>
<tr>
<td><a href="addStudent.jsp"> 注册学生</a></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" %>
<%
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>
<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()
loadStudentData();
$("#btn1").click(function (){
loadStudentData();
})
})
function loadStudentData(){
$.ajax({url:"student/listStudent.do",
type:"get",
dataType:"json",
success:function (data){
//清除旧的数据
$("#tbody").html("");
//增加新的数据
$.each( data, function (i,n){
$("#tbody").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>学号</tr>
<tr>姓名</tr>
<tr>年龄</tr>
</thead>
<tbody id = "tbody">
</tbody>
</table>
<input type="button" id="btn1" value="查询数据">
</div>
</body>
</html>
转发.jsp
<%--
Created by IntelliJ IDEA.
User: 登哥叫我
Date: 2022/1/28
Time: 21:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>结果页面</h1>
<div> ${key1}</div>
</body>
</html>
碰到的bug,还有一些错误,运行异常
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SqlSessionFactory' defined in class path resource [conf/applicationContext.xml]: Invocation of init method failed; nested exception is org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 30; columnNumber: 1;
该异常是mybatis配置文件中出现了问题,检擦标签是否正确,例如value 和ref需要区分开。
访问静态资源比如index.jsp时出现的404,主要原因是web.xml中的创建中央调度器的时候<url-pattern>的值写成了"\",且没有配置相关的一些配置。
最简单的就是<url-pattern>*.xxx</url-pattern>。
|