- SSM整合案例
项目工程目录
导入pom.xml
<?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">
<parent>
<artifactId>com.liu.Spring_ioc</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>com.liu.spring_ssm</artifactId>
<dependencies>
<!--spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--servlet和jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!--mybatis相关-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
appliacationContext.xml: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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--组件扫描service和mapper-->
<context:component-scan base-package="com.liu">
<!--排除controller的扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--加载jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--引用数据源c3p0-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--集成mybatis-->
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--加载mybatis核心文件-->
<property name="configLocation" value="classpath:sqlMapConfig-spring.xml"/>
</bean>
<!--扫描mapper所在的包 为mapper创建实现类 自动产生bean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.liu.mapper"/>
</bean>
<!--集成mybatis-->
<!--声明式事务控制-->
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事務增强-->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--事务的aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.liu.service.impl.*.*(..))"/>
</aop:config>
</beans>
jdbc.properties文件
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123lyl
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
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
spring-mvc(web层核心配置文件)
<?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="com.liu.domain.Account" alias="account"></typeAlias>-->
<!--默认扫描com.liu.mapper包下的接口,会自动生成别名,别名是接口名(大or小写)-->
<package name="com.liu.domain"/>
</typeAliases>
<!---->
</configuration>
<?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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--组件扫描 主要扫描controller-->
<context:component-scan base-package="com.liu.controller"/>
<!--配置mvc的注解驱动-->
<mvc:annotation-driven/>
<!--内部资源解析器-->
<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--开放静态资源访问权限-->
<mvc:default-servlet-handler/>
</beans>
sqlMapConfig-spring.xml------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>
<!--定义别名-->
<typeAliases>
<!--<typeAlias type="com.liu.domain.Account" alias="account"></typeAlias>-->
<!--默认扫描com.liu.mapper包下的接口,会自动生成别名,别名是接口名(大or小写)-->
<package name="com.liu.domain"/>
</typeAliases>
<!---->
</configuration>
web工程核心配置文件(spring)
<?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">
<!--配置spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--springmvc的前端控制器-->
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!--代表任何访问都要进入我的springmvc框架-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--乱码过滤器-->
<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>
</web-app>
AccountMapper.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">
<!--namespace 命名空间 就是你的mapper接口全限类名-->
<mapper namespace="com.liu.mapper.AccountMapper">
<!--抽取sql片段-->
<sql id="files">
select * from account
</sql>
<select id="findAll" resultType="account">
<include refid="files"></include>
</select>
<select id="findById" parameterType="int" resultType="account">
select * from account where id=#{id}
</select>
<insert id="save" parameterType="account">
insert into account(name,money) values (#{name},#{money})
</insert>
<delete id="delete" parameterType="int">
delete from account where id=#{id}
</delete>
<update id="update" parameterType="account">
update account set name = #{name},money = #{money} where id = #{id}
</update>
<select id="findLikeName" parameterType="account" resultType="account">
select * from account
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
</where>
</select>
</mapper>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1><a href="${pageContext.request.contextPath}/account/findAll"> hello world!!!</a></h1>
</body>
</html>
save.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加</title>
</head>
<body>
<h1>添加账户信息表单</h1>
<form name="accountForm" action="${pageContext.request.contextPath}/account/save" method="post">
账户名称:<input type="text" name="name"><br>
账户金额:<input type="text" name="money"><br>
<input type="submit" value="保存"><br>
</form>
</body>
</html>
update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/account/update" method="post">
<input type="hidden" name="id" value="${account.id}">
<--没有隐藏域表单的id,修改不了,踩坑踩坑踩坑踩坑--></--没有隐藏域表单的id,修改不了,踩坑踩坑踩坑踩坑-->
名称: <input type="text" name="name" value="${account.name}"> <br>
名称: <input type="text" name="money" value="${account.money}"> <br>
<input type="submit" value="编辑完成">
</form>
</body>
</html>
accountList.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User:
Date: 2022/2/10
Time: 17:03
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>展示账户数据列表
<a href="${pageContext.request.contextPath}/save.jsp">添加</a>
</h1>
<form action="${pageContext.request.contextPath}/account/like" method="post">
<input type="text" name="name">
<input type="submit">
</form>
<table border="1px">
<tr>
<th>账户编号</th>
<th>账户名称</th>
<th>账户金额</th>
<th> 操 作</th>
</tr>
<c:forEach items="${accountList}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
<td>
<a href="javascript:void(0)" οnclick="del('${account.id}')">删除</a>
<a href="${pageContext.request.contextPath}/account/toUpdate?id=${account.id}">修改</a>
</td>
</tr>
</c:forEach>
</table>
<script>
function del(accountId) {
if (confirm("你确定要删除吗??")) {
location.href = "${pageContext.request.contextPath}/account/delete/" + accountId;
}
}
</script>
</body>
</html>
controller层
package com.liu.controller;
import com.liu.domain.Account;
import com.liu.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* @author Liu
* @date 2022/2/10
* @apiNote
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
//保存
@RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
public String save(Account account) {
accountService.save(account);
return "redirect:/account/findAll";
}
//查询
@RequestMapping("/findAll")
public ModelAndView findAll() {
List<Account> accountList = accountService.findAll();
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("accountList");
return modelAndView;
}
@RequestMapping("/like")
public ModelAndView findLikeName(String name) {
List<Account> likeName = accountService.findLikeName(name);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("accountList",likeName);
modelAndView.setViewName("accountList");
return modelAndView;
}
@RequestMapping("/delete/{accountId}")
public String delete(@PathVariable("accountId") Integer accountId){
System.out.println(accountService.delete(accountId));
return "redirect:/account/findAll";
}
@RequestMapping("/toUpdate")
public String toUpdate(int id, Model model){
Account serviceById = accountService.findById(id);
model.addAttribute("account",serviceById);
return "update";
}
@RequestMapping("/update")
public String update(Account account){
accountService.update(account);
return "redirect:/account/findAll";
}
}
service层
package com.liu.service.impl;
import com.liu.domain.Account;
import com.liu.mapper.AccountMapper;
import com.liu.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author Liu
* @date 2022/2/10
* @apiNote
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
public void save(Account account) {
accountMapper.save(account);
}
public List<Account> findAll() {
List<Account> accountList = accountMapper.findAll();
return accountList;
}
public Account findById(int id) {
return accountMapper.findById(id);
}
public int delete(int id) {
int re = accountMapper.delete(id);
return re;
}
public List<Account> findLikeName(String name) {
return accountMapper.findLikeName(name);
}
public void update(Account account) {
accountMapper.update(account);
}
}
package com.liu.mapper;
import com.liu.domain.Account;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author Liu
* @date 2022/2/10
* @apiNote
*/
public interface AccountMapper {
void save(Account account);
List<Account> findAll();
Account findById(int id);
int delete(int id);
List<Account> findLikeName(@Param("name") String name);
//设置参数的目的在于,表单name属性传过来,与之匹配,然后就mybatis识别,查询成功,返回给页面。
void update(Account account);
}
javaBean
package com.liu.domain;
/**
* @author Liu
* @date 2022/2/10
* @apiNote
*/
public class Account {
private Integer id;
private String name;
private Double money;
public Account() {
}
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 Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}