【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容器中。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/15710.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/15710.shtml
英文地址,請注明出處:http://en.pswp.cn/web/15710.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

軟件杯 題目: 基于深度學習的疲勞駕駛檢測 深度學習

文章目錄 0 前言1 課題背景2 實現目標3 當前市面上疲勞駕駛檢測的方法4 相關數據集5 基于頭部姿態的駕駛疲勞檢測5.1 如何確定疲勞狀態5.2 算法步驟5.3 打瞌睡判斷 6 基于CNN與SVM的疲勞檢測方法6.1 網絡結構6.2 疲勞圖像分類訓練6.3 訓練結果 7 最后 0 前言 &#x1f525; 優…

為什么單片機不能直接驅動繼電器和電磁閥

文章是瑞生網轉載&#xff0c;PDF格式文章下載&#xff1a; 為什么單片機不能直接驅動繼電器和電磁閥.pdf: https://url83.ctfile.com/f/45573183-1247189072-10b6d1?p7526 (訪問密碼: 7526)

java-數組內存分配

在 Java 中&#xff0c;數組是一種基本數據結構&#xff0c;用于存儲一系列相同類型的數據。在內存中&#xff0c;數組分配是一塊連續的內存空間&#xff0c;用于存儲數組中的所有元素。本篇文章將詳細解釋 Java 中數組的內存分配&#xff0c;包括數組的聲明、創建、內存模型以…

memcpy的使?和模擬實現

目錄 一&#xff1a;memcpy的使? memcpy的使?的代碼 二&#xff1a;memcpy函數的模擬實現: memcpy和strcpy的區別 用途&#xff1a; 安全性&#xff1a; 數據類型&#xff1a; 性能&#xff1a; 在字符串中的用法示例&#xff1a; memcpy: strcpy 一&#xff1a;…

Ajax面試題精選及參考答案(3萬字長文)

目錄 什么是Ajax,它的核心原理是什么? Ajax應用程序的優勢有哪些? Ajax最大的特點是什么?

Science 基于尖峰時序編碼的模擬神經觸覺系統,可實現動態對象分類

快速處理和有效利用手與物體交互過程中產生的動態觸覺信號&#xff08;例如觸摸和抓握&#xff09;對于觸覺探索和靈巧的物體操作至關重要。將電子皮膚&#xff08;e-skins&#xff09;推進到模仿自然觸覺的水平&#xff0c;是恢復截肢者和癱瘓患者喪失的功能的可行解決方案&am…

實現地圖上展示坐標時,不要全部展示、只展示幾個距離相對較大marker點位,隨著地圖放大再全部展示出來。

比例尺級別地面分辨率 &#xff08;米/像素&#xff09;比例尺0156543.031&#xff1a;591658700.82178271.5151&#xff1a;295829350.4239135.75751&#xff1a;147914675.2319567.878751&#xff1a;73957337.649783.9393751&#xff1a;36978668.854891.9696881&#xff1a…

電機控制系列模塊解析(22)—— 零矢量剎車

一、零矢量剎車 基本概念 逆變器通常采用三相橋式結構&#xff0c;包含六個功率開關元件&#xff08;如IGBT或MOSFET&#xff09;&#xff0c;分為上橋臂和下橋臂。每個橋臂由兩個反并聯的開關元件組成&#xff0c;上橋臂和下橋臂對應于電機三相繞組的正負端。正常工作時&…

mongodb在游戲開發領域的優勢

1、分布式id 游戲服務器里的大部分數據都是要求全局唯一的&#xff0c;例如玩家id&#xff0c;道具id。之所以有這種要求&#xff0c;是因為運營業務上需要進行合服操作&#xff0c;保證不同服的數據在進行合服之后&#xff0c;也能保證id不沖突。如果采用關系型數據庫&#x…

【C++題解】1699 - 輸出是2的倍數,但非3的倍數的數

問題&#xff1a;1699 - 輸出是2的倍數&#xff0c;但非3的倍數的數 類型&#xff1a;循環 題目描述&#xff1a; 請從鍵盤讀入一個整數 n&#xff0c;輸出 1~n 中所有是 2 的倍數&#xff0c;但非 3 的倍數的數&#xff0c;每行 1個。 比如&#xff0c;讀入一個整數10 &…

Spring AI實戰之二:Chat API基礎知識大串講(重要)

歡迎訪問我的GitHub 這里分類和匯總了欣宸的全部原創(含配套源碼)&#xff1a;https://github.com/zq2599/blog_demos Spring AI實戰全系列鏈接 Spring AI實戰之一&#xff1a;快速體驗(OpenAI)Spring AI實戰之二&#xff1a;Chat API基礎知識大串講(重要)SpringAIOllama三部曲…

Linux:進程地址空間、進程控制(一.進程創建、進程終止、進程等待)

上次介紹了環境變量&#xff1a;Linux&#xff1a;進程概念&#xff08;四.main函數的參數、環境變量及其相關操作&#xff09; 文章目錄 1.程序地址空間知識點總結上述空間排布結構是在內存嗎&#xff1f;&#xff08;進程地址空間引入&#xff09; 2.進程地址空間明確幾個點進…

NDIS小端口驅動開發(三)

微型端口驅動程序處理來自過度驅動程序的發送請求&#xff0c;并發出接收指示。 在單個函數調用中&#xff0c;NDIS 微型端口驅動程序可以指示具有多個接收 NET_BUFFER_LIST 結構的鏈接列表。 微型端口驅動程序可以處理對每個NET_BUFFER_LIST結構上具有多個 NET_BUFFER 結構的多…

JAVA -- > 初識JAVA

初始JAVA 第一個JAVA程序詳解 public class Main {public static void main(String[] args) {System.out.println("Hello world");} }1.public class Main: 類型,作為被public修飾的類,必須與文件名一致 2.public static 是JAVA中main函數準寫法,記住該格式即可 …

python皮卡丘動畫代碼

在Python中&#xff0c;我們可以使用多種方法來創建皮卡丘的動畫&#xff0c;例如使用matplotlib庫。 解決方案1&#xff1a;使用matplotlib庫 以下是一個使用matplotlib庫創建皮卡丘動畫的例子&#xff1a; import matplotlib.pyplot as plt import matplotlib.animation …

Slash后臺管理系統代碼閱讀筆記 如何實現環形統計圖表卡片?

目前&#xff0c;工作臺界面的上半部分已經基本梳理完畢了。 接下來&#xff0c;我們看看這個環形圖卡片是怎么實現的&#xff1f; 具體代碼如下&#xff1a; {/*圖表卡片*/} <Row gutter{[16, 16]} className"mt-4" justify"center">{/*環形圖表…

U盤引導盤制作Rufus v4.5.2180

軟件介紹 Rufus小巧實用開源免費的U盤系統啟動盤制作工具和格式化U盤的小工具&#xff0c;它可以快速將ISO鏡像文件制作成可引導的USB啟動安裝盤&#xff0c;支持Windows或Linux啟動&#xff0c;堪稱寫入鏡像速度最快的U盤系統制作工具。 軟件截圖 更新日志 github.com/pbat…

嵌入式全棧開發學習筆記---C語言筆試復習大全24

目錄 內存管理 內存分配 堆和棧的區別&#xff1f;&#xff08;面試重點&#xff09; 申請內存的函數 malloc realloc free gcc工具鏈 編譯的過程&#xff08;面試重點&#xff09; 第一步&#xff0c;預處理&#xff1a; 第二步&#xff0c;編譯&#xff1a; 第三…

【Spring Boot】使用 Redis + Cafeine 實現二級緩存

使用 Redis Caffeine 實現二級緩存可以有效提升應用的性能和緩存的命中率。Caffeine 是一個高效的 Java 本地緩存庫&#xff0c;而 Redis 是一個分布式緩存解決方案。通過將兩者結合&#xff0c;Caffeine 作為一級緩存用于快速訪問常用數據&#xff0c;Redis 作為二級緩存用于…

解決LabVIEW通過OPC Server讀取PLC地址時的錯誤180121602

在使用LabVIEW通過OPC Server讀取PLC地址時&#xff0c;若遇到錯誤代碼180121602&#xff0c;建議檢查網絡連接、OPC Server和PLC配置、用戶權限及LabVIEW設置。確保網絡暢通&#xff0c;正確配置OPC變量&#xff0c;取消緩沖設置以實時讀取數據&#xff0c;并使用診斷工具驗證…