SSM專案整合
一.環境準備
-
開發工具:idea2020.1
-
構建工具:maven3.8.4
-
spring框架5.2.18;JDK:1.8;資料庫:MySQL;連接池:德魯伊
二.環境搭建
2.1 基本環境搭建
2.1.1構建model

2.1.3創建基本目錄

2.2 pom檔案依賴包引入
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.2.18.RELEASE</spring.version>
</properties>
?
<dependencies>
<!--測驗依賴-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--日志-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--決議JSON-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!--作用范圍是provided表示,打包的時候不會將jar包打入war包-->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--上傳檔案依賴jar包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--Spring依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring AOP和aspectj框架整合的模塊-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!--事務需要的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--鏈接資料庫要用-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mysql jdbc驅動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!--Druid資料庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!-- mybatis框架包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mybatis和spring整合依賴包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--分頁依賴-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.1</version>
</dependency>
</dependencies>
?
<build>
<!--資源插件,處理src/main/java目錄的xml-->
<resources>
<resource>
<directory>src/main/java</directory> <!--所在的目錄-->
<includes><!--包括properties和xml都會被掃描-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory> <!--所在的目錄-->
<includes><!--包括properties和xml都會被掃描-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
2.3 撰寫組態檔
2.3.1撰寫spring組態檔
-
j將所有的組態檔都放在在src\main\resources目錄下面,方便管理維護;
-
創建spring的xml組態檔applicationContext.xml

-
撰寫applicationContext.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 https://www.springframework.org/schema/tx/spring-tx.xsd"> ? <!--開啟掃描--> <context:component-scan base-package="com.yang"> <!--配置哪些注解不掃描 Controller用springMVC--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--讀取外部組態檔--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--將Druid資料源交給Spring IOC容器來管理--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="username" value="${prop.username}"/> <property name="password" value="${prop.password}"/> <property name="url" value="${prop.url}"/> <property name="driverClassName" value="${prop.driverClassName}"/> <property name="initialSize" value="${prop.initialSize}"/> <property name="maxActive" value="${prop.maxActive}"/> </bean> <!--SqlSessionFactory 會話工廠交給spring容器管理--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 加載資料環境 --> <!-- 系結mybatis組態檔 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 幾乎所有的東西都能在這里面配,完全不需要mybatis的核心配置 根據個人喜好,個人感覺分開一點維護比較容易 --> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.yang.mapper"></property> </bean> <!-- 事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> ? </beans>
2.3.2撰寫jdbc.properties檔案
prop.username=用戶名
prop.password=密碼
prop.url=jdbc:mysql://localhost:3306/資料庫名
#driverClassName
prop.driverClassName=com.mysql.cj.jdbc.Driver
#初始化連接數
prop.initialSize=10
#最小連接數
prop.minIdle=5
#最大連接數
prop.maxActive=20
#最大等待時間
prop.maxWait=5000
2.3.3配置springMVC檔案
<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
?
<!--開啟注解掃描,只掃描Controller注解,直接指定到controller,否則會無法添加事務-->
<context:component-scan base-package="com.yang.controller" />
<!--配置的視圖決議器物件;這里使用jsp;也可以使用其他的視圖決議器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<!--也可以放開下面這一行; 就只能決議jsp了;-->
<!--<property name="suffix" value=".jsp"/>-->
<property name="contentType" >
<value>text/html; charset=UTF-8</value>
</property>
</bean>
<!--MVC注解驅動,如果不加這個驅動所有的都會交給默認的請求去處理了,只能訪問靜態資源,而其他跳 轉功能等無法使用所以default-servlet-handler標簽要和annotation-driven一起使用-->
<mvc:annotation-driven/>
<!--開啟靜態資源掃描,由于設定了DispatcherServlet所以所有的請求都會交給DispatcherServlet去處理,而當它處理不了的時候,就需要交給默認的servlet處理
web階段是由于Tomcat中設定為默認servlet,而mvc中設定為DispatcherServlet,起沖突時,就地原則,就使用DispatcherServlet,所以需要在開啟該標簽,當DispatcherServlet處理不了時,交給默認的去處理,若也處理不了就404了-->
<mvc:default-servlet-handler/>
<!--檔案上傳決議類 id必須是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<!--視圖控制器,當視圖只配置一個跳轉頁面的時候可以用 path路徑,view-name映射路徑-->
<mvc:view-controller path="/in" view-name="index.jsp"/>
<mvc:view-controller path="/" view-name="in.html"/>
</beans>
2.3.4撰寫mybatis組態檔
<?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"/>
</settings>
<!--配置插件,分頁查詢-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"/>
</plugins>
?
</configuration>
2.3.5配置web.xml檔案
<!DOCTYPE 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 Application</display-name>
<!--加載applicationContext檔案-->
<!-- 加載全域初始化引數,讓服務器啟動就加載spring組態檔-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置spring監聽器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--設定字符編碼-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--設定請求編碼utf-8編碼-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!--設定回應編碼為utf-8-->
<init-param>
<param-name>ForceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置HiddenHttpMethodFilter以使用put和delete請求-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置springMVC前段控制器,對瀏覽器請求統一處理-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置springMVC的組態檔的位置和名稱-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMVC.xml</param-value>
</init-param>
<!--將初始化時間提前到服務器啟動時間-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!--/的意思就是接受除了.jsp以外的所有請求;/*表示所有包括.jsp-->
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
到這里基本的框架就搭好了,接下來就是業務代碼的撰寫了
三.業務代碼
3.1撰寫前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你好</h1>
<a href="user/2">查詢</a><br/>
<hr/>
<form action="user" method="post">
用戶名<input type="text" name="username" /><br/>
密碼<input type="text" name="password" /><br/>
<input type="submit" value="添加用戶" /><br/>
</form><hr/>
<form action="user/20" method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="洗掉用戶" /><br/>
</form><hr/>
</body>
</html>
3.2后端代碼
3.2.1基本結構

-
一般要將dao介面和mapper檔案放在同一目錄下才行;但為了方便管理將其放在resource目錄下面
3.2.2 Controller
/**
* (User)表控制層
*
* @author makejava
* @since 2021-12-27 14:38:49
*/
@RestController
@RequestMapping("user")
public class UserController {
/**
* 服務物件
*/
@Resource
private UserService userService;
?
/*
* 分頁查詢
* @return 查詢結果
*/
@GetMapping
public List<User> queryByPage() {
//使用分頁查詢插件,下面的引數分別是頁數和每頁展示數量
PageHelper.startPage(2,2);
return userService.queryByPage();
}
?
/**
* 通過主鍵查詢單條資料
*
* @param id 主鍵
* @return 單條資料
*/
@GetMapping("{id}")
public ResponseEntity<User> queryById(@PathVariable("id") Integer id) {
return ResponseEntity.ok(this.userService.queryById(id));
}
?
/**
* 新增資料
*
* @param user 物體
* @return 新增結果
*/
@PostMapping
public ResponseEntity<User> add(User user) {
return ResponseEntity.ok(this.userService.insert(user));
}
?
/**
* 編輯資料
*
* @param user 物體
* @return 編輯結果
*/
@PutMapping
public ResponseEntity<User> edit(User user) {
return ResponseEntity.ok(this.userService.update(user));
}
?
/**
* 洗掉資料
*
* @param id 主鍵
* @return 洗掉是否成功
*/
@DeleteMapping
public ResponseEntity<Boolean> deleteById(Integer id) {
return ResponseEntity.ok(this.userService.deleteById(id));
}
?
}
?
3.2.3 Service和serviceImpl
/**
* (User)表服務介面
*
* @author makejava
* @since 2021-12-27 14:39:23
*/
public interface UserService {
/**
* 分頁查詢
* @return
*/
List<User> queryByPage();
/**
* 通過ID查詢單條資料
*
* @param id 主鍵
* @return 實體物件
*/
User queryById(Integer id);
/**
* 新增資料
*
* @param user 實體物件
* @return 實體物件
*/
User insert(User user);
/**
* 修改資料
*
* @param user 實體物件
* @return 實體物件
*/
User update(User user);
/**
* 通過主鍵洗掉資料
*
* @param id 主鍵
* @return 是否成功
*/
boolean deleteById(Integer id);
}
serviceImpl
/**
* (User)表服務實作類
*
* @author makejava
* @since 2021-12-27 14:39:24
*/
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public List<User> queryByPage() {
return userDao.queryPage();
}
/**
* 通過ID查詢單條資料
*
* @param id 主鍵
* @return 實體物件
*/
@Override
public User queryById(Integer id) {
return this.userDao.queryById(id);
}
/**
* 新增資料
*
* @param user 實體物件
* @return 實體物件
*/
@Override
@Transactional(rollbackFor=Exception.class)
public User insert(User user) {
userDao.insert(user);
int i = 12/0;
return user;
}
/**
* 修改資料
*
* @param user 實體物件
* @return 實體物件
*/
@Override
public User update(User user) {
this.userDao.update(user);
return this.queryById(user.getId());
}
/**
* 通過主鍵洗掉資料
*
* @param id 主鍵
* @return 是否成功
*/
@Override
public boolean deleteById(Integer id) {
return this.userDao.deleteById(id) > 0;
}
}
3.2.4 dao介面
/**
* (User)表資料庫訪問層
*
* @author makejava
* @since 2021-12-27 14:40:01
*/
public interface UserDao {
/**
* 通過ID查詢單條資料
*
* @param id 主鍵
* @return 實體物件
*/
User queryById(Integer id);
/**
* 查詢指定行資料
*
* @param user 查詢條件
* @param pageable 分頁物件
* @return 物件串列
*/
List<User> queryAllByLimit(User user, @Param("pageable") Pageable pageable);
/**
* 統計總行數
*
* @param user 查詢條件
* @return 總行數
*/
long count(User user);
/**
* 新增資料
*
* @param user 實體物件
* @return 影響行數
*/
int insert(User user);
/**
* 批量新增資料(MyBatis原生foreach方法)
*
* @param entities List<User> 實體物件串列
* @return 影響行數
*/
int insertBatch(@Param("entities") List<User> entities);
/**
* 修改資料
*
* @param user 實體物件
* @return 影響行數
*/
int update(User user);
/**
* 通過主鍵洗掉資料
*
* @param id 主鍵
* @return 影響行數
*/
int deleteById(Integer id);
List<User> queryPage();
}
3.2.5 mapper檔案
<?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.yang.mapper.UserDao">
?
<resultMap type="com.yang.bean.User" id="UserMap">
<result property="id" column="id" jdbcType="INTEGER"/>
<result property="username" column="username" jdbcType="VARCHAR"/>
<result property="password" column="password" jdbcType="VARCHAR"/>
<result property="email" column="email" jdbcType="VARCHAR"/>
</resultMap>
?
<!--分頁查詢 回傳型別還可以是user,mybatis會自動把查到的物件封裝到集合中-->
<select id="queryPage" resultMap="UserMap">
select
id, username, password, email
from user
</select>
<!--查詢單個-->
<select id="queryById" resultMap="UserMap">
select
id, username, password, email
from user
where id = #{id}
</select>
?
<!--查詢指定行資料-->
<select id="queryAllByLimit" resultMap="UserMap">
select
id, username, password, email
from user
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="username != null and username != ''">
and username = #{username}
</if>
<if test="password != null and password != ''">
and password = #{password}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</where>
limit #{pageable.offset}, #{pageable.pageSize}
</select>
?
<!--統計總行數-->
<select id="count" resultType="java.lang.Long">
select count(1)
from user
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="username != null and username != ''">
and username = #{username}
</if>
<if test="password != null and password != ''">
and password = #{password}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</where>
</select>
?
<!--新增所有列-->
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into user(username, password, email)
values (#{username}, #{password}, #{email})
</insert>
?
<insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
insert into user(username, password, email)
values
<foreach collection="entities" item="entity" separator=",">
(#{entity.username}, #{entity.password}, #{entity.email})
</foreach>
</insert>
?
<insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
insert into user(username, password, email)
values
<foreach collection="entities" item="entity" separator=",">
(#{entity.username}, #{entity.password}, #{entity.email})
</foreach>
on duplicate key update
username = values(username),
password = values(password),
email = values(email)
</insert>
?
<!--通過主鍵修改資料-->
<update id="update">
update user
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
</set>
where id = #{id}
</update>
?
<!--通過主鍵洗掉-->
<delete id="deleteById">
delete from user where id = #{id}
</delete>
?
</mapper>
四 測驗
-
新建一個Tomcat服務,將包部署到Tomcat就可以測驗啦
-
頁面不好看自己優化吧
五 一些問題
-
pom檔案中的依賴都要用到,少了會啟動失敗
-
mybatis和spring可以全部整合到一起;但是不方便維護
-
在MVC的掃描中只能掃描controller;否則會導致配置事務不起作用
<!--掃描Controller-->
<context:component-scan base-package="com.yang">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<!--下面這個是防止事務沒起作用,spring.xml的父容器先于Servlet的子容器生效,將Service提前加載了,這里不用再進行加載裝配;或者像上面的配置一樣,直接指定只掃controller-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396175.html
標籤:其他
