【SpringMVC学习】SSM整合

news2024/9/24 21:24:29

文章目录

  • 配置准备
    • 1. 新建工程项目
    • 2. 引入配置文件+配置config
  • 功能模块开发
    • 数据库与POJO配置
    • Dao和Service和Controller的配置
    • 测试接口功能

配置准备

1. 新建工程项目

使用webapp模版生成maven项目
配置相关文件功能
在这里插入图片描述

2. 引入配置文件+配置config

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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.0</modelVersion>

  <groupId>com.itheima</groupId>
  <artifactId>springmvc_08_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.16</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


新建相关文件

在这里插入图片描述
主要配置文件SpringConfig

@Configuration //说明是配置文件
@ComponentScan({"com.itheima.service", "com.itheima.service"}) // 配置导入bean
@PropertySource("jdbc.properties") // 引入jdbc的配置文件
@Import({JdbcConfig.class, MyBatisConfig.class}) // 引入jdbc和mybatis的config
public class SpringConfig {
}

数据库配置文件JdbcConfig

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

数据库配置信息jdbc.properties
这里的配置需要useSSL=false才能连接成功,原因见

【已解决】com.mysql.jdbc.exceptions.jdbc4.CommunicationsExcepti:Communications link failure ----mysql连接报错
关于数据库连接中useSSL是否为true 或者 false的选择

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

配置MyBatisConfig

public class MyBatisConfig {
    @Bean
    // spring容器中根据类型自动装配dataSource
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.itheima.domain");
        return factoryBean;
    }

    @Bean
    // 映射扫描
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}

再次新建两个文件
在这里插入图片描述

配置ServletConfig

package com.itheima.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
//        return new Class[0];
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
//        return new Class[0];
        return new Class[]{SpringMVCConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
//        return new String[0];
        return new String[]{"/"};
    }
}

配置SpringMVCConfig

package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMVCConfig {
}

功能模块开发

Java中的POJO是什么?
DAO层和Service层的究极理解–这波我在大气层

数据库与POJO配置

新建表格,构建表结构
在这里插入图片描述
在这里插入图片描述
根据表结构实现POJO
在这里插入图片描述

package com.itheima.domain;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

Dao和Service和Controller的配置

先新建对应的类
在这里插入图片描述

使用Mybatis自动代理写Dao的接口和实现

package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserDao {
    // 写入每个方法对应的sql语句
    // 这里的username是表中属性 ✅是这个?还是POJO中字段名?
    //    @Insert("insert into tb_user values(null,#{username},#{password},#{gender},#{addr}}}))")
    @Insert("insert into tb_user (username,password,gender,addr) values(#{username},#{password},#{gender},#{addr})")
    public void save(User user) ;

    @Update("update tb_user set username=#{username}, password=#{password}, gender=#{gender}, addr=#{addr} where id = #{id}}")
    public void update(User user);

    @Delete("delete from tb_user where id = #{id}")
    public void delete(Integer id);

    @Select("select * from tb_user where id = #{id}")
    public User getById(Integer id);

    @Select("select * from tb_user")
    public List<User> getAll();



}

实现Service的接口
Service本质就是调用Dao的执行方法,这是分离的思想


package com.itheima.service;

import com.itheima.domain.User;

import java.util.List;

public interface UserService {
    // 使用boolean表示是否成功

    /**
     * 正规开发使用文档注释
     * @param user
     * @return
     */
    public boolean save(User user) ;

    /**
     * 修改
     * @param user
     * @return
     */
    public boolean update(User user);


    /**
     * 按id删除
     * @param id
     * @return
     */
    public boolean delete(Integer id);

    /**
     * 按id查询
     * @param id
     * @return
     */
    public User getById(Integer id);

    public List<User> getAll();
}

实现Controller

package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class UserController {
    @Autowired
    private UserService userService;

    // 提供所有方法
    @PostMapping
    public boolean save(@RequestBody User user) {
        // user数据由json数据中来
        return userService.save(user);
    }

    @PutMapping
    public boolean update(@RequestBody User user) {
        return userService.update(user);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return userService.delete(id);
    }

    @GetMapping("/{id}")
    public User getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @GetMapping
    public List<User> getAll() {
        return userService.getAll();
    }

}

测试接口功能

实际开发中需要测试的环节

  1. 业务层接口开发完,Junit做测试
  2. 表现层接口开发完,Postman做测试

Junit业务层测试
新建测试类
在这里插入图片描述

package com.itheima.service;

import com.itheima.config.SpringConfig;
import com.itheima.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

// 使用spring整合测试
@RunWith(SpringJUnit4ClassRunner.class)
// 业务层的这些bean都定义在spring的config中
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testByID(){
        System.out.println(userService.getById(1));
    }

    @Test
    public void testGetAll(){
        List<User> all = userService.getAll();
        System.out.println(all);

    }

}

接口测试

maven接口启动tomcat,如果遇到问题,可以参考

记一个很坑的问题:Context initialization failed
解决 No qualifying bean of type 问题
Tomcat启动报错: Context initialization failed
【bug排查】启动tomcat服务器报错Context initialization failed
maven启动tomcat插件神坑, Failed to start component StandardEngineTomcat.StandardHostlocalhost.Standar
Maven项目启动报错:Failed to start component StandardEngineTomcat.StandardHostlocalhost.StandardContex
Unable to locate Spring NamespaceHandler for XML schema产生的原因及解决方法
scope为provided【讲的是maven的继承关系等等,感觉挺好的】

如何使用idea配置tomcat并启动,可以参考我之前的笔记【黑马笔记】IDEA配置Tomcat

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/610969.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

word文件加密怎么操作?1分钟就可以轻松实现!

案例&#xff1a;我经常使用word文章整理一些资料&#xff0c;有些资料比较重要&#xff0c;我不希望别人可以随意打开它。听说可以对word文档进行加密&#xff0c;具体应该怎么操作&#xff1f; 随着数字化时代的到来&#xff0c;电子文档在我们的日常生活和工作中扮演着越来…

chatgpt赋能python:Python噪音数据处理:一个有效的解决方案

Python噪音数据处理&#xff1a;一个有效的解决方案 Python作为一种强大的编程语言&#xff0c;在数据处理领域有着广泛的应用。可以用Python来处理许多不同类型的数据&#xff0c;其中包括噪音数据。噪音数据通常被定义为意外的或不需要的信号&#xff0c;这些信号可能会影响…

创业第一步:如何写好商业计划书

即使你的项目不需要融资&#xff0c;你也把标准商业计划书作为一个工具模板来应用&#xff0c;帮助更全面的盘点你要做的事情。 撰写一份性感的商业计划书如同造房子&#xff1a;第一步是科学设计&#xff0c;打好结构&#xff08;有清晰的撰写逻辑&#xff09;&#xff1b;第…

std::remove cannot convert ‘std::vector<std::__cxx11::basic_string<char> >:: 报错

最近遇到一个非常奇怪C++的问题: vector<string> tmp;tmp.erase(std::remove(tmp.begin(), tmp.end(), Routers[i].name_), tmp.end());在Windows下的VS中编译没有任何问题。 但是在Linux 下的 g++下面报错: 解决方法,包含头文件: #include <algorithm&g…

真无线蓝牙耳机推荐,八款口碑最好的真无线蓝牙耳机排行榜

真无线&#xff08;TWS&#xff09;耳机是近年来最流行的耳机品类&#xff0c;与传统有线或蓝牙耳机相比&#xff0c;它们具有更好的自由度和移动性。而除了常规的柄状和豆状形态的产品&#xff0c;现在市面上出现了越来越多拥有特殊形态的TWS耳机&#xff0c;它们在设计上更加…

执行dotnet ef database update EF同步数据表时报错 Duplicate column name ‘xxx‘

1、问题背景描述&#xff1a; 我为abpnext项目加了一个新表的业务代码。 然后执行了 dotnet ef database update 结果返回错误提示 Duplicate column name ExtraProp&#xff0c;翻译过来就是字段重复。如下图所示 然后我打开新增加的init代码初始化文件&#xff0c;发现他居…

设计模式之不一样的责任链模式

责任链模式&#xff08;Chain of Responsibility Pattern&#xff09;是一种行为型设计模式&#xff0c;它通过将请求的发送者和接收者解耦&#xff0c;使多个对象都有机会处理请求。在这个模式中&#xff0c;请求沿着一个处理链依次传递&#xff0c;直到有一个对象能够处理它为…

如何将坐标数据(.xls)转换为矢量范围(.shp)

在工作中&#xff0c;我们经常会遇到要将坐标数据&#xff08;.xls&#xff09;转换为矢量范围&#xff08;.shp&#xff09;的情况&#xff0c;那该如何使用ArcMap完成这项工作呢 / 『思路&#xff1a;使用ArcMap将Excel数据以 XY 数据的方式导入&#xff0c;导出点要素&#…

知行之桥EDI系统QA|第一期

随着使用知行之桥EDI系统的用户群体日益壮大&#xff0c;在使用过程中&#xff0c;用户可能对软件系统的工作原理、功能模块和实施过程有一些疑问。近期整理了有关知行之桥EDI系统的四个常见问题&#xff1a; 1.如何延长知行之桥EDI系统的登录在线时间&#xff1f; 2.一台Wind…

Flask中debug的用法详解

Flask默认是没有开启debug模式的&#xff0c;使用app.run()运行程序后&#xff0c;控制台输出* Debug mode: off。 在具体使用Flask时&#xff0c;可以根据应用场景选择是否使用debug。 开发模式&#xff1a;在程序员自己写代码的时候&#xff0c;开启debug模式&#xff0c;即…

vue3-实战-04-管理后台表单校验-layout-菜单组件封装

目录 1-自定义校验规则 2-layout组件静态页面搭建 3-logo组件封装 4-左侧菜单静态组件搭建 4.1-动态获取菜单数据 4.2-封装菜单动态展示组件 4.3-配置菜单名称-隐藏-图标属性 4.4-菜单刷新定位当前菜单 5-内容展示区组件封装 1-自定义校验规则 上一篇我们在登录表单进…

Vue.js 中的动态组件是什么?如何使用动态组件?

Vue.js 中的动态组件是什么&#xff1f;如何使用动态组件&#xff1f; Vue.js是一种流行的前端框架&#xff0c;它提供了一种称为“动态组件”的技术&#xff0c;使得我们可以动态地切换组件的内容和结构。在本文中&#xff0c;我们将深入探讨Vue.js中的动态组件&#xff0c;包…

我踩过的那些坑,浅谈一下如何更优雅地使用 Linux

前言 相信很多尝鲜过桌面 Linux 系统的朋友&#xff0c;对它一个很深刻的印象就是稳定性差&#xff1a;不知道怎么就把系统搞崩了&#xff0c;又找不到问题的具体原因和解决方法&#xff0c;只能尝试重装&#xff0c;直到心力交瘁地回到了 Windows 或 macOS。但另一方面&#…

实例明确的和模型自适应监督的半监督语义分割

文章目录 Instance-specific and Model-adaptive Supervision for Semi-supervised Semantic Segmentation摘要本文方法Quantitative hardness analysisModel-adaptive supervisionIntensity-based augmentationsCutMix-based augmentationsModel-adaptive unsupervised loss 实…

第四章 Electron|Node 使用SQLite3数据库

一、SQLite是什么 &#x1f447; &#x1f447; &#x1f447; SQLite是一种嵌入式关系型数据库管理系统&#xff0c;是一个零配置、无服务器的、自给自足的、事务性的SQL数据库引擎。SQLite是一个轻量级的数据库&#xff0c;可以在各种操作系统上使用&#xff0c;并且支持SQL…

网络名词术语解析 | 路由、交换机、集线器、半/全双工、DNS、LAN、WAN、端口、MTU

欢迎关注博主 Mindtechnist 或加入【Linux C/C/Python社区】一起学习和分享Linux、C、C、Python、Matlab&#xff0c;机器人运动控制、多机器人协作&#xff0c;智能优化算法&#xff0c;滤波估计、多传感器信息融合&#xff0c;机器学习&#xff0c;人工智能等相关领域的知识和…

Python 数据可视化

Python 数据可视化 Python提供了多个用于数据可视化的工具和库。其中最常用的包括&#xff1a; 1. Matplotlib&#xff1a;Matplotlib 是一个用于绘制二维图形的 Python 库。它提供了广泛的绘图选项&#xff0c;可以帮助您创建线图、散点图、柱状图、饼图、等高线图、3D 图形…

linuxOPS基础_linux网络配置

ifconfig查看网络信息 命令&#xff1a;ifconfig 作用&#xff1a;获取网卡的相关信息 语法&#xff1a;# ifconfig 示例1 查看网络信息 案例1使用ifconfig查看linux网络配置 ifconfig注意&#xff0c;我们发现当前ens33看不到IP地址信息&#xff0c;那是因为网卡默认不启…

如何为您的企业培养社交媒体粉丝(16种方式)

增加社交媒体关注度似乎很困难&#xff0c;但这对各种规模的企业来说都是一项重要任务。通过正确的方法&#xff0c;可以吸引忠实的追随者并在社交媒体上建立强大的影响力。在本文中&#xff0c;我们将探讨 16 种有效的方法来增加您的社交媒体粉丝并与您的受众互动。 目录 为…

Java实现LL1语法分析器【编译原理】

java通过预测分析法实现语法分析程序【编译原理】 前言推荐实验要求需知LL1工作原理 Java实现LL1语法分析器0实验步骤LL1.javaGrammar.javaLeftRecursion.javaFirstAndFollow.javaAnalyzeTable.javaLL1Stack.java实验结果 Java实现LL1语法分析器1Grammar.javaProduction.javaFi…