• 超详细整合SSM框架--(Spring + Spring MVC + MyBatis)


    超详细整合SSM框架--(Spring + Spring MVC + MyBatis)

    阅读该文章之前首先要清楚Spring框架,SpringMVC框架,Mybatis框架。

    SSM框架,是Spring + Spring MVC + MyBatis的缩写,这个是继SSH之后,目前比较主流的Java EE企业级框架,适用于搭建各种大型的企业级应用系统。



    SpringMVC框架:

    MVC简介

    MVC 全名是 Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写, 是一种用于设计创建 Web 应用程序表现层的模式。


    Model(模型): 通常指的就是我们的数据模型。作用一般情况下用于封装数据。
    View(视图): 通常指的就是我们的 jsp 或者 html。作用一般就是展示数据的。 通常视图是依据模型数据创建的。
    Controller(控制器): 是应用程序中处理用户交互的部分。作用一般就是处理程序逻辑的。


    SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于 Spring FrameWork 的后续产品,已经融合在 Spring Web Flow 里面。Spring 框架提供了构建 Web

    应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用 Spring 进行 WEB 开发时,可以选择使用 Spring 的 Spring MVC 框架或集成其他 MVC 开发框架。

    SpringMVC 已经成为目前最主流的 MVC 框架之一,并且随着 Spring3.0 的发布,已成为最优秀的 MVC 框架。



    image


    SpringMVC中的常用注解

    @GetMapping

    作用:用于建立请求URL和处理请求方法之间的对应关系

    可以出现在类上,请求URL的第一级访问目录
    可以出现在方法上,请求URL的第二级访问目录
    value:用于指定请求的URL。它和path属性的作用是一样的
    method:用于指定请求的方式
    params:用于指定限制请求参数的条件

    """

    @Controller
    //@RequestMapping("SpringMVC/")
    public class HelloController {
    //请求方法为get 请求参数必须有username
    @RequestMapping(value = "/hello",method = RequestMethod.GET,params = {"username"})
    //@RequestMapping("/hello")
    public String sayHello(){
    System.out.println("SpringMVC hello~~~");
    return "success";
    }
    }

    """



    @RequestParam

    作用:把请求中指定名称的参数给控制器中的形参赋值

    value:请求参数的名称
    required:请求参数中必须提供此参数。默认值:true,表示必须提供,如果不提供就报错。

    """

    @RequestMapping("/testRequestParam")
    //RequestParam --更名
    // 属性 value=别名 required=必须含有的参数
    public String testRequestParam(@RequestParam(value = "username") String name){
    System.out.printf(name);
    System.out.println("testRequestParam执行了~~~");
    return "success";
    }

    """



    @RequestBody

    作用:用于获取请求体内容。直接使用得到key=value&key=vaule...结构的数据。get请求方式不适用

    required:是否必须有请求体。当取值为true时,get请求会报错。如果取值为false,get请求得到是null

    """

    @RequestMapping("/testRequestBody")
    //RequestBody 获取请求体中的内容 如:username=benshan&password=98989&money=200
    public String testRequestBody(@RequestBody String body){
    System.out.println("testRequestBody执行了~~~");
    System.out.println(body);
    return "success";
    }

    """



    @PathVariable

    作用:用于绑定URL中的占位符。url中有/delete/{id},{id}就是占位符。

    """

    @RequestMapping("/testPathVariable/{id}")
    //PathVariable使用Restful风格,结构清晰,拓展方便
    public String testPathVariable(@PathVariable(value = "id") String id){
    System.out.println("testPathVariable~~~");
    System.out.println(id);
    return "success";
    }

    """



    @RequestHeader

    作用:用于获取请求消息头

    value 提供消息头名称
    required:是否必须有此消息头

    """

    @RequestMapping("/testRequestHeader")
    //testRequestHeader获取请求头的值
    public String testRequestHeader(@RequestHeader(value = "Accept") String header){
    System.out.println("testRequestHeader~~~");
    System.out.println(header);
    return "success";
    }

    """



    @CookieValue

    作用:用于把指定cookie名称的值传入控制器方法参数

    value:指定cookie的名称
    required:是否必须有此cookie

    """

    @RequestMapping("/testCookieValue")
    //testRequestHeader获取请求头的值
    public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookie){
    System.out.println("testCookieValue~~~");
    System.out.println(cookie);
    return "success";
    }

    """


    @ModelAttribute

    作用:可以修饰方法和参数。出现在方法上,表示当前方法会在控制器的方法执行之前执行,先执行。出现在参数上,获取指定的数据给参数赋值

    value 用于获取数据的key

    """

    @RequestMapping("/testModelAttribute")
    public String testModelAttribute(){
    System.out.println("testModelAttribute~~~");
    return "success";
    }
    @ModelAttribute
    //在控制器执行之前 执行
    public void showUser(){
    System.out.println("showUser执行了~~~");
    }

    """


    @SessionAttributes

    作用:用于多次执行控制器方法间的参数共享

    value 用于指定存入的属性名称

    type:用于指定存入的数据类型


    新注解

    @RequestMapping 和 @GetMapping @PostMapping 区别

    @GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

    @PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。



    Spring框架

    Spring是什么?

    Spring是一个轻量级Java开发框架,最早有Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题。它是一个分层的JavaSE/JavaEE full-stack(一站式)轻量级开源框架,为开发Java应用程序提供全面的基础架构支持。Spring负责基础架构,因此Java开发者可以专注于应用程序的开发。


    体系结构

    image



    核心容器(Core Container):Spring的核心容器是其他模块建立的基础,有Spring-core、Spring-beans、Spring-context、Spring-context-support和Spring-expression(String表达式语言)等模块组成

    数据访问/集成(Data Access)层:数据访问/集成层由JDBC、ORM、OXM、JMS和事务模块组成。

    Web层:Web层由Spring-web、Spring-webmvc、Spring-websocket和Portlet模块组成。

    AOP(Aspect Oriented Programming)模块:提供了一个符合AOP要求的面向切面的编程实现,允许定义方法拦截器和切入点,将代码按照功能进行分离,以便干净地解耦。

    植入(Instrumentation)模块:提供了类植入(Instrumentation)支持和类加载器的实现,可以在特定的应用服务器中使用。

    消息传输(Messaging):Spring4.0以后新增了消息(Spring-messaging)模块,该模块提供了对消息传递体系结构和协议的支持。

    测试(Test)模块:Spring-test模块支持使用JUnit或TestNG对Spring组件进行单元测试和集成测试。



    引入jar包

    """

    <dependencies>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.0.11.RELEASEversion>
    dependency>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.0.11.RELEASEversion>
    dependency>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-txartifactId>
    <version>5.0.11.RELEASEversion>
    dependency>
    dependencies>

    """


    导入约束

    """

    <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:component-scan base-package="com.dynamic2">context:component-scan>
    beans>

    """


    常见注解


    用于创建对象

    @Component:把资源让spring来管理。相当于xml中配置一个bean。value:指定bean的id,如果不指定value属性,默认bean的id是当前类的类名。首字母小写

    @Controller:与@Component功能一样,一般用在表现层,便于分层

    @Service:与@Component功能一样,一般用在业务层,便于分层

    @Repository:与@Component功能一样,一般用于持久层,便于分层



    """

    /**
    * @Author: Promsing
    * @Date: @Date: 2023/7/17 - 11:34
    * @Description: 用于创建对象
    * @version: 1.0
    * XML配置
    */
    @Repository("accountDao ")
    public class AccountDaoImpl implements IAccountDao {
    ......
    }
    @Service("accountService")
    public class AccountServiceImpl implements IAccountService {
    ......
    }
    @Component("accountServiceImpl")
    @Scope("prototype")//多例
    public class AccountServiceImpl2 implements IAccountService {
    ......
    }

    """



    用于注入数据

    @Autowired:自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他bean类型。当有多个类型匹配时。使用要注入的对象变量名称作为bean的id,在spring容器中查找,找到了注入成功,找不到就报错。

    @Qualifier:在自动按照类型注入的基础上,再按照Bean的id注入。它在给字段注入时不能单独使用,必须和@Autowire一起使用;但是给方法参数注入时,可以单独使用。value属性是指定Bean的id

    @Resource:直接按照Bean的id注入。它也只能注入其他Bean类型。name属性是指定Bean的id

    @Value:注入基本数据类型和String类型数据

    """

    /**
    * @Author: Promsing
    * @Date: @Date: 2023/7/17 - 11:34
    * @Description: 用于创建对象
    * @version: 1.0
    * XML配置
    */
    @Component("accountServiceImpl")
    @Scope("prototype")//多例
    public class AccountServiceImpl implements IAccountService {
    //注入成员变量
    /* @Autowired 自动按照类型注入--寻找类型
    @Qualifier("accountDao2")*/ //寻找id
    //以上两个注解相加的作用等于这个
    @Resource(name = "accountDao2")
    private IAccountDao accountDao2;
    @Override
    public void saveAccount() {
    accountDao2.saveAccount();
    //System.out.println("service中的saveAccount执行了~~");
    }
    }

    """



    用于改变作用范围

    @Scope:指定Bean的作用范围。value属性指定范围的值--singleton单例,prototype多例,request作用与web应用的请求范围,session作用与web应用的会话范围,global-session作用与集群环境中会话范围


    """

    @Component("accountServiceImpl")
    @Scope("prototype")//多例
    public class AccountServiceImpl implements IAccountService {
    ......
    }

    """



    和生命周期相关(了解)

    @PostConstruct:用于指定初始化方法

    @PreDestroy:用于指定销毁方法


    Spring5

    @Configuration:用于指定当前类是一个spring配置类,当有容器时会从该类上加载注解。获取容器是使用AnnotationApplicationContext(有@Configuration注解的类.class)

    @ComponentScan:用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件找那个的

    @Bean:该注解只用用在方法上,表明使用此方法创建一个对象,并且放入spring容器中

    @Import:用于导入其他配置类,解耦合


    """

    /**
    * @Author: Promsing
    * @Date: @Date: 2023/7/17 - 0:36
    * @Description: Spring配置类
    * @version: 1.0
    */
    @Configuration//指定当前类是一个配置类
    @ComponentScan("com.dynamic_transaction_anno")//用于指定spring在初始化容器时需要扫描的包
    @Import({JdbcConfig.class,TransactionConfig.class})//导入其他配置类
    @EnableTransactionManagement//开启spring注解事务的支持
    public class SpringConfig {
    @Bean("jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource ds){
    return new JdbcTemplate(ds);
    }
    @Bean("dataSource")
    public DataSource createDataSource(){
    DriverManagerDataSource dr=new DriverManagerDataSource();
    dr.setDriverClassName("com.mysql.jdbc.Driver");//com.mysql.jdbc.Driver
    dr.setUrl("jdbc:mysql//localhost:330b/eesy");
    dr.setUsername("root");
    dr.setPassword("root");
    return dr;
    }
    }

    """


    Spring整合Junit

    @RunWith:替代原有的运行器

    @ContextConfiguration:指定配置文件的位置


    """

    @RunWith(SpringJUnit4ClassRunner.class)//替代原有运行器
    @ContextConfiguration(classes=SpringConfiguration.class)//指定配置类
    public class AccountServiceTest {
    @Test
    public void testFindAll(){
    //执行测试方法
    }
    }

    """


    从IOC容器中获取对象

    """

    /**
    * @Author: Promsing
    * @Date:@Date: 2023/7/17 - 11:22
    * @Description: 单元测试
    * @version: 1.0
    */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=SpringConfiguration.class)
    public class AccountServiceTest {
    @Resource(name = "accountServiceImpl")
    private IAccountService accountService;
    @Test
    //从容器中获取对象
    public void test(){
    //一、获取容器
    //使用配置文件加载
    ApplicationContext ac=new ClassPathXmlApplicationContext("bean3_1.xml");
    //使用配置类加载
    /// ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
    //二、获取对象
    accountService=(IAccountService)ac.getBean("accountServiceImpl",IAccountService.class);
    //三、执行方法
    List allAccounts = accountService.findAllAccount();
    for (Account allAccount : allAccounts) {
    System.out.println(allAccount);
    }
    }
    }

    """



    Mybatis框架

    MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。


    image


    Mybatis简介

    官网链接:https://mybatis.org/mybatis-3/zh/index.html。
    更加详细的信息可以去官网查看。


    MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

    要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。

    如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:


    """

    <dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>x.x.xversion>
    dependency>

    """


    配置步骤

    1.引入Mybatis的jar包

    2.编写实体类与DAO接口

    3.添加主配置文件(配置mysql环境,事务类型,数据源,连接数据库的基本信息,映射文件的位置)

    4.添加DAO接口的映射文件(需要指明DAO接口的位置,为每个方法做一个映射)注:所在路径在Resource文件夹下,目录路径需要DAO的层次结构一样

    5.使用mybatis框架


    使用步骤(所有的xml配置已配置完毕)

    1.读取配置文件,可使用mybatis封装的Resources类。

    2.创建SQLSessionFactory工厂

    3.使用工厂生产SQLsession对象

    4.使用SQLSession创建DAO接口的代理对象

    5.使用代理对象执行方法

    6.提交事务,释放资源


    基础数据

    实体类
    """

    public class User implements Serializable {
    /**
    * Java实体类为什么要实现Serializable接口
    * 1.用于序列化与反序列化--一个类只有实现了Serializable接口,它的对象才能被序列化。
    * 2.Serializable接口就是Java提供用来进行高效率的异地共享实例对象的机制,实现这个接口即可。
    */
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    public String getUsername() {
    return username;
    }
    public void setUsername(String username) {
    this.username = username;
    }
    public Date getBirthday() {
    return birthday;
    }
    public void setBirthday(Date birthday) {
    this.birthday = birthday;
    }
    public String getSex() {
    return sex;
    }
    public void setSex(String sex) {
    this.sex = sex;
    }
    public String getAddress() {
    return address;
    }
    public void setAddress(String address) {
    this.address = address;
    }
    @Override
    public String toString() {
    return "User{" +
    "id=" + id +
    ", username='" + username + '\'' +
    ", birthday=" + birthday +
    ", sex='" + sex + '\'' +
    ", address='" + address + '\'' +
    '}';
    }

    """


    DAO层的接口

    """

    public interface IUserDao {
    /**
    * 查询所有
    * @return 所有的User信息
    */
    //@Select("select * from User")
    List findAll();
    /**
    * 保存操作
    * @param user
    */
    //@Insert("insert into User(username,address,sex,birthday)values()")
    void saveUser(User user);
    /**
    * 更改操作
    */
    void updateUser(User user);
    /**
    * 删除操作
    * @param i
    */
    void deleteUser(Integer i);
    /**
    * 根据id查询单个用户
    * @param id
    * @return
    */
    User findById(Integer id);
    /**
    * 根据名称模糊查询
    * @param name
    * @return
    */
    List findByName(String name);
    /**
    * 查询总用户数
    * @return
    */
    int findTotal();
    }

    """


    主配置文件

    """

    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://localhost:3306/eesy"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    dataSource>
    environment>
    environments>
    <mappers>
    <mapper resource="com/dynamic_basics/dao/IUserDao.xml">mapper>
    mappers>
    configuration>

    """


    子配置文件

    """

    mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.dynamic_basics.dao.IUserDao">
    <resultMap id="userMap" type="com.dynamic_basics.domain.User">
    <id property="userId" column="id">id>
    <result property="userName" column="username">result>
    <result property="userAddress" column="address">result>
    <result property="userSex" column="sex">result>
    <result property="userBirthday" column="birthday">result>
    resultMap>
    <select id="findAl l" resultType="com.dynamic_basics.domain.User" resultMap="userMap">
    select * from user
    select>
    <insert id="saveUser" parameterType="com.dynamic_basics.domain.User">
    insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    insert>
    <insert id="updateUser" parameterType="com.dynamic_basics.domain.User">
    update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    insert>
    <delete id="deleteUser" parameterType="int">
    delete from User where id=#{id}
    delete>
    <select id="findById" parameterType="int" resultType="com.dynamic_basics.domain.User">
    select * from user where id=#{id}
    select>
    <select id="findByName" resultType="com.dynamic_basics.domain.User" parameterType="String">
    select * from user where username like #{name}
    select>
    <select id="findTotal" resultType="int">
    SELECT COUNT(id) FROM `user`;
    select>
    mapper>

    """


    测试类

    """

    /**
    * @Author: Promsing
    * @Date: @Date: 2023/7/17 - 8:58
    * @Description: 描述 形容
    * @version: 1.0
    */
    public class MyBatisTest {
    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;
    @Before
    public void init()throws Exception{
    //1.读取配置文件 Resources是myBatis封装的类
    in= Resources.getResourceAsStream("SqlMapConfig.xml");
    //2.创建SQLSessionFactory工厂
    // SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
    SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
    SqlSessionFactory factory=builder.build(in);
    //3.使用工厂生产SQLSession对象
    sqlSession = factory.openSession();
    //4.使用SQLSession创建DAO接口的代理对象
    userDao = sqlSession.getMapper(IUserDao.class);
    }
    @After
    public void destory()throws Exception{
    //6.释放资源
    //提交事务
    sqlSession.commit();
    sqlSession.close();
    in.close();
    }
    //入门案例
    /**
    * 查询操作
    */
    @Test
    public void selectUser(){
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    List all = userDao.findAll();
    for (User user : all) {
    System.out.println(user);
    }
    //释放资源-使用注解After
    }
    /**
    * 测试保存
    */
    @Test
    public void testSave() {
    User user=new User();
    user.setUsername("mybatis");
    user.setAddress("北京市延庆区");
    user.setSex("女");
    user.setBirthday(new Date());
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    userDao.saveUser(user);
    //释放资源-使用注解After
    }
    /**
    * 测试修改
    */
    @Test
    public void testUpdate() {
    User user=new User();
    user.setId(50);
    user.setUsername("mybatis_plus");
    user.setAddress("北京市安次");
    user.setSex("男");
    user.setBirthday(new Date());
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    userDao.updateUser(user);
    //释放资源-使用注解After
    }
    /**
    * 测试删除
    */
    @Test
    public void testDelete() {
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    userDao.deleteUser(50);
    //释放资源-使用注解After
    }
    /**
    * 查询单个人员信息
    */
    @Test
    public void testFindById() {
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    User user=userDao.findById(49);
    System.out.println(user);
    //释放资源-使用注解After
    }
    /**
    * 模糊查询
    */
    @Test
    public void testFindByName() {
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    List users=userDao.findByName("%王%");
    users.forEach(i-> System.out.println(i));
    //释放资源-使用注解After
    }
    /**
    * 测试查询总记录条数
    */
    @Test
    public void testFindTotal() {
    //初始化资源-使用注解Before
    //5.使用代理对象执行方法
    int total=userDao.findTotal();
    System.out.println(total);
    //释放资源-使用注解After
    }
    }

    """


    总结

    Mybatis其实使用的方法很简单,需要多记住一些配置,当配置做好了,使用的时候很简单。Mybatis框架将JDBC中复杂的注册驱动、获取连接,使用不同的服务类---
    (DriverManager,Connection,Statement,ResultSet)都封装了。其实框架的学习就是了解框架、熟悉配置,使用框架的阶段。


    配置顶层结构:


    image


    常用标签设置


    image


    具体配置的详解请去mybatis官网



    整合思路

    1.先搭建整合的环境

    2.把Spring的配置搭建完成

    3.再使用Spring整合SpringMVC框架

    4.最后使用Spring整合Mybatis框架


    设计数据库

    """

    CREATE DATABASE ssm;
    USE ssm;
    CREATE TABLE account ( id INT PRIMARY KEY auto_increment, NAME VARCHAR ( 20 ), money DOUBLE );

    """


    搭建环境,选择maven工程,选择骨架webapp


    image


    导入依赖

    """

    <name>SSM Maven Webappname>
    <url>http://www.example.comurl>
    <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
    <spring.version>5.0.2.RELEASEspring.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>1.2.12log4j.version>
    <mysql.version>5.1.6mysql.version>
    <mybatis.version>3.4.5mybatis.version>
    properties>
    <dependencies>
    <dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.11version>
    <scope>testscope>
    dependency>
    <dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.6.8version>
    dependency>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aopartifactId>
    <version>5.0.2.RELEASEversion>
    dependency>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.0.2.RELEASEversion>
    dependency>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webartifactId>
    <version>5.0.2.RELEASEversion>
    dependency>
    <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>5.0.2.RELEASEversion>
    dependency> <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.0.2.RELEASEversion>
    dependency> <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-txartifactId>
    <version>5.0.2.RELEASEversion>
    dependency> <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.0.2.RELEASEversion>
    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.0version>
    dependency>
    <dependency>
    <groupId>c3p0groupId>
    <artifactId>c3p0artifactId>
    <version>0.9.1.2version>
    <type>jartype>
    <scope>compilescope>
    dependency>
    dependencies>

    """


    创建目录结构,创建domain,controller,service,dao

    web依赖于service,service依赖于dao,dao依赖于domain

    image


    domain

    """

    package com.dynamic.domain;
    import java.io.Serializable;
    /**
    * @Author: Promsing
    * @Date: 2023/7/17 - 17:44
    * @Description: 实体类-Account
    * @version: 1.0
    */
    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 +
    '}';
    }
    }

    """


    Controller层

    """

    package com.dynamic.controller;
    /**
    * @Author: Promsing
    * @Date: 2023/7/17 - 17:50
    * @Description: Web层账户
    * @version: 1.0
    */
    @Controller
    @RequestMapping("/account")
    public class AccountController {
    @Autowired
    private AccountService service;
    //需要加 /
    @GetMapping("/findAll")
    public String findAll(Model model){
    System.out.println("表现层查询所有信息!");
    //调用Service方法
    List all = service.findAll();
    for (Account account : all) {
    System.out.println(account);
    }
    model.addAttribute("all",all);
    return "success";
    }
    @PostMapping("/save")
    public String save(Account account){
    service.saveAccount(account);
    return "success";
    }
    }

    """


    service层

    """

    public interface AccountService {
    /**
    * 查询所有
    * @return
    */
    public List findAll();
    /**
    * 保存账户信息
    * @param account
    */
    public void saveAccount(Account account);
    }
    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao dao;
    @Override
    public List findAll() {
    System.out.println("业务层:查询所有信息!");
    return dao.findAll();
    }
    @Override
    public void saveAccount(Account account) {
    System.out.println("业务层:保存账户。。。");
    dao.saveAccount(account);
    }
    }

    """


    dao层

    """

    /**
    * @Author: Promsing
    * @Date: 2023/7/17 - 17:46
    * @Description: DAO层 使用注解
    * @version: 1.0
    */
    @Repository
    public interface AccountDao {
    /**
    * 查询所有
    * @return
    */
    @Select("select * from account")
    public List findAll();
    /**
    * 保存账户信息
    * @param account
    */
    @Insert("insert into account (name,money) values(#{name},#{money})")
    public void saveAccount(Account account);
    }

    """


    index页面

    """

    <%--
    Created by IntelliJ IDEA.
    User: Administrator
    Date: 2023/7/17
    Time: 19:00
    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>
    head>
    <body>
    <a href="account/findAll">测试查询a>
    <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>

    """


    Success页面

    """

    <%--
    Created by IntelliJ IDEA.
    User: Administrator
    Date: 2023/7/17
    Time: 19:10
    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>
    head>
    <body>
    <h1>成功页面h1>
    ${all}
    <br/>
    <c:forEach items="${all}" var="account">
    ${account.name}
    ${account.money}
    c:forEach>
    body>
    html>

    """


    编写Spring框架

    applicationContext文件

    """

    <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.dynamic">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    beans>

    """


    Spring整合SpringMVC框架

    编写SpringMVC框架

    web.xml

    """

    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 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.dynamic">
    <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>
    <property name="suffix" value=".jsp">property>
    bean>
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:annotation-driven>mvc:annotation-driven>
    beans>

    """


    整合SpringMVC框架

    在Controller中能够成功调用service对象中的方法


    image

    image


    在web.xml中配置ContextLoaderListener监听器。加载applicationContext.xml文件

    在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器。(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)

    """

    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 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>

    """


    Spring整合Mybatis框架

    编写Mybatis框架

    在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件(AccountDAO接口的方法上添加注解,编写Sql语句)

    """

    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"/>
    <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="root"/>
    dataSource>
    environment>
    environments>
    <mappers>
    <package name="com.dynamic.dao"/>
    mappers>
    configuration>

    """


    整合Mybatis框架

    把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中,同时配置Spring的声明式事务管理

    """

    <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.dynamic">
    <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="root"/>
    bean>
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource">property>
    bean>
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.dynamic.dao">property>
    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*" read-only="true">tx:method>
    <tx:method name="*" isolation="DEFAULT">tx:method>
    tx:attributes>
    tx:advice>
    <aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.dynamic.service..ServiceImpl.*(..))"/>
    aop:config>
    beans>

    """



  • 相关阅读:
    Ts内置类型---下
    部门新来了个腾讯拿30k跳槽出来的,让我见识到了跳槽天花板
    创新创业理论研究与实践杂志社创新创业理论研究与实践编辑部2022年第18期目录
    ⽬标⾏动及稠密环境未知情况下,⽆⼈机跟踪的系统解决⽅案
    CentosLinux 7 字符安装教程
    如何做好分布式任务调度——Scheduler 的一些探索
    网络工程师的爬虫技术之路:跨界电商与游戏领域的探索
    java计算机毕业设计积分权益商城源码+mysql数据库+系统+lw文档+部署
    22、短信登录(隐藏用户的敏感信息)
    KMP模式匹配算法
  • 原文地址:https://www.cnblogs.com/xw-01/p/17558383.html