SSM(SpringMVC+Sping+Mybatis)整合

源码下载:https://github.com/rj2017211811/Spring-SpringMVC-Mybatics-
1.所需jar包
SSM(SpringMVC+Sping+Mybatis)整合
SSM(SpringMVC+Sping+Mybatis)整合
2.项目目录
SSM(SpringMVC+Sping+Mybatis)整合
3.web.xml:配置spring容器文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">

    <!-- 配置beans.xml的路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:beans.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

	</listener>

	<!-- 配置DispatcherServlet -->
	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置spring-mvc.xm的路径 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>/</url-pattern>
		
	</servlet-mapping>
	<display-name>myssm</display-name>
	<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>

4.log4j.properties:记录日志

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=error, stdout

log4j.logger.com.springframework=DEBUG
log4j.logger.com.ibatis=DEBUG  
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG  
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG  
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG  

log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG  
log4j.logger.java.sql.ResultSet=DEBUG

5.spring-mvc.xml文件:配置view层路径和注解controller

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"

	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
				
				http://www.springframework.org/schema/mvc
				http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context-4.2.xsd">
	<!-- 自动扫描controller -->			
	<context:component-scan base-package="per.czt.ssm.controller"/>
	<!--注解驱动 -->
	<mvc:annotation-driven/>
	
	<!-- 内部视图资源解析器 -->
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/public/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>

6.beans.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
				         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
				         http://www.springframework.org/schema/context
				         http://www.springframework.org/schema/context/spring-context-3.0.xsd
				         http://www.springframework.org/schema/tx
				         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
				         http://www.springframework.org/schema/aop 
				         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

		<!-- 数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/ssmdb?useSSL=false&amp;serverTimezone=UTC&amp;characterEncoding=utf-8"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
	</bean>
	
	<!-- 配置sessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 事务相关控制 -->
	<bean name="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!-- 通知 -->
	<tx:advice id="userTxAdvice"
		transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" read-only="true" />
			<tx:method name="get*" read-only="true" />
			<tx:method name="select*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:pointcut id="pc" expression="execution(* per.czt.ssm.service.*.*(..))" />
		<!--把事务控制在Service层-->
		<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
	</aop:config>
	<!-- 为userDao配置sqlSessionFactory -->
	<bean id="userDao" class="per.czt.ssm.dao.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>
	<!-- 为userService配置dao -->
	
	<bean id="userService" class="per.czt.ssm.service.UserServiceImpl">
		<property name="userDao" ref="userDao"></property>
	</bean>
</beans>

7.sqlMapConfig.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>
		<typeAlias type="per.czt.ssm.domain.User" alias="User"/>
	</typeAliases>
	<mappers >
	    <mapper resource="per/czt/ssm/domain/User.xml"/>
	</mappers>
</configuration>

8.User对象和User.xml映射文件
User.java

在这里插入代码片
```package per.czt.ssm.domain;

public class User {
	private Integer id;
	private String username;
	
	private String password;
	private Integer grade;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getGrade() {
		return grade;
	}
	public void setGrade(Integer grade) {
		this.grade = grade;
	}
	
	
}

User.xml

<?xml version="1.0" encoding="UTF-8"?> select * from user where 1=1 and id=#{id} and username=#{username} and password=#{password}
</select>
<insert id="insert" parameterType="per.czt.ssm.domain.User">
	insert into user(username,password) values(#{username},#{password})
</insert>
<delete id="delete" parameterType="per.czt.ssm.domain.User">
	delete from user where 1=1
	<if test="id!=null">
		and id=#{id}
	</if>
	<if test="username!=null">
		and username=#{username}
	</if>
	<if test="password!=null">
		and password=#{password}
	</if>
</delete>
<update id="update" parameterType="per.czt.ssm.domain.User">
	update user
	<set>
		<if test="username!=null">
			username=#{username},
		</if>
		<if test="password!=null">
			password=#{password}
		</if>
	</set>

	where id=#{id}
</update>
``` 9.dao层:根据User.xml定义的各种sql操作数据库 UserDao接口
package per.czt.ssm.dao;

import java.util.List;

import per.czt.ssm.domain.User;

public interface UserDao {
	public List<User> searchAll();
	public int insert(User u);
	public int delete(User u);
	public int update(User u);
	public List<User> search(User u);
	

}

UserDaoImpl实现类

package per.czt.ssm.dao;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

import per.czt.ssm.domain.User;
@Repository("userDao")
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

	
	@Override
	public List<User> searchAll() {
		List<User> userList=this.getSqlSession().selectList("per.czt.mybatics.domain.User.search", null);
		return userList;
	}

	@Override
	public int insert(User u) {
		int flag=this.getSqlSession().insert("per.czt.mybatics.domain.User.insert", u);
		this.getSqlSession().commit();
		
		return flag;
	}

	@Override
	public int delete(User u) {
		int flag=this.getSqlSession().delete("per.czt.mybatics.domain.User.delete", u);
		this.getSqlSession().commit();
		return flag;
	}

	@Override
	public int update(User u) {
		int flag=this.getSqlSession().update("per.czt.mybatics.domain.User.update", u);
		this.getSqlSession().commit();
		return flag;
	}

	

	@Override`在这里插入代码片`
	public List<User> search(User u) {
		List<User>  userList=this.getSqlSession().selectList("per.czt.mybatics.domain.User.search", u);
		//this.getSqlSession().commit();
		return userList;
	}
	

}

10.service层:处理dao层结果返回
UserService接口

package per.czt.ssm.service;

import java.util.List;

import per.czt.ssm.domain.User;

public interface UserService {
	public List<User> searchAll();
	public int insert(User u);
	public int delete(User u);
	public int update(User u);
	public List<User> search(User u);
}

UserDaoImpl实现类

package per.czt.ssm.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import per.czt.ssm.dao.UserDao;
import per.czt.ssm.domain.User;
@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource(name="userDao")
	private UserDao userDao;
	

	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	@Override
	public List<User> searchAll() {
		
		return userDao.searchAll();
	}


	@Override
	public int insert(User u) {
		// TODO Auto-generated method stub
		return userDao.insert(u);
	}


	@Override
	public int delete(User u) {
		// TODO Auto-generated method stub
		return userDao.delete(u);
	}


	@Override
	public int update(User u) {
		// TODO Auto-generated method stub
		return userDao.update(u);
	}


	@Override
	public List<User> search(User u) {
		// TODO Auto-generated method stub
		return userDao.search(u);
	}

}

10.controller层:处理service层结构,返回给view层
HomeController.java

package per.czt.ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
	@RequestMapping("/home")
	public String goHome()
	{
		System.out.println("通过了homeController");
		return "index";
	}

}

UserController.java

package per.czt.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 per.czt.ssm.domain.User;
import per.czt.ssm.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	@RequestMapping("/listAll")
	public String listAll(Model model)
	{
		List<User> userList=userService.searchAll();
		model.addAttribute(userList);
		
		System.out.println("显示列表");
		return "/user/userList";
	}
	@RequestMapping("/delete")
	public String delete(Integer id)
	{
		User u=new User();
		u.setId(id);
		int flag=userService.delete(u);
		if(flag==1)
		{
			System.out.println("删除成功");
		}
		else
		{
			System.out.println("删除失败");
		}
		return "redirect:/user/listAll";
	}
	
	
	@RequestMapping("/toAdd")
	public String toAdd()
	{
		
		return "/user/userAdd";
	}
	
	@RequestMapping("/add")
	public String add(String username,String password)
	{
		User u=new User();
		u.setUsername(username);
		u.setPassword(password);
		int flag=userService.insert(u);
		if(flag==1)
		{
			System.out.println("增加成功");
		}
		else
		{
			System.out.println("增加失败");
		}
		return "redirect:/user/listAll";
	}
	
	@RequestMapping("/toUpdate")
	public String toUpdate(Integer id,Model model)
	{
		User u=new User();
		u.setId(id);
	
		model.addAttribute(u);
		return "/user/userUpdate";
	}
	
	@RequestMapping("/update")
	public String update(User user,Model model)
	{
		
	
		int flag=userService.update(user);
		if(flag==1)
		{
			System.out.println("更新成功");
		}
		else
		{
			System.out.println("更新失败");
		}
		return "redirect:/user/listAll";
	}
	
}

11.view层:显示
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<jsp:forward page="/WEB-INF/public/index.jsp"></jsp:forward>
</body>
</html>

/WEB-INF/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="${pageContext.request.contextPath }/user/listAll.action">显示列表</a><br>
	
	<a href="${pageContext.request.contextPath }/user/toAdd.action">增加用户</a><br>
</body>
</html>

/WEB-INF/user/userList.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>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table border="1">
		<thead>
			<tr>
				<th>id</th>
				<th>username</th>
				<th>password</th>
				<th>删除</th>
				<th>修改</th>
			</tr>

		</thead>
		<tbody>
			<c:forEach items="${userList }" var="user">
				<tr>
					<td>${user.id }</td>
					<td>${user.username }</td>
					<td>${user.password }</td>
					<td><a href="${pageContext.request.contextPath }/user/delete.action?id=${user.id }">删除</a></td>
					<td><a href="${pageContext.request.contextPath }/user/toUpdate.action?id=${user.id }">修改</a></td>
				</tr>

			</c:forEach>


		</tbody>

	</table>
	<a href="${pageContext.request.contextPath }">返回主界面</a>
</body>
</html>

/WEB-INF/user/userAdd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>添加用户</h1>
	<form action="${pageContext.request.contextPath }/user/add.action" method="post">
		<table>
			<tr><th>username</th><td><input type="text" name="username"></td></tr>
			<tr><th>password</th><td><input type="password" name="password"> </td></tr>
	        <tr><td colspan="2"><input type="submit" value="添加"> </td></tr>
	    </table>
	</form>
		<a href="${pageContext.request.contextPath }/user/listAll.action">返回列表</a><br>
</body>
</html>

/WEB-INF/user/userUpdate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>修改用户</h1>
	<form action="${pageContext.request.contextPath }/user/update.action" method="post">
		<table>
		<tr><th>id</th><td><input type="text" name="id"  value="${user.id }" readonly="readonly"></td></tr>
			<tr><th>username</th><td><input type="text" name="username" value="${user.username }"> </td></tr>
			<tr><th>password</th><td><input type="password" name="password" value="${user.password }"> </td></tr>
	        <tr><td colspan="2"><input type="submit" value="修改"> </td></tr>
	    </table>
	</form>
	<a href="${pageContext.request.contextPath }/user/listAll.action">返回列表</a><br>
	
</body>
</html>