简单易学的SSM(Spring+SpringMVC+MyBatis)整合

SSM(Spring+SpringMVC+MyBatis)的整合:

具体执行过程:  1.用户在页面向后台发送一个请求

2.请求由DispatcherServlet 前端控制器拦截交给SpringMVC管理,SpringMVC讲这个请求传递给Controller层处理。

同时请求由Listener监听到交付给Spring,Spring建立IOC容器。

3.Controller层中会调用相应的Service层的方法处理业务逻辑。此时Service从上一步中建立好的IOC容器获取对象,然后获取

到Mapper接口中的代理类对象调用接口中的方法。

4.这个方法在对应的SQL映射文件mapper.xml中执行SQL语句,与数据库交互,获取到结果后返回给Service中的这个方法,

然后返回给Controller,再跳转到JSP页面显示给用户。

总结:SpringMVC                     与前台页面交互

Spring                             处理业务逻辑

MyBatis                          与数据库打交道

从下面的配置中不难发现:  SpringMVC的底层是由Listener实现的

Spring本质是一个Servler

这有助于大家理解SSM

SSM配置:

建立动态WEB项目,导入相应JAR包:

简单易学的SSM(Spring+SpringMVC+MyBatis)整合

简单易学的SSM(Spring+SpringMVC+MyBatis)整合

然后在web.xml中配置Spring和SpringMVC:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Spring-SpringMVC-MyBatis</display-name>
<!-- 配置Spring -->
<!--配置Listener监听浏览器发过来的请求 并动态创建IOC容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置SpringMVC -->
<!-- 配置前端控制器,拦截相应的请求 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置过滤器来处理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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 浏览器form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,所以添加过滤器转化 -->
<!-- 配置过滤器来将PUT请求转化为PUT DELETE请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 默认的访问文件 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

对应的编辑SpringMVC的配置文件 springmvc.xml(注意这个xml的类型是 Spring Bean Configuration File)

<?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 http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 配置扫描包,使SpringMVC只扫描Controller层 -->
<context:component-scan base-package="com.neuedu" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!-- 可以处理静态资源 -->
<mvc:default-servlet-handler />
<!-- 标配,功能强大,诸多用处。例如使处理静态资源后RequestMapping继续能够使用等功能 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>

对应配置Spring的配置文件 spring.xml 文件类型同上,不过我们通常命名为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"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 扫描相关除去Controller的包 -->
<context:component-scan base-package="com.neuedu" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 加载外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0数据源 -->
<bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
</bean>
<!-- 配置事务管理 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="comboPooledDataSource"></property>
</bean>
<!-- 开启基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!-- Spring与MyBatis整合 -->
<!-- 配置SqlSession工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="comboPooledDataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" ></property>
</bean>
<!-- 扫描Mapper包 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.neuedu.mapper"></property>
</bean>
</beans>

这里有个jdbc.properties外部文件 连接数据库使用,读者视情况修改

jdbc.username:root
jdbc.password:123456
jdbc.driver:com.mysql.jdbc.Driver
jdbc.url:jdbc:mysql://localhost:3306/studentmanage

对应配置MyBatis的配置文件 mybatis-config.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>
<properties resource="jdbc.properties"></properties>
<settings>
<!-- 驼峰式命名 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>

如果想要在控制台打印日志 可添加log4j.xml 这个文件固定,请读者自行按需添加,在此不做赘述。

至此,配置完毕。然后在src下建立相应的包即可,一般来说

bean 通用实体类                                            -------------------------------------------   与数据库表对应的类

mapper 存放mapper接口和对应的.xml 文件  ------------------------------------------    由MyBatis 管理

service 处理业务逻辑                                    -------------------------------------------   由Spring管理

controller  与前端进行交互                             --------------------------------------------  由SpringMVC管理

好,废话不多说,开始项目(以一个简单的显示学生列表的方式展示SSM)

建数据库:

简单易学的SSM(Spring+SpringMVC+MyBatis)整合

在bean包中建立Stu.java

在mapper包中建立接口StuMapper.java 和对应的StuMapper.xml  SQL映射文件

在sevice包的StuServce.java 中调用接口中的方法

在controller中StuController 中调用Service层的方法 然后讲结果返回给JSP页面显示

具体代码如下:

Stu.java:
package com.neuedu.bean; public class Stu {
private int ID;
private String UserName;
private String PassWord;
public Stu() {
super();
}
public Stu(int iD, String userName, String passWord) {
super();
ID = iD;
UserName = userName;
PassWord = passWord;
}
public Stu(String userName, String passWord) {
super();
UserName = userName;
PassWord = passWord;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getPassWord() {
return PassWord;
}
public void setPassWord(String passWord) {
PassWord = passWord;
}
@Override
public String toString() {
return "Stu [ID=" + ID + ", UserName=" + UserName + ", PassWord=" + PassWord + "]";
} }
StuMapper.java:
package com.neuedu.mapper; import java.util.List; import com.neuedu.bean.Stu; public interface StuMapper {
public List<Stu> getStuList();
}
StuMapper.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.neuedu.mapper.StuMapper">
<select id="getStuList" resultType="com.neuedu.bean.Stu">
select * from stu
</select> </mapper>
StuService.java:
package com.neuedu.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.neuedu.bean.Stu;
import com.neuedu.mapper.StuMapper;
@Service
public class StudentService { @Autowired
private StuMapper mapper; public List<Stu> getStuList() {
return mapper.getStuList();
}
}
StuController.java:
package com.neuedu.controller; import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.neuedu.bean.Stu;
import com.neuedu.service.StudentService;
@Controller
public class StuController {
@Autowired
private StudentService studentService;
@RequestMapping(value="/getStuList")
public String getStuList(Map<String,Object> map){
List<Stu> list=studentService.getStuList();
map.put("stulist", list);
return "StudentList";
}
}
StudentList.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<title>学生信息展示</title>
</head>
<body>
<h1 align="center">学生信息</h1>
<div align="center">
<form action="${pageContext.request.contextPath}/queryStu" method="post">
<input type="text" name="queryname" placeholder="请输入将要查找的姓名" >
<input type="submit" value="查询"/>
</form>
</div>
<table border="1" align="center" width="50%">
<tr>
<th>姓名</th>
<th>密码</th>
<th colspan="2">操作</th>
</tr>
<c:forEach items="${stulist}" var="stu">
<tr>
<td>${stu.userName}</td>
<td>${stu.passWord}</td>
<td><a href="${pageContext.request.contextPath}/deleteStu?id=${stu.ID}">删除</a></td>
<td><a href="${pageContext.request.contextPath}/toUpdateStu?id=${stu.ID}">修改</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="5" align="center" ><a href="${pageContext.request.contextPath}/toAddStu">添加</a> </td>
</tr>
</table>
<br/>
</body>
</html>

页面显示:

简单易学的SSM(Spring+SpringMVC+MyBatis)整合

 第一次写这么多,有什么错误的地方欢迎批评指正!

上一篇:安装torch-opencv


下一篇:一次Linux服务器被入侵和删除木马程序的经历