springmvc+mybatis整合SSM案例教程

时间:2020-12-07 16:36:40

最近一段时间在学习ssm框架,搭建成功的框架没几个,不是jar错误就是配置文件内容写错,总结了几点经验,在这里跟大家分享一下:

1、jar尽量要统一;(spring使用jar尽量都是同一版本的,其它的也是一样)

2、XML配置文件,要仔细编码,很多的错误都是xml引起的,它不像是代码片段可调试,一旦报错,需要我们仔细排查了


下面说下今天的主题:SSM框架。(在文章最后我会把源码放上去,需要的朋友可以做个参考)

先预览下项目

springmvc+mybatis整合SSM案例教程

1、导入所需jar包

aopalliance-1.0.jar
aspectjweaver-1.7.1.jar
commons-logging-1.1.3.jar
commons-pool-1.6.jar
json-lib-2.4-jdk15.jar
junit-4.8.2.jar
mybatis-3.4.1.jar
mybatis-spring-1.3.0.jar
ojdbc14.jar
spring-aop-4.3.5.RELEASE.jar
spring-aspects-4.3.5.RELEASE.jar
spring-beans-4.3.5.RELEASE.jar
spring-context-4.3.5.RELEASE.jar
spring-context-support-4.3.5.RELEASE.jar
spring-core-4.3.5.RELEASE.jar
spring-expression-4.3.5.RELEASE.jar
spring-jdbc-4.3.5.RELEASE.jar
spring-tx-4.3.5.RELEASE.jar
spring-web-4.3.5.RELEASE.jar
spring-webmvc-4.3.5.RELEASE.jar


这里的jar可分为及部分:

1)、spring所需的jar(这里我使用的是4.3.5版本的)

2)、使用spring所需jar

3)、mybatis所需jar

4)、连接数据所需jar

5)、Junit所需jar

大致可分为这五部分


2编写web.xml文件

这里的web.xml所需配置并不多,包括两部分

1)、Springmvc的核心控制器:DispatcherServlet

2)、 防止post请求乱码:CharacterEncodingFilter

完整的配置如下:web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- springmvc前端控制器 -->
<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:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- 解决中文乱码 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
</web-app>


3、编写applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"
default-autowire="byName">


<!-- 配置DataSource数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@192.168.6.25:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean>

<!--配置工厂, 创建SqlSessionFactoryBean,同时指定数据源
ref="dataSource" :指定的是数据源中的id
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:cn/ssm/entity/empMapper.xml"></property>
</bean>

<!-- 配置MapperScannerConfigurer
value="sqlSessionFactory"指定的是Session工厂的id
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="cn.ssm.dao"></property>
</bean>


<!-- 开启注解扫描 -->
<context:component-scan base-package="com.ssm"/>

<!-- 开启RequestMapping 注解 -->
<mvc:annotation-driven />

<!-- 处理请求转发 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/emp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>


4、实体类

emp实体类:

package cn.ssm.entity;

import java.sql.Date;

public class Emp {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Double sal;
private Double comm;
private Integer deptno;

public Integer getEmpno() {
return empno;
}

public void setEmpno(Integer empno) {
this.empno = empno;
}

public String getEname() {
return ename;
}

public void setEname(String ename) {
this.ename = ename;
}

public String getJob() {
return job;
}

public void setJob(String job) {
this.job = job;
}

public Integer getMgr() {
return mgr;
}

public void setMgr(Integer mgr) {
this.mgr = mgr;
}

public Date getHiredate() {
return hiredate;
}

public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}

public Double getSal() {
return sal;
}

public void setSal(Double sal) {
this.sal = sal;
}

public Double getComm() {
return comm;
}

public void setComm(Double comm) {
this.comm = comm;
}

public Integer getDeptno() {
return deptno;
}

public void setDeptno(Integer deptno) {
this.deptno = deptno;
}

}

Condition实体类

package cn.ssm.entity;

import java.util.List;

public class Condition {
private Integer deptno;
private Double salary;
private List<Integer> empnos;

public Integer getDeptno() {
return deptno;
}

public void setDeptno(Integer deptno) {
this.deptno = deptno;
}

public Double getSalary() {
return salary;
}

public void setSalary(Double salary) {
this.salary = salary;
}

public List<Integer> getEmpnos() {
return empnos;
}

public void setEmpnos(List<Integer> empnos) {
this.empnos = empnos;
}

}


5、编写Dao接口

package cn.ssm.dao;

import java.util.List;
import cn.ssm.entity.Condition;
import cn.ssm.entity.Emp;

public interface EmpDao {
public List<Emp> findAll(); // 查询全部

public List<Emp> findByDept(Condition cond); // 根据部门查询

public List<Emp> findBySalary(Condition cond); // 大于当前工资

public List<Emp> findByDeptAndSalary(Condition cond); // 查询当前部门下,大于当前收入的员工

public void update(Emp emp);// 更新员工信息

public List<Emp> findByDeptAndSalary2(Condition cond); // 查询当前部门下,大于当前收入的员工

public void update2(Emp emp);// 更新员工信息

public List<Emp> findById(Condition cond); // 根据id查询
}


6、编写实体类映射mapper.xml文件  (与实体类在同一目录下,从applicationContext.xml文件中可看出)

empMapper.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="cn.ssm.dao.EmpDao">

<!-- 查询全部的员工 -->
<select id="findAll" resultType="cn.ssm.entity.Emp">
select * from t_emp
</select>

<!-- if的用法 -->
<select id="findByDept" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">
select * from t_emp
<if test="deptno !=null">
where deptno = #{deptno}
</if>
</select>

<!-- chose的用法 -->
<select id="findBySalary" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">
select * from t_emp
<choose>
<when test="salary>3000">
where sal>#{salary}
</when>
<otherwise>
where sal>3000
</otherwise>
</choose>
</select>

<!-- where -->
<!-- 查询当前部门下,大于当前收入的员工-->
<select id="findByDeptAndSalary" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">
select * from t_emp
<where>
<if test="deptno !=null">
and deptno=#{deptno}
</if>
<if test="salary!=null">
and sal>#{salary}
</if>
</where>
</select>

<!-- update -->
<!-- 更新员工信息 -->
<update id="update" parameterType="cn.ssm.entity.Condition">
update t_emp
<set>
<if test="ename!=null">
ename=#{ename}
</if>
<if test="job!=null">
job=#{job}
</if>
</set>
where empno=#{empno}
</update>

<!-- 使用trim代替where -->
<!-- 查询 -->
<select id="findByDeptAndSalary2" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">
select * from t_emp
<trim prefix="where" prefixOverrides="and" >
<if test="deptno!=null">
and deptno=#{deptno}
</if>
<if test="salary !=null">
and sal>#{salary}
</if>
</trim>
</select>
<!-- 使用trim代替set -->
<!-- 更新 -->
<update id="update2">
update t_emp
<trim prefix="set" prefixOverrides="," >
<if test="ename!=null">
ename=#{ename},
</if>
<if test="job!=null">
job=#{job},
</if>
</trim>
where empno=#{empno}
</update>

<!-- 根据id查询 -->
<select id="findById" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">
select * from t_emp where empno in
<foreach collection="empnos" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</select>
</mapper>

7、编写Junti测试文件

package cn.ssm.test;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.ssm.dao.EmpDao;
import cn.ssm.entity.Condition;
import cn.ssm.entity.Emp;



public class TestEmp {


/**
* 查询全部
*/
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = ctx.getBean(EmpDao.class);
List<Emp> list = dao.findAll();
for (Emp e : list) {
System.out.println(e.getEmpno() + " " + e.getEname() + " "
+ e.getJob());
}
}

/**
* 根据部门查询
*/
@Test
public void Testfind() {

ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = ctx.getBean(EmpDao.class);

Condition condition = new Condition();
condition.setDeptno(10);
List<Emp> list = dao.findByDept(condition);
for (Emp emp : list) {
System.out.println(emp.getEname() + " " + emp.getJob());
}
}

/**
* 查询大于当前收入的员工
*/
@Test
public void testfindbysalary() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = ctx.getBean(EmpDao.class);
Condition condition = new Condition();
condition.setSalary(4000.0);
List<Emp> list = dao.findBySalary(condition);
for (Emp emp : list) {
System.out.println(emp.getDeptno() + " " + emp.getJob() + " "
+ emp.getMgr());
}

}

/**
* 查询当前部门下,大于当前收入的员工
*/
public void testfindByDeptAndSalary() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = context.getBean(EmpDao.class);
Condition condition = new Condition();

condition.setDeptno(20);
condition.setSalary(2000.0);
List<Emp> list = dao.findByDeptAndSalary(condition);
for (Emp emp : list) {
System.out.println(emp.getEname() + " " + emp.getEname());
}
}

/**
* 查询当前部门下,大于当前收入的员工
*/
@Test
public void testfindByDeptAndSalary2() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = context.getBean(EmpDao.class);
Condition condition = new Condition();

condition.setDeptno(20);
condition.setSalary(2000.0);
List<Emp> list = dao.findByDeptAndSalary(condition);
for (Emp emp : list) {
System.out.println(emp.getEname() + " " + emp.getEname());
}
}

/**
* 更新员工信息
*/
public void testupdate() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = context.getBean(EmpDao.class);
Emp emp = new Emp();
emp.setEmpno(14);
emp.setEname("Tom");
dao.update(emp);

}

/**
* 更新员工信息
*/
public void testupdate2() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = context.getBean(EmpDao.class);
Emp emp = new Emp();
emp.setEmpno(14);
emp.setEname("Tom");
dao.update(emp);
}

/**
* 根据id查询
*/
@Test
public void testFindById() {
ApplicationContext axt = new ClassPathXmlApplicationContext(
"applicationContext.xml");
EmpDao dao = axt.getBean(EmpDao.class);
List<Integer> ids = new ArrayList<Integer>();
ids.add(3);
ids.add(10);
Condition cond = new Condition();
cond.setEmpnos(ids);
List<Emp> list = dao.findById(cond);
for (Emp emp : list) {
System.out.println(emp.getEname() + " " + emp.getDeptno());
}

}
}


8、编写Controller进行测试

package cn.ssm.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ssm.dao.EmpDao;
import cn.ssm.entity.Emp;


@Controller
public class EmpController {
@Resource
private EmpDao empDao;
public void setEmpDao(EmpDao empDao) {
this.empDao = empDao;
}

@RequestMapping("/findEmp.do")
public String find(Model model) {
List<Emp> list = empDao.findAll();
model.addAttribute("emps", list);
return "emp_list";
}
}

9、编写jsp页面

根据applicationContext.xml中的配置,我们在WEB-INF中建立emp文件夹,然后建立emp_list.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'emp_list.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<body style="text-align: center;">
<table width="80%" border="1" cellpadding="2" cellspacing="0">
<tr>
<th>EMPNO</th>
<th>ENAME</th>
<th>JOB</th>
<th>MGR</th>
<th>HIREDATE</th>
<th>SAL</th>
<th>COMM</th>
<th>DEPTNO</th>
</tr>
<c:forEach items="${emps}" var="emp">
<tr>
<td>${emp.empno}</td>
<td>${emp.ename}</td>
<td>${emp.job}</td>
<td>${emp.mgr}</td>
<td>${emp.hiredate}</td>
<td>${emp.sal}</td>
<td>${emp.comm}</td>
<td>${emp.deptno}</td>
</tr>

</c:forEach>
</table>
</body>

</html>

10、测试

在浏览器中输入:http://localhost:8080/SSMDemo/findEmp.do即可

springmvc+mybatis整合SSM案例教程

11、源码下载:SSMDemo

(项目预览图中有个db.properties没有用到,

<!-- 读取属性文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"></property>
</bean>

<!-- 配置DataSource数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>

把applicationContext.xml修改成这样就可以了。两种方式都可以,有问题可以在文章末尾处浏览,大家一起学习