当前位置: 首页 > news >正文

【Spring】SSM整合_入门代码实现

1. Maven依赖

在pom.xml中添加SSM框架的依赖

<!-- Spring Core -->  
<dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-context</artifactId>  <version>5.3.x</version>  
</dependency>  
<!-- Spring Web MVC -->  
<dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-webmvc</artifactId>  <version>5.3.x</version>  
</dependency>  
<!-- MyBatis -->  
<dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis</artifactId>  <version>3.5.x</version>  
</dependency>  
<!-- MyBatis Spring Integration -->  
<dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis-spring</artifactId>  <version>2.0.x</version>  
</dependency>  
<!-- Database Driver (e.g., MySQL) -->  
<dependency>  <groupId>mysql</groupId>  <artifactId>mysql-connector-java</artifactId>  <version>8.0.x</version>  
</dependency>  
<!-- Other dependencies... -->

2. Spring配置文件 (applicationContext.xml)

在src/main/resources目录下创建applicationContext.xml文件,并配置数据源、事务管理和MyBatis的SqlSessionFactoryBean。

<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">  <!-- DataSource Configuration -->  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>  <property name="url" value="jdbc:mysql://localhost:3306/your_database"/>  <property name="username" value="your_username"/>  <property name="password" value="your_password"/>  </bean>  <!-- Session Factory Configuration -->  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  <property name="dataSource" ref="dataSource"/>  <property name="mapperLocations" value="classpath:mappers/*.xml"/>  </bean>  <!-- Mapper Scanner Configuration -->  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  <property name="basePackage" value="com.example.yourapp.mapper"/>  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>  </bean>  <!-- Transaction Manager Configuration -->  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  <property name="dataSource" ref="dataSource"/>  </bean>  <!-- Enable Transaction Annotation Support -->  <tx:annotation-driven transaction-manager="transactionManager"/>  <!-- Other bean definitions... -->  
</beans>

3. SpringMVC配置文件 (springmvc-config.xml)

在src/main/resources目录下创建springmvc-config.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: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">  <!-- Enable @Controller support -->  <mvc:annotation-driven/>  <!-- Scan for @Controllers -->  <context:component-scan base-package="com.example.yourapp.controller" />  <!-- Configure View Resolver -->  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  <property name="prefix" value="/WEB-INF/views/" />  <property name="suffix" value=".jsp" />  </bean>  <!-- Other bean definitions for MVC components -->  </beans>

4. 配置web.xml

在src/main/webapp/WEB-INF目录下,配置web.xml以加载Spring和SpringMVC的配置文件,并设置DispatcherServlet。

<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">  <!-- Spring Context Loader Listener -->  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- Spring Context Config Location -->  <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>/WEB-INF/applicationContext.xml</param-value>  </context-param>  <!-- Spring MVC Servlet -->  <servlet>  <servlet-name>dispatcherServlet</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <init-param>  <param-name>contextConfigLocation</param-name>  <param-value>/WEB-INF/springmvc-config.xml</param-value>  </init-param>  <load-on-startup>1</load-on-startup>  </servlet>  <!-- Map all requests to the DispatcherServlet for handling -->  <servlet-mapping>  <servlet-name>dispatcherServlet</servlet-name>  <url-pattern>/</url-pattern>  </servlet-mapping>  <!-- Other configurations... -->  </web-app>

5. 创建Mapper接口和映射文件

在src/main/java/com/example/yourapp/mapper目录下创建Mapper接口,并在src/main/resources/mappers目录下创建相应的XML映射文件。

Mapper接口

在src/main/java/com/example/yourapp/mapper目录下创建UserMapper.java接口:

package com.example.yourapp.mapper;  import com.example.yourapp.model.User;  
import org.apache.ibatis.annotations.Mapper;  
import org.apache.ibatis.annotations.Param;  import java.util.List;  @Mapper  
public interface UserMapper {  User findUserById(@Param("id") Integer id);  List<User> findAllUsers();  int insertUser(User user);  int updateUser(User user);  int deleteUserById(@Param("id") Integer id);  
}

映射文件
在src/main/resources/mappers目录下创建UserMapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
<mapper namespace="com.example.yourapp.mapper.UserMapper">  <select id="findUserById" resultType="com.example.yourapp.model.User">  SELECT * FROM users WHERE id = #{id}  </select>  <select id="findAllUsers" resultType="com.example.yourapp.model.User">  SELECT * FROM users  </select>  <insert id="insertUser" parameterType="com.example.yourapp.model.User">  INSERT INTO users (name, email) VALUES (#{name}, #{email})  </insert>  <update id="updateUser" parameterType="com.example.yourapp.model.User">  UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}  </update>  <delete id="deleteUserById" parameterType="java.lang.Integer">  DELETE FROM users WHERE id = #{id}  </delete>  </mapper>

6. 创建Controller、Service和DAO层

在src/main/java/com/example/yourapp目录下创建Controller、Service和DAO层的相关类和接口。

Model类(可选,但通常在项目中会有)

在src/main/java/com/example/yourapp/model目录下创建User.java:

package com.example.yourapp.model;  public class User {  private Integer id;  private String name;  private String email;  // getters and setters  
}

Service接口和实现

在src/main/java/com/example/yourapp/service目录下创建UserService.java接口和UserServiceImpl.java实现类:

UserService.java:

package com.example.yourapp.service;  import com.example.yourapp.model.User;  import java.util.List;  public interface UserService {  User findUserById(Integer id);  List<User> findAllUsers();  int insertUser(User user);  int updateUser(User user);  int deleteUserById(Integer id);  
}

UserServiceImpl.java:

package com.example.yourapp.service.impl;  import com.example.yourapp.mapper.UserMapper;  
import com.example.yourapp.model.User;  
import com.example.yourapp.service.UserService;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  import java.util.List;  @Service  
public class UserServiceImpl implements UserService {  @Autowired  private UserMapper userMapper;  @Override  public User findUserById(Integer id) {  return userMapper.findUserById(id);  }  // ... 其他方法的实现 ...  
}

Controller类

在src/main/java/com/example/yourapp/controller目录下创建UserController.java:

package com.example.yourapp.controller;  import com.example.yourapp.model.User;  
import com.example.yourapp.service.UserService;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.HttpStatus;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.*;  import java.util.List;  @RestController  
@RequestMapping("/users")  
public class UserController {  @Autowired  private UserService userService;  @GetMapping("/{id}")  public ResponseEntity<User> getUserById(@PathVariable Integer id) {  User user = userService.findUserById(id);  if (user == null) {  return new ResponseEntity<>(HttpStatus.NOT_FOUND);  }  return new ResponseEntity<>(user, HttpStatus.OK);  }  @GetMapping("/")  public ResponseEntity<List<User>> getAllUsers() {  List<User> users = userService.findAllUsers();  return new ResponseEntity<>(users, HttpStatus.OK);  }  @PostMapping("/")  public ResponseEntity<Integer> createUser(@RequestBody User user) {  int result = userService.insertUser(user);  if (result == 1) {  return new ResponseEntity<>(user.getId(), HttpStatus.CREATED);  } else {  return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);  }  }  @PutMapping("/")  public ResponseEntity<Integer> updateUser(@RequestBody User user) {  int result = userService.updateUser(user);  if (result == 1) {  return new ResponseEntity<>(HttpStatus.OK);  } else {  return new ResponseEntity<>(HttpStatus.NOT_FOUND);  }  }  @DeleteMapping("/{id}")  public ResponseEntity<Void> deleteUserById(@PathVariable Integer id) {  int result = userService.deleteUserById(id);  if (result == 1) {  return new ResponseEntity<>(HttpStatus.NO_CONTENT);  } else {  return new ResponseEntity<>(HttpStatus.NOT_FOUND);  }  }  
}

7. 测试和部署

  • 编写测试用例或使用Postman等工具测试API接口。
  • 打包项目为WAR文件,并部署到Tomcat或其他Servlet容器中。

相关文章:

【Spring】SSM整合_入门代码实现

1. Maven依赖 在pom.xml中添加SSM框架的依赖 <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.x</version> </dependency>…...

C++代码错误解决1(函数模板)

1、代码如下 //示例函数模板的使用 #include <iostream> #include <string> using namespace std; template <typename T>//函数模板 T max(T a,T b) {return a>b?a:b; } int main() {int a,b;cout<<"input two integers to a&b:"…...

idea configuration 配置 方便本地启动环境切换

idea 再项目启动的时候避免切换环境导致上线的时候出现环境配置问题 可以再idea 的 configuration 中配置项目的 vm options 虚拟机的内容占用 -Xmx256m -Xms256m -Xmn100m -Xss256k program arguments properties 文件中需要修改的配置参数 active profiles 指定启动的本…...

win10配置wsl的深度学习环境

# 1、一步完成wsl&#xff1a;开启虚拟机、linux子系统、并下载ubuntu # 官方文档: https://learn.microsoft.com/zh-cn/windows/wsl/install wsl --install# 2、打开windows terminal&#xff0c;选ubuntu交互环境 # 第一次需要配置用户名和密码 # 接下来正常使用即可# 3、cud…...

如何处理时间序列的缺失数据

您是否应该删除、插入或估算&#xff1f; 世界上没有完美的数据集。每个数据科学家在数据探索过程中都会有这样的感觉&#xff1a; df.info()看到类似这样的内容&#xff1a; 大多数 ML 模型无法处理 NaN 或空值&#xff0c;因此如果您的特征或目标包含这些值&#xff0c;则在…...

fastapi中实现多个路由请求

大家伙&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂。 前言 最近在写机器人相关的接口&#xff0c;顺手学了学python&#xff0c;发现这是个好东西&#xff0c;写代码效率比java要高很多&#xff0c;比如写个词云呀&#xff0c;写个回调呀&am…...

前端框架选择指南:React vs Vue vs Angular

选择前端框架时&#xff0c;React、Vue 和 Angular 都是流行的选择&#xff0c;各有优缺点。我们可以从各个维度进行比较和选择&#xff1a; React 核心理念&#xff1a; 组件化开发&#xff0c;专注于视图层。学习曲线&#xff1a; 相对平缓&#xff0c;因为重点在于JSX和组…...

猫头虎 解析:为什么AIGC在国内适合做TOB,在国外适合做TOC?

猫头虎 解析&#xff1a;为什么AIGC在国内适合做TOB&#xff0c;在国外适合做TOC&#xff1f; 博主 猫头虎 的技术世界 &#x1f31f; 欢迎来到猫头虎的博客 — 探索技术的无限可能&#xff01; 专栏链接&#xff1a; &#x1f517; 精选专栏&#xff1a; 《面试题大全》 — 面…...

并发编程笔记8--ThreadLocal结构详解

ThreadLocal&#xff0c;即线程变量&#xff0c;是一个以ThreadLocal对象为键&#xff0c;任意对象为值的存储结构。这个结构被附带在线程上&#xff0c;也就是说一个线程可以根据一个ThreadLocal对象查询到绑定在这个线程上的值。可以通过set(T)方法来设置一个值&#xff0c;在…...

强烈推荐 20.7k Star!企业级商城开源项目强烈推荐!基于DDD领域驱动设计模型,助您快速掌握技术奥秘,实现业务快速增长

更多资源请关注纽扣编程微信公众号 1 项目简介 商城是个从零到一的C端商城项目&#xff0c;包含商城核心业务和基础架构两大模块,推出用户、消息、商品、订单、优惠券、支付、网关、购物车等业务模块&#xff0c;通过商城系统中复杂场景&#xff0c;给出对应解决方案。使用 …...

【C++STL详解(四)------vector的模拟实现】

文章目录 vector各函数接口总览vector当中的成员变量介绍默认成员函数构造函数1构造函数2构造函数3拷贝构造函数赋值运算符重载函数析构函数 迭代器相关函数begin和end 容量和大小相关函数size和capacityreserveresizeempty 修改容器内容相关函数push_backpop_backinserterases…...

租赁系统|北京租赁系统|租赁软件开发流程

在数字化时代的浪潮下&#xff0c;小程序成为了各行各业争相探索的新领域。租赁行业亦不例外&#xff0c;租赁小程序的开发不仅提升了用户体验&#xff0c;更为商家带来了更多商业机会。本文将详细解析租赁小程序的开发流程&#xff0c;为有志于进军小程序领域的租赁行业从业者…...

JAVA面试题大全(十四)

1、Kafka 可以脱离 Zookeeper 单独使用吗&#xff1f;为什么&#xff1f; kafka不能脱离zookper单独使用&#xff0c;因为kafka使用zookper管理和协调kafka的节点服务器。 2、Kafka 有几种数据保留的策略&#xff1f; Kafka提供了多种数据保留策略&#xff0c;这些策略用于定…...

Web Accessibility基础:构建无障碍的前端应用

Web Accessibility&#xff08;网络无障碍&#xff09;是确保所有人都能平等访问和使用网站和应用程序的关键。这包括视觉、听觉、运动和认知能力有限的用户。以下是一些构建无障碍前端应用的基础原则和代码示例&#xff1a; 2500G计算机入门到高级架构师开发资料超级大礼包免…...

谈谈你对 SPA 的理解?

1 理解基本概念 SPA&#xff08;single-page application&#xff09;单页应用&#xff0c;默认情况下我们编写 Vue、React 都只有一个html 页面&#xff0c;并且提供一个挂载点&#xff0c;最终打包后会再此页面中引入对应的资源。&#xff08;页面的渲染全部是由 JS 动态进行…...

JAVA给一个JSON数组添加对象

操作Mysql表的json字段&#xff0c;查询json字段的内容&#xff0c;将新增的内容添加到查询的json数组中 String a "[{\"name\": \"张三\", \"age\": 10, \"gender\": \"男\", \"email\": \"123qq.co…...

设计一个完美的用户角色权限表

设计一个完美的用户角色权限表需要考虑系统的安全性、灵活性和可扩展性。以下是一个详细的用户角色权限管理表设计方案&#xff0c;包含多个表结构和字段描述。 目录 1. 用户表&#xff08;Users Table&#xff09;2. 角色表&#xff08;Roles Table&#xff09;3. 权限表&…...

Git 基本使用

目录 Git 安装与设置 在 Windows上安装 Git git 的配置 Git 原理 git 的四个区域 git 工作流程 git 文件的状态 Git 操作 创建仓库 免密登录 基本操作 版本回退 本地仓库整理 分支命令 合并分支 解决冲突 Git 安装与设置 在 Windows上安装 Git 在 Windows上使…...

LabVIEW使用PID 控制器有哪些应用场景?

如何在LabVIEW中创建PID控制器? LabVIEW为各种控制工程任务提供了内置函数和库&#xff0c;包括PID控制器编程。这些功能位于控制设计和仿真调色板中&#xff0c;其中有用于不同类型控制器的子调色板。要在LabVIEW中创建PID控制器&#xff0c;需要将PID函数从PID子调色板拖放…...

UTC与GPS时间转换-[week, sow]

UTC与GPS时间转换-[week, sow] utc2gpsgps2utc测试参考 Ref: Global Positioning System utc2gps matlab源码 function res utc2gps(utc_t, weekStart)%% parameterssec_day 86400;sec_week 604800;leapsec 18; % 默认周一为一周的开始if nargin < 2weekStart d…...

【HTTP三个基础问题】

面试官您好&#xff01;HTTP是超文本传输协议&#xff0c;是互联网上客户端和服务器之间传输超文本数据&#xff08;比如文字、图片、音频、视频等&#xff09;的核心协议&#xff0c;当前互联网应用最广泛的版本是HTTP1.1&#xff0c;它基于经典的C/S模型&#xff0c;也就是客…...

Rapidio门铃消息FIFO溢出机制

关于RapidIO门铃消息FIFO的溢出机制及其与中断抖动的关系&#xff0c;以下是深入解析&#xff1a; 门铃FIFO溢出的本质 在RapidIO系统中&#xff0c;门铃消息FIFO是硬件控制器内部的缓冲区&#xff0c;用于临时存储接收到的门铃消息&#xff08;Doorbell Message&#xff09;。…...

Angular微前端架构:Module Federation + ngx-build-plus (Webpack)

以下是一个完整的 Angular 微前端示例&#xff0c;其中使用的是 Module Federation 和 npx-build-plus 实现了主应用&#xff08;Shell&#xff09;与子应用&#xff08;Remote&#xff09;的集成。 &#x1f6e0;️ 项目结构 angular-mf/ ├── shell-app/ # 主应用&…...

Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信

文章目录 Linux C语言网络编程详细入门教程&#xff1a;如何一步步实现TCP服务端与客户端通信前言一、网络通信基础概念二、服务端与客户端的完整流程图解三、每一步的详细讲解和代码示例1. 创建Socket&#xff08;服务端和客户端都要&#xff09;2. 绑定本地地址和端口&#x…...

论文笔记——相干体技术在裂缝预测中的应用研究

目录 相关地震知识补充地震数据的认识地震几何属性 相干体算法定义基本原理第一代相干体技术&#xff1a;基于互相关的相干体技术&#xff08;Correlation&#xff09;第二代相干体技术&#xff1a;基于相似的相干体技术&#xff08;Semblance&#xff09;基于多道相似的相干体…...

[大语言模型]在个人电脑上部署ollama 并进行管理,最后配置AI程序开发助手.

ollama官网: 下载 https://ollama.com/ 安装 查看可以使用的模型 https://ollama.com/search 例如 https://ollama.com/library/deepseek-r1/tags # deepseek-r1:7bollama pull deepseek-r1:7b改token数量为409622 16384 ollama命令说明 ollama serve #&#xff1a…...

Golang——9、反射和文件操作

反射和文件操作 1、反射1.1、reflect.TypeOf()获取任意值的类型对象1.2、reflect.ValueOf()1.3、结构体反射 2、文件操作2.1、os.Open()打开文件2.2、方式一&#xff1a;使用Read()读取文件2.3、方式二&#xff1a;bufio读取文件2.4、方式三&#xff1a;os.ReadFile读取2.5、写…...

相关类相关的可视化图像总结

目录 一、散点图 二、气泡图 三、相关图 四、热力图 五、二维密度图 六、多模态二维密度图 七、雷达图 八、桑基图 九、总结 一、散点图 特点 通过点的位置展示两个连续变量之间的关系&#xff0c;可直观判断线性相关、非线性相关或无相关关系&#xff0c;点的分布密…...

从零手写Java版本的LSM Tree (一):LSM Tree 概述

&#x1f525; 推荐一个高质量的Java LSM Tree开源项目&#xff01; https://github.com/brianxiadong/java-lsm-tree java-lsm-tree 是一个从零实现的Log-Structured Merge Tree&#xff0c;专为高并发写入场景设计。 核心亮点&#xff1a; ⚡ 极致性能&#xff1a;写入速度超…...

qt+vs Generated File下的moc_和ui_文件丢失导致 error LNK2001

qt 5.9.7 vs2013 qt add-in 2.3.2 起因是添加一个新的控件类&#xff0c;直接把源文件拖进VS的项目里&#xff0c;然后VS卡住十秒&#xff0c;然后编译就报一堆 error LNK2001 一看项目的Generated Files下的moc_和ui_文件丢失了一部分&#xff0c;导致编译的时候找不到了。因…...