在SSM整合的时候,我们是用Spring框架去整合SpringMVC框架和MyBatis框架。
create database ssm;
create table account(
id int primary key auto_increment,
name varchar(100),
money double(7,2),
);
MyBatis 和 Spring 的版本对应关系
pom.xml
<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">
<modelVersion>4.0.0modelVersion>
<groupId>com.keafmdgroupId>
<artifactId>ssmartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>ssm Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<spring.version>5.2.7.RELEASEspring.version>
<slf4j.version>1.7.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<mysql.version>5.1.49mysql.version>
<mybatis.version>3.4.5mybatis.version>
properties>
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.5version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>compilescope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.2version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.1version>
<type>jartype>
<scope>compilescope>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
Account:
package com.keafmd.domain;
import java.io.Serializable;
/**
* Keafmd
*
* @ClassName: Account
* @Description: 账户实体类
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:03
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
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 +
'}';
}
}
package com.keafmd.dao;
import com.keafmd.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountDao
* @Description: 账户dao接口
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:05
*/
public interface AccountDao {
//查询所有账户
public List<Account> findAll();
//保存账户
public void saveAccount(Account account);
}
package com.keafmd.service;
import com.keafmd.domain.Account;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountService
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:15
*/
public interface AccountService {
//查询所有账户
public List<Account> findAll();
//保存账户
public void saveAccount(Account account);
}
package com.keafmd.service.impl;
import com.keafmd.dao.AccountDao;
import com.keafmd.domain.Account;
import com.keafmd.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountServiceImpl
* @Description: 账户的业务层实现类
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:16
*/
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("业务层,查询所有。。。");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层,保存账户。。。");
}
}
package com.keafmd.controller;
/**
* Keafmd
*
* @ClassName: AccountController
* @Description: 账户控制器 web
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:19
*/
public class AccountController {
}
applicationContext.xml:
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.keafmd">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
beans>
AccountServiceImpl:
package com.keafmd.service.impl;
import com.keafmd.dao.AccountDao;
import com.keafmd.domain.Account;
import com.keafmd.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountServiceImpl
* @Description: 账户的业务层实现类
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:16
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("业务层,查询所有。。。");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层,保存账户。。。");
}
}
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
测试代码:
package com.keafmd.test;
import com.keafmd.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Keafmd
*
* @ClassName: TestSpring
* @Description: 测试类
* @author: 牛哄哄的柯南
* @date: 2021-02-17 22:37
*/
public class TestSpring {
@Test
public void run1(){
//加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//获取对象
AccountService as = (AccountService)ac.getBean("accountService");
//调用方法
as.findAll();
}
}
运行结果:
业务层,查询所有。。。
Process finished with exit code 0
web.xml:
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
springmvc.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.keafmd">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:annotation-driven/>
beans>
index.jsp:
<%--
Created by IntelliJ IDEA.
User: Keafmd
Date: 2021/2/17
Time: 23:20
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>
<a href="account/findAll">测试查询</a>
</body>
</html>
AccountController:
package com.keafmd.controller;
import com.keafmd.domain.Account;
import com.keafmd.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.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountController
* @Description: 账户控制器 web
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:19
*/
@Controller
@RequestMapping("/account")
public class AccountController {
/**
* 查询所有
* @param
* @return
*/
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层,查询所有账户信息。。。");
return "list";
}
}
list.jsp:
<%--
Created by IntelliJ IDEA.
User: Keafmd
Date: 2021/2/18
Time: 15:50
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>查询所有的账户</h1>
</body>
</html>
表现层,查询所有账户信息。。。
目的:在controller中能成功的调用service对象中的方法。
在web.xml添加监听器:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
web.xml:
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
package com.keafmd.controller;
import com.keafmd.domain.Account;
import com.keafmd.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.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountController
* @Description: 账户控制器 web
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:19
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 查询所有
* @return
*/
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层,查询所有账户信息。。。");
//调用service的方法
accountService.findAll();
return "list";
}
}
表现层,查询所有账户信息。。。
业务层,查询所有。。。
SqlMapConfig.xml:
<configuration>
<properties resource="jdbcConfig.properties">properties>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC">transactionManager>
<dataSource type="pooled">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.keafmd.dao"/>
mappers>
configuration>
jdbcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=root
package com.keafmd.dao;
import com.keafmd.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountDao
* @Description: 账户dao接口
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:05
*/
public interface AccountDao {
//查询所有账户
@Select("select * from account")
public List<Account> findAll();
//保存账户
@Insert("insert into account(name,money) values(#{name},#{money})")
public void saveAccount(Account account);
}
TestMybatis:
package com.keafmd.test;
import com.keafmd.dao.AccountDao;
import com.keafmd.domain.Account;
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.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
/**
* Keafmd
*
* @ClassName: TestMybatis
* @Description: 测试Mybatis
* @author: 牛哄哄的柯南
* @date: 2021-02-18 16:37
*/
public class TestMybatis {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private AccountDao accountDao;
@Before
public void init() throws Exception{
//加载配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
factory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession对象
session = factory.openSession();
//获取到代理对象
accountDao = session.getMapper(AccountDao.class);
}
@After
public void destory() throws Exception{
session.commit();
session.close();
in.close();
}
/**
* 查询所有
*/
@Test
public void run1(){
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
}
/**
* 测试保存
*/
@Test
public void saveAccount(){
Account account = new Account();
account.setName("毛利小五郎");
account.setMoney(800.00);
// account.setMoney(800d);
accountDao.saveAccount(account);
}
}
运行run1():
Account{
id=1, name='keafmd', money=9000.0}
Account{
id=2, name='小兰', money=8000.0}
Account{
id=3, name='新一', money=8000.0}
Account{
id=4, name='毛利小五郎', money=800.0}
Account{
id=5, name='怪盗基德', money=660.0}
Account{
id=6, name='某某', money=290.0}
Process finished with exit code 0
整合思路:把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中同时,把 mybatis 配置文件的内容清掉。
把以下内容添加到applicationContext.xml配置文件中:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.keafmd.dao"/>
bean>
SqlMapConfig.xml和jdbcConfig.properties可以删除了。
把以下内容添加到applicationContext.xml配置文件中:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
aop:config>
applicationContext.xml:
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.keafmd">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
<property name="user" value="root"/>
<property name="password" value="18044229"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.keafmd.dao"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
aop:config>
beans>
AccountDao:
package com.keafmd.dao;
import com.keafmd.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountDao
* @Description: 账户dao接口
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:05
*/
@Repository
public interface AccountDao {
//查询所有账户
@Select("select * from account")
public List<Account> findAll();
//保存账户
@Insert("insert into account(name,money) values(#{name},#{money})")
public void saveAccount(Account account);
}
AccountServiceImpl:
package com.keafmd.service.impl;
import com.keafmd.dao.AccountDao;
import com.keafmd.domain.Account;
import com.keafmd.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountServiceImpl
* @Description: 账户的业务层实现类
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:16
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层,查询所有。。。");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层,保存账户。。。");
accountDao.saveAccount(account);
}
}
package com.keafmd.controller;
import com.keafmd.domain.Account;
import com.keafmd.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.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountController
* @Description: 账户控制器 web
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:19
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 查询所有
* @param model
* @return
*/
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("表现层,查询所有账户信息。。。");
//调用service的方法
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
/**
* 保存
* @param account
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/save")
public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
return;
}
}
<%--
Created by IntelliJ IDEA.
User: Keafmd
Date: 2021/2/18
Time: 15:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>查询所有的账户</h1>
<%--${
list}--%>
<c:forEach items="${list}" var="account">
${
account.name}
${
account.money}
</c:forEach>
</body>
</html>
修改index.jsp代码,添加测试保存的代码:
<%--
Created by IntelliJ IDEA.
User: Keafmd
Date: 2021/2/17
Time: 23:20
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>
<a href="account/findAll">测试查询</a>
<h1>测试保存</h1>
<form action="account/save" method="post">
姓名:<input type="text" name="name" /><br/>
金额:<input type="text" name="money" /><br/>
<input type="submit" value="保存">
</form>
</body>
</html>
修改 AccountController 代码,添加save方法:
package com.keafmd.controller;
import com.keafmd.domain.Account;
import com.keafmd.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.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Keafmd
*
* @ClassName: AccountController
* @Description: 账户控制器 web
* @author: 牛哄哄的柯南
* @date: 2021-02-17 21:19
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 查询所有
* @param model
* @return
*/
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("表现层,查询所有账户信息。。。");
//调用service的方法
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
/**
* 保存
* @param account
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/save")
public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
return;
}
}
以上就是SSM整合案例(超详细)的全部内容。
看完如果对你有帮助,感谢点赞支持!
如果你是电脑端的话,看到右下角的 “一键三连” 了吗,没错点它[哈哈]
加油!
共同努力!
Keafmd