SSM整合

2023-05-16

一、spring整合springmvc、mybatis

二、配置文件+注解

1、创建相应的类:dao,controller,domain,service,service.impl

2、首先配置spring,使用注解方式

编写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">

<!--    开启注解的扫描,只处理service和dao,controller不需要spring框架处理,排除掉controller包不扫描-->
    <context:component-scan base-package="cn.rzpt">
<!--        配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService

测试

3、配置springMVC环境

在web.xml配置全端控制器

<web-app>
  <display-name>Archetype Created Web Application</display-name>
<!--  配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--    加载springMVC.xml文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
<!--    启动服务器,创建该Servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <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>

配置springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">

<!--    开启注解扫描,只扫描controller注解-->
    <context:component-scan base-package="cn.rzpt">
<!--        开启扫描哪个类-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
<!--    配置视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--    过滤静态资源-->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
<!--    开启springmvc注解的支持-->
    <mvc:annotation-driven />
</beans>

测试:编辑jsp文件

<a href="account/findAll">测试</a>

编辑controller类

@Controller
@RequestMapping("/account")
public class AccountController {
    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层:查询所有账户信息.....");
        return "list";
    }
}

编辑list.jsp

<h3>查询所有账户信息</h3>

4、spring整合springmvc

思路:在controller中能够调用service方法,则表示整合成功

在controller中依赖注入service对象就可以

那么什么时候构建service对象?

因为tomcat服务器启动,加载web.xml文件,并没有加载applicationConfig.xml

需要在web.xml中配置一个监听器类,用来监听ServletContext的创建和销毁,并提供WEB版本工厂,存储在ServletContext对象中

这个监听器有spring-web提供org.springframework.web.context.ContextLoaderListener

<web-app>
  <display-name>Archetype Created Web Application</display-name>
<!--  配置spring的监听器.默认只加载WEB-INF目录下的applicationContext.xml文件
可以设置配置文件的路径
-->
  <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>
  

controller类中:

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层:查询所有账户信息.....");

        //调用service方法,成功调用整合
        accountService.findAll();

        return "list";
    }
}

5、mybatis配置(采用注解方式)

核心配置文件SqlMapConfig.xml需要配置

与dao匹配的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>
<!--    配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="zxn682899"/>
            </dataSource>
        </environment>
    </environments>
    
<!--    引入映射配置文件-->
    <mappers>
<!--        resource是使用配置文件的方式,使用注解的话不能使用resource-->
<!--        <mapper resource="cn/rzpt/dao/AccountDao.xml"></mapper>-->
<!--        <mapper class="cn.rzpt.dao.AccountDao"/>-->
<!--        使用package,包内的所有类都可以访问到-->
        <package name="cn.rzpt.dao"/>
    </mappers>
</configuration>

dao注解:

@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);
}

测试类:

@Test
public void run1() throws IOException {
    //加载配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //创建SQLSessionFactory对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //创建SqlSession对象
    SqlSession session = factory.openSession();
    //获取到代理对象
    AccountDao dao = session.getMapper(AccountDao.class);
    //查询所有数据
    List<Account> list = dao.findAll();
    for(Account account : list){
        System.out.println(account);
    }
    //关闭资源
    session.close();
    in.close();
}

6、spring整合mybatis

思路:如何把代理对象存到spring容器中

//获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class);

在applicationConfig.xml中配置mybatis整合

<!--spring整合mybatis框架-->
<!--    1:配置连接池-->
    <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="zxn68289"/>
    </bean>
<!--    2:配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    3:配置AccountDao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.rzpt.dao"/>
    </bean>

service中:

@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);
    }
}

controller中

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表现层:查询所有账户信息.....");

        //调用service方法,成功调用整合
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);

        return "list";
    }
}

list.jsp中

<%@ 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>
<h3>查询所有账户信息</h3>
<c:forEach items="${list}" var="account">
    ${account.name}<br>
    ${account.money}<br>
</c:forEach>

注意&符合改成:&amp;

?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8

7、spring整合mybatis事务框架

保存数据需要事务开启

配置事务在apllication中,加入:


<!--    配置spring框架声明式事务管理-->
<!--    1:配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    2:配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
<!--    3:配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.rzpt.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>  

index.jsp:


<h3>测试保存</h3>
<form action="account/save" method="post">
    姓名:<input type="text" name="name"/><br/>
    金额:<input type="text" name="money"/><br/>
    <input type="submit" value="保存">
</form>  

AccountController中:  

@RequestMapping("/save")
public String save(Account account){  

//注意account的自动封装,从jsp来的数据  

    System.out.println("表现层:保存账户信息.....");

    //调用service方法,成功调用整合
    accountService.saveAccount(account);

    return "list";
}  

 

也可以:

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SSM整合 的相关文章

  • mybatis多表操作

    xff08 1 xff09 多表查询 用户和账户 xff0c 要求 xff1a 一个用户可以有多个账户 xff0c 一个账户只能属于一个用户 xff08 多个账户也可以属于同一个用户 xff09 步骤 xff1a 1 建立两张表 xff1a

随机推荐

  • centos .sh文件无法执行

    到sh文件目录下执行 sed i s r sh
  • Maven学习笔记

    xff08 1 xff09 标准目录结构 src main java目录 xff1a 核心代码部分 src main resources xff1a 配置文件部分 src test java xff1a 测试代码部分 src test re
  • JSTL学习笔记

    xff08 1 xff09 概念 xff1a JavaServer Pages Tag Library jsp标准标签库 xff08 2 xff09 作用 xff1a 用于简化和替换jsp页面上的Java代码 xff08 3 xff09 使
  • idea 开启 tomcat 热部署 的 具体流程 和 使用方式

    idea 开启 tomcat 热部署 的 具体流程 和 使用方式 https www cnblogs com c2g5201314 p 12275243 html https blog csdn net qq 41288095 articl
  • java 判断字符串是否为空

    四种判断为空表示方式 xff1a 1 str 61 61 null 2 34 34 equals str 3 str length 61 61 0 4 str isEmpty 1234 代码中的四种不为空的运用 xff1a if str 6
  • springmvc返回值

    xff08 1 xff09 返回字符串 xff08 2 xff09 void xff08 3 xff09 返回ModelAndView 把user对象存储到mv对象中 xff0c 也会把user对象存入到request对象 mv addOb
  • springmvc上传下载

    xff08 1 xff09 form表单的enctype取值是 xff1a multipart form data xff0c method取值是 xff1a post xff0c 提供一个文件选择域 xff08 2 xff09 sprin
  • 数据库多表和范式

    xff08 1 xff09 一对多的关系 xff1a 一个部门可以有多个员工 xff0c 一个员工只能属于一个部门 在多的一方建立外键 xff0c 指向1的一方的主键 xff08 2 xff09 多对多关系 课程 学生 中间表 xff0c
  • springjdbc学习笔记

    xff08 1 xff09 导包 xff08 2 xff09 创建jdbcTemplate xff0c 依赖数据源DataSource 实例化的时候需要传入DataSource jdbcTemplate 61 new JdbcTemplat
  • MySQL多表操作

    xff08 1 xff09 笛卡尔积 xff1a 两个集合的所有组合 xff1a select from 表1 xff0c 表2 xff08 2 xff09 内连接查询 xff1a 隐式内连接 xff1a select from 表1 xf
  • MySQL事务

    xff08 1 xff09 概念 xff1a 一个包含多个步骤业务操作 xff0c 被事务管理 xff0c 这些操作具有统一性 xff08 要么成功 xff0c 要么失败 xff09 操作开启事务 xff08 start transacti
  • 软件产品化

    1 产品化定义 xff1a 软件产品化是指客户无需为软件添加或调整代码和语句即能完成软件的安装配置 应用初始化 系统管理 用户使用的全过程 xff0c 并且软件至少能满足80 以上的用户某一组应用需求 微软Office或杀毒软件就是产品化软
  • MySQL忘记root密码

    1 cmd gt net stop mysql 停止mysql服务 需要管理员运行该cmd 2 使用无验证方式启动mysql服务 xff1a mysqld skip grant tables 3 打开新的cmd窗口 直接输入mysql命令
  • 对象转型

    一 对象转型介绍 对象转型分为两种 xff1a 一种叫向上转型 父类对象的引用或者叫基类对象的引用指向子类对象 xff0c 这就是向上转型 xff0c 另一种叫向下转型 转型的意思是 xff1a 如把float类型转成int类型 xff0c
  • 获取文件的真实(服务器)路径

  • jQuery选择器

    1 基本选择器 标签选择器 xff08 元素选择器 xff09 xff0c 语法 xff1a 34 html标签名 34 id选择器 xff0c 语法 xff1a 34 id的属性值 34 类选择器 xff0c 语法 xff1a 34 cl
  • MySQL8:Unknown initial character set index ‘255‘ received from server. Initial client character 解决方法

    Unknown initial character set index 39 255 39 received from server Initial client character set can be forced via the 39
  • mybatis延迟加载

    1 什么是延迟加载 在使用时候才加载数据 xff0c 不用的时候不加载 2 关联对象是1时 xff0c 采用立即加载 xff1b 关联对象是多是 xff0c 采用延迟加载 3 一对一 xff08 一对多 xff09 延迟加载步骤及配置 xf
  • springmvc拦截器

    一 springmvc拦截器只有springmvc有 xff0c Servlet的拦截器可以适用任何web项目 二 步骤 1 编写拦截器类 xff0c 实现 HandlerInterceptor 接口 xff1b 配置拦截器 2 案例 pu
  • SSM整合

    一 spring整合springmvc mybatis 二 配置文件 43 注解 1 创建相应的类 xff1a dao controller domain service service impl 2 首先配置spring xff0c 使用