ch08-ssm:ssm整合开发
ssm:SpringMVC + Spring +Mybatis.
SpringMVC:层,界面层,复制接受请求,显示处理结果的。
Spring:业务层,管理servic,dao,工具类对象的。
Mybatis:持久层,访问数据库的
用户发起请求--SpringMVC接受--Spring中的serv对象--Mybatis处理数据
ssm整合也叫做SSI(IBatis也就是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对象
实现步骤:
0.使用springdb的mysql库,表使用student(id auto-increment,name.age)
1.新建maven web项目
2.加入依赖
springmvc,spring,mybatis三个框架的依赖。jackson依赖,MySQL驱动,druid连接池
jsp,servlet依赖
3.写web.xml
1)注册DispatchersServlet,目的:1.创建springmvc容器对象。才能常见controller类对象。
2.创建的是Servlet,才能接受用户的请求。
2)注册spring的监听器:contextLoaderListener,目的:创建spring的容器对象,才能创建service,dao等对象
3.注册字符集过滤器,解决post请求乱码的问题
4.创建包,controller包,service,dao,实体类包名创建好
5.写springmvc,spring,mybatis的配置文件
1)springmvc配置文件
2)spring配置文件
3)mybatis主配置文件
4)数据库的属性配置文件
6.写代码,dao接口和mapper文件,service和实现类,controller,实体类
7.写jsp页面
bug可能是你的applicationcontext.xml文件的的命名空间写错了
每写完一个功能就要运行一下好找出错位置
500错误
SSM项目,mapper文件未被编译成class文件
运行项目的时候一直报异常
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
然后百度了一下说是dao层和mapper.xml层联系有问题,然后就一直在看这两个层的,始终没看出毛病
后来看了一下编译文件
这个时候问题就出现了
发现mapper文件未被编译
于是在pom.xml文件中加入了这样一段代码
此时我们需要在maven的pom.xml中中添加
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
这样再次build的时候相应的mapper.xml将生成在classes中
问题解决
index.jsp--addStudent.jsp---student/addStudent.do( service的方法,调用dao的方法)--result.jsp
用到的层级结构图
controller包中的StudentController类
@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;
}
//处理查询,响应ajax
@RequestMapping("/queryStudent.do")
@ResponseBody
public List<Student> queryStudent(){
//参数检查,简单的数据处理
List<Student> students = service.findStudents();
return students;
}
}
dao包中的StudentDao类
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
StudentDao的mapper文件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.bjpowernode.dao.StudentDao">
<!--mybatis.xml中配置过实体类的别名,resultType就可以不写全限定名称,写一个Student就行-->
<select id="selectStudents" 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>
domain包的Student实体类
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
service包中的StudentService类
public interface StudentService {
int addStudent(Student student);
List<Student> findStudents();
}
及它的实现类StudentServiceImpl
@Service
public class StudentServiceImpl implements StudentService {
//引用类型自动注入@Autowired,@Resource
@Resource
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int nums = studentDao.insertStudent(student);
return nums;
}
@Override
public List<Student> findStudents() {
return studentDao.selectStudents();
}
}
resource包下一般放一个conf包存放配置文件
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>
<bean id="sqlSessFactoryBean" 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="sqlSessFactoryBean"/>
<property name="basePackage" value="com.bjpowernode.dao"/>
</bean>
<!--声明service的注解@Service所在的包名位置-->
<context:component-scan base-package="com.bjpowernode.service"/>
<!--事务配置:注解的配置,aspectj的配置-->
</beans>
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="com.bjpowernode.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>
数据库连接信息----jdbc.properties
高版本的mysql要声明编码
jdbc.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=03180813
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="com.bjpowernode.domain"/>
</typeAliases>
<mappers>
<!--告诉mybatis要执行的sql语句的位置
name:是包名,这个包中的所以mapper.xml一次都能加载
使用package的要求:
1.mapper文件名称和dao接口名必须完全一样,包括大小写
2.mapper文件和dao接口必须在同一目录
-->
<package name="com.bjpowernode.dao"/>
</mappers>
</configuration>
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">
<!--注册中央调度器-->
<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>
<!--注册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>
webapp下有三个jsp文件
index.jsp--addStudent.jsp---student/addStudent.do( service的方法,调用dao的方法)--result.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/ssm.jpg"/>
<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>
<base href="<%=basePath%>">
<title>注册学生</title>
</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>
查询学生信息(用jquery发起ajax请求)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();
$("#btnLoader").click(function () {
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 + "</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>
一个普通的结果显示result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
result.jsp 结果界面,注册结果:${tips}
</body>
</html>