Spring+SpringMVC+Mybatis整合案例

本文我们主要介绍使用SSM框架搭建一个简单项目的过程与注意事项。

项目目录

持久层Dao 进行数据库读写操作,属于Mybatis
业务层Service 调用Dao层的函数,对数据库进行操作,以实现业务需求。属于Spring
控制层Controller 前端发送的请求被控制层拦截,控制层调用业务层Service的函数执行业务计算。执行完毕之后结果返回到前端页面。属于SpringMVC
前端 发送请求,服务器执行完请求之后,返回结果到前端。属于SpringMVC
web.xml 配置web项目的基本信息,可配置项目使用的框架。
applicationContext.xml配置Spring框架
springmvc.xml 配置mvc框架
log4j.properties配置日志处理
index.jsp项目运行后的主界面
list.jsp前端控制器处理后的页面
在这里插入图片描述

Web.xml配置

tomcat启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml。web.xml文件是用来初始化配置信息:比如Welcome页面、servlet、servlet-mapping、filter、listener、启动加载级别等。

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--配置Spring的监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--读取spring配置文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>springmvc</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>springmvc</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

**1、javaEE项目启动过程:首先加载Spring上下文环境配置文件,然后加载SpringMVC配置文件。
**
Spring配置加载过程:
tomcat服务器启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,然后会读取它的listener和context-param节点,然后紧接着会创建一个ServletContext(servlet上下文,全局的),这个web项目的所有部分都将共享这个上下文,容器将转换为键值对,并交给servletContext,可以获取当前该web应用对象,即servletContext对象,获取context-param值,进而获取资源,在web应用启动前操作) ,listener中ContextLoaderListener监听器的作用就是启动Web容器时,监听servletContext对象的变化,获取servletContext对象的,来自动装配ApplicationContext的配置信息。这样spring的加载过程就完成了。

SpringMVC配置加载过程:
配置DispatcherServlet,配置这个是拦截所有请求,都交给springmvc转发。

Servlet介绍:
Servlet通常称为服务端小程序,是服务端的程序,用于处理及响应客户的请求。Servlet是一个特殊的Java类,创建Servlet类自动继承HttpServlet。客户端通常只有GET和POST两种请求方式,Servlet为了响应这两种请求,必须重写doGet()和doPost()方法。大部分时候,Servlet对于所有的请求响应都是完全一样的,此时只需要重写service()方法即可响应客户端的所有请求。

filter设置
web.xml中配置了CharacterEncodingFilter,配置这个是拦截所有的资源并设置好编号格式。
encoding设置成utf-8就相当于request.setCharacterEncoding(“UTF-8”);
foreEncoding设置成true就相当于response.setCharacterEncoding(“UTF-8”);

Spring框架配置

applicationContext.xml是web.xml中读取的Spring配置文件,前几行是spring框架的版本信息。
配置注解扫描:Controller层我们不开启注解扫描,他们会被SpringMVC扫描。
整合mabits框架:配置连接池、SqlSessionFactory工厂、AccountDao接口所在包三项后实现整合mybatis。
进行事务管理配置,AOP增强。

<?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" 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/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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--开启spring注解扫描,不扫描controller-->
    <context:component-scan base-package="cn.itcast">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Spring整合MyBatis框架-->
    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://175.24.68.139:3306/ssm?serverTimezone=GMT%2B8"/>
        <property name="user" value="root"/>
        <property name="password" value="52wendyma"/>
    </bean>

    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--配置AccountDao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.itcast.dao"/>
    </bean>


    <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
</beans>

SpringMVC的配置

MVC需要扫描Controller层的注解,需要开启注解扫描,并配置扫描的目录。
配置视图解析器对象。
配置过滤静态资源。因为dispatcherServlet默认会拦截http://localhost:8080下面的所有文件,包括静态资源文件,不配置过滤就无法访问到静态资源。

<?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.itcast">
        <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 location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>

</beans>

项目逻辑结构

前端 index.jsp 发送请求,服务器执行完请求之后,返回结果到前端。属于SpringMVC

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="account/findAll">测试查询</a>
<h3>测试包</h3>

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

</body>
</html>

控制层Controller 前端发送的请求被控制层拦截,控制层调用业务层Service的函数执行业务计算。执行完毕之后结果返回到前端页面。属于SpringMVC
业务层查询出的数据存到线性表list中,再把该线性表作为model的一个属性(Model对象可以封装数据)。
通过返回字符串list,后续可以从前端页面list.jsp获取该属性,并进行相关处理。

注解:使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面;若返回json等内容到页面,则需要加@ResponseBody注解。
@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在控制层方法前面加@ResponseBody注解。但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面。本例中返回jsp页面就不加该注解。

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

    @Autowired
    private AccountService accountService;

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

        // 调用service的方法
       // accountService.findAll();
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "list";
    }

    @RequestMapping("/save")
    public String save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        accountService.saveAccount(account);
        //response.sendRedirect(request.getContextPath()+"/account/findAll");
        return "redirect:/account/findAll";
    }
}

业务层Service 调用Dao层的函数,对数据库进行操作,以实现业务需求。属于Spring

@Service("accountService")
public class AccountServiceImpl implements AccountService{

    @Autowired
    private AccountDao accountDao;

    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户...");
        //return null;
        return accountDao.findAll();
    }

    public void saveAccount(Account account) {
        System.out.println("业务层:保存帐户...");
        accountDao.saveAccount(account);
    }
}

持久层Dao 进行数据库读写操作,属于Mybatis

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

}

处理后的页面
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.id}
        ${account.name}
        ${account.money}
        <\br>
    </c:forEach>


</body>
</html>

账户模型 用来封装前端请求的数据

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;
 }

pom.xml

属于maven项目管理,可管理jar包

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值