第一次入手ssm框架,想把这些框架整合需要的步骤全部记录下来,既是为了以后回顾,也是为了重新巩固一遍知识,虽然还不是很懂各种各样的配置,但是还是要去慢慢理解,因而此举很有必要,下面我们进入ssm框架的整合吧。
表现层(springMVC):Controller层(Handler层) 负责具体的业务模块流程的控制
Controller层通过要调用Service层的接口来控制业务流程,控制的 配置也在Spring配置文件里面。
业务层(Spring):Service层 Service层:负责业务模块的逻辑应用设计。 首先设计其接口,然后再实现他的实现类。 通过对Spring配置文件中配置其实现的关联,完成此步工作,我们 就可以通过调用Service的接口来进行业务处理。 最后通过调用DAO层已定义的接口,去实现Service具体的 实现类。
持久层(Mybatis):Dao层(Mapper层) Dao层:负责与数据库进行交互设计,用来处理数据的持久化工作。 DAO层的设计首先是设计DAO的接口, 然后在Spring的配置文件中定义此接口的实现类,就可在其他模块中 调用此接口来进行数据业务的处理,而不用关心接口的具体实现类是 哪个类,这里用到的就是反射机制, DAO层的数据源配置,以及有 关数据库连接的参数都在Spring的配置文件中进行配置。
视图层:View层 负责前台jsp页面的展示。 此层需要与Controller层结合起来开发。
各层次之间的联系 本来Controller层与View层是可以放在.jsp文件里一起开发的,但是为了降低代码的复杂度,提高其可维护性,将其分为了这两层,这也体现了MVC框架的特性,即结构清晰,耦合度低。 Service层是建立在DAO层之上的,建立了DAO层后才可以建立Service层,而Service层又是在Controller层之下的,因而Service层应该既调用DAO层的接口,又要提供接口给Controller层的类来进行调用,它刚好处于一个中间层的位置。每个模型都有一个Service接口,每个接口分别封装各自的业务处理方法。
db.properties
jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/sqlfiftypractice?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 jdbc.username=root jdbc.password=123456log4j.properties
log4j.rootLogger = INFO , stdout log4j.logger.mypackage=DEBUG 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{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %m%nweb.xml配置文件
<?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"> <!--DispatcherServlet--> <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:application-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--encodingFilter--> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Session过期时间--> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>spring-dao.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" 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"> <context:annotation-config/> <!--1.配置数据库相关参数 --> <context:property-placeholder location="classpath:db.properties"/> <!--2.数据库连接池--> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--配置连接池属性--> <property name="driverClass" value="${jdbc.driverClass}"/> <!-- 基本属性 url、user、password --> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> </bean> <!--约定大于配置--> <!--3.配置SqlSessionFactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--往下才是mybatis和spring真正整合的配置--> <!--注入数据库连接池--> <property name="dataSource" ref="dataSource"/> <!--配置mybatis全局配置文件:mybatisConfig.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--扫描entity包,使用别名,多个用;隔开--> <property name="typeAliasesPackage" value="com.lhh.pojo"/> <!--扫描sql配置文件:mapper需要的xml文件--> <!--<property name="mapperLocations" value="classpath:config/mybatis/*Mapper.xml"/>--> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!-- 4:配置扫描Dao接口包,动态实现DAO接口,注入到spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入SqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描的Dao接口--> <property name="basePackage" value="com.lhh.dao"/> </bean> </beans>spring-service.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--扫描service包下所有使用注解的类型--> <context:component-scan base-package="com.lhh.service"/> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入数据库连接池--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置基于注解的声明式事务默认使用注解来管理事务行为--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>spring-mvc.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: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"> <!--配置spring mvc--> <!--1,开启springmvc注解模式 a.自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter b.默认提供一系列的功能:数据绑定,数字和日期的format@NumberFormat,@DateTimeFormat c:xml,json的默认读写支持--> <mvc:annotation-driven/> <!--2.静态资源默认servlet配置--> <!-- 1).加入对静态资源处理:js,gif,png 2).允许使用 "/" 做整体映射 --> <mvc:default-servlet-handler/> <!--3:配置JSP 显示ViewResolver--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4:扫描web相关的bean--> <context:component-scan base-package="com.lhh.controller"/> </beans>mybatis-config.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> <!--<settings> <!–<setting name="logImpl" value="STDOUT_LOGGING"/>–> <!–<setting name="logImpl" value="LOG4J"/>–> </settings>--> <typeAliases> <!--给全限定类名起一个别名,在映射文件中使用这个别名,节省了开发的时间--> <typeAlias type="com.lhh.pojo.Account" alias="account"></typeAlias> </typeAliases> <mappers> <!--在同一个包下,并且名称相同可以使用.--> <mapper class="com.lhh.dao.AccountMapper"></mapper> </mappers> </configuration>spring核心配置文件:application-context.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="spring-dao.xml"></import> <import resource="spring-service.xml"></import> <import resource="spring-mvc.xml"></import> </beans>有一个lombok插件,可以自动生成set,get,以及构造方法,但是不建议使用。
package com.lhh.pojo; public class Account { private int id; private String username; private int money; public Account(int id, String username, int money) { this.id = id; this.username = username; this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", username='" + username + '\'' + ", money=" + money + '}'; } public Account() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }service接口的实现类:
package com.lhh.service.impl; import com.lhh.dao.AccountMapper; import com.lhh.pojo.Account; import com.lhh.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { /*注入dao*/ @Autowired private AccountMapper accountMapper; public int addAccount(Account account) { return accountMapper.addAccount(account); } public int deleteAccount(int id) { return accountMapper.deleteAccount(id); } public int updateAccoount(Account account) { return accountMapper.updateAccoount(account); } public List<Account> queryAccount() { return accountMapper.queryAccount(); } public Account queryAccountById(int id) { return accountMapper.queryAccountById(id); } public List<Account> queryAccountByName(String name) { return accountMapper.queryAccountByName(name); } }index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE HTML> <html> <head> <title>首页</title> <style type="text/css"> a { text-decoration: none; color: black; font-size: 18px; } h3 { width: 180px; height: 38px; margin: 100px auto; text-align: center; line-height: 38px; background: deepskyblue; border-radius: 4px; } </style> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <h3> <a href="${pageContext.request.contextPath}/account/queryAllAccount">点击进入列表页</a> </h3> </body> </html>addAccount.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>新增书籍</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> <small>新增用户</small> </h1> </div> </div> </div> <form action="${pageContext.request.contextPath}/account/addAccount" method="post"> 用户名称:<input type="text" name="username"><br><br><br> 用户金额:<input type="text" name="money"><br><br><br> <input type="submit" value="添加"> </form> </div>allAccount.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>书籍列表</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> <small>书籍列表 —— 显示所有书籍</small> </h1> </div> </div> </div> <div class="row"> <div class="col-md-4 column"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/account/toAddAccount">新增</a> <a class="btn btn-primary" href="${pageContext.request.contextPath}/account/showAllAccount">显示所有</a> </div> <div class="col-md-8 column"> <form action="${pageContext.request.contextPath}/account/search" class="form-inline" method="post"> <span style="color: red;width: 30px">${error}</span> <input type="text" name="name" class="form-control"> <input type="submit" value="搜索" style="border-radius: 5px;background-color: lightblue;" class="btn btn-primary"> </form> </div> </div> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-hover table-striped"> <thead> <tr> <th>账户姓名</th> <th>账户金额</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach var="account" items="${requestScope.get('list')}"> <tr> <td>${account.getUsername()}</td> <td>${account.getMoney()}</td> <td> <a href="${pageContext.request.contextPath}/account/toUpdateAccount?id=${account.getId()}">更改</a> | <a href="${pageContext.request.contextPath}/account/del/${account.getId()}">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> <h1>${msg}</h1> </div>updateAccount.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改信息</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> <small>修改账户信息</small> </h1> </div> </div> </div> <form action="${pageContext.request.contextPath}/account/updateAccount" method="post"> <input type="hidden" name="id" value="${account.getId()}"/> 用户名称:<input type="text" name="username" value="${account.getUsername()}"/> 用户金额:<input type="text" name="money" value="${account.getMoney()}"/> <input type="submit" value="提交"/> </form> </div>项目整体结构图: