日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot入门(项目)

發(fā)布時(shí)間:2023/12/20 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot入门(项目) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

springboot 第一天

  • 第一步—— 創(chuàng)建springboot項(xiàng)目。
  • **用戶-創(chuàng)建數(shù)據(jù)表**
  • **創(chuàng)建實(shí)體類**:
  • 配置application.properties
  • 單元測(cè)試
    • 附:
    • pom.xml
  • 設(shè)計(jì)接口與抽象方法
      • UserMapper
      • StoreApplication
      • UserMapper.xml
      • application.properties
      • UserMapperTests測(cè)試類
      • 規(guī)劃并創(chuàng)建異常類
        • ServiceException
        • UsernameDuplicateException
        • InsertException
      • UserServiceImpl
      • 單元測(cè)試
      • 附:
      • 接口與抽象方法
    • 附碼:

初次學(xué)習(xí)springboot所以第一步配置環(huán)境。因?yàn)椴涣?xí)慣用Idea,個(gè)人比較依賴eclipse。
最近eclipse無法配置springboot環(huán)境(可能個(gè)人問題或網(wǎng)絡(luò)問題。我本人在新疆)
用的軟件是【Spring Tool Suite 4】。界面跟eclipse一樣,相當(dāng)于spring的eclipse版本。
個(gè)人是自學(xué)的,最近的到了一個(gè)達(dá)內(nèi)學(xué)員的springboot學(xué)習(xí)日記和源碼。所以根據(jù)那個(gè)開始做了自己的測(cè)試項(xiàng)目。登錄注冊(cè)頁面是根據(jù)嗶哩嗶哩教程視頻自己創(chuàng)建的。源碼: 登錄注冊(cè)頁面-下載
資源:( springboot筆記含源碼…)

配置以下環(huán)境:

  • jdk環(huán)境搭配
  • Spring Tool Suite 4(eclipse)
  • MySQL

eclipse 配置:(版本可以個(gè)人習(xí)慣自己選)

  • Tomcat8.5
  • maven 3.5.3
  • MySQL 8.0.19

第一步—— 創(chuàng)建springboot項(xiàng)目。


我沒有選war。因?yàn)槲艺J(rèn)為jar比較好(但選war或jar)都可以的沒有太大關(guān)系

這依賴關(guān)系我也不太懂,所以模糊添加幾個(gè)重要因素

創(chuàng)建好了項(xiàng)目,第二部創(chuàng)建數(shù)據(jù)庫

用戶-創(chuàng)建數(shù)據(jù)表

創(chuàng)建數(shù)據(jù)庫:

CREATE DATABASE store;

使用該數(shù)據(jù)庫:

USE store;

再創(chuàng)建用戶數(shù)據(jù)表:

CREATE TABLE t_user (uid INT AUTO_INCREMENT COMMENT '用戶id',username VARCHAR(20) NOT NULL UNIQUE COMMENT '用戶名',password CHAR(32) NOT NULL COMMENT '密碼',salt CHAR(36) COMMENT '鹽值',gender INT COMMENT '性別:0-女,1-男',phone VARCHAR(20) COMMENT '電話號(hào)碼',email VARCHAR(30) COMMENT '電子郵箱',avatar VARCHAR(100) COMMENT '頭像',is_delete INT COMMENT '是否刪除:0-未刪除,1-已刪除',created_user VARCHAR(20) COMMENT '日志-創(chuàng)建人',created_time DATETIME COMMENT '日志-創(chuàng)建時(shí)間',modified_user VARCHAR(20) COMMENT '日志-最后修改執(zhí)行人',modified_time DATETIME COMMENT '日志-最后修改時(shí)間',PRIMARY KEY (uid)) DEFAULT CHARSET=utf8mb4;

創(chuàng)建實(shí)體類

在cn.cyjt.shoot.entity里創(chuàng)建兩個(gè)實(shí)體類

- BaseEntity 有日志相關(guān)的4個(gè)屬性,所以,在創(chuàng)建實(shí)體類之前,應(yīng)該先創(chuàng)建這些實(shí)體類的基類,將4個(gè)日志屬性聲明在基類中:- User entity.User用戶數(shù)據(jù)的實(shí)體類 /**實(shí)體類的基類BaseEntity */public class BaseEntity implements Serializable {private static final long serialVersionUID = 6613396591482385844L;private String createdUser;//創(chuàng)建改人private Date createdTime;//創(chuàng)建時(shí)間private String modifiedUser;//修改人private Date modifiedTime;//修改時(shí)間//get,set,string方法 public class User extends BaseEntity{/*** 用戶數(shù)據(jù)的實(shí)體類*/private static final long serialVersionUID = 3414303419311561404L;private Integer uid;private String username;private String password;private String salt;private Integer gender;private String phone;private String email;private String avatar;private Integer isDelete;//get,set,string方法

配置application.properties

首先,需要在application.properties中配置連接數(shù)據(jù)庫的相關(guān)信息:

spring.datasource.url=jdbc:mysql://localhost:3306/shoot?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaispring.datasource.username=rootspring.datasource.password=rootmybatis.mapper-locations=classpath:mappers/*.xml#解決返回亂碼問題#spring.http.encoding.charset=UTF-8#spring.http.encoding.force=true#spring.http.encoding.enabled=trueserver.servlet.encoding.charset=UTF-8server.servlet.encoding.force=trueserver.servlet.encoding.enabled=true

單元測(cè)試

配置完成后,應(yīng)該在src/test/java下的cn.cyjt.shoot.StoreApplicationTests類中編寫并執(zhí)行“獲取數(shù)據(jù)庫連接”的單元測(cè)試:

@Autowiredpublic DataSource dataSource;@Testpublic void getConnection() throws SQLException {Connection conn = dataSource.getConnection();System.err.println("dataSource.getConnection() conn:::"+conn);}

第一步,springboot連接數(shù)據(jù)庫測(cè)試完成了

附:

pom.xml

我的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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.4.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><groupId>cn.cyjt</groupId><artifactId>shoot</artifactId><version>0.0.1-SNAPSHOT</version><name>shoot</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- 數(shù)據(jù)庫連接池jar包坐標(biāo) --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

設(shè)計(jì)接口與抽象方法

UserMapper

創(chuàng)建cn.cyjt.shoot.mapper.UserMapper接口,并在接口中添加抽象方法:

/*** 處理用戶數(shù)據(jù)的持久層接口*/public interface UserMapper {/*** 插入用戶數(shù)據(jù)* @param user 用戶數(shù)據(jù)* @return 受影響的行數(shù)*/Integer insert(User user);/*** 根據(jù)用戶名查詢用戶數(shù)據(jù)* @param username 用戶名* @return 匹配的用戶數(shù)據(jù),如果沒有匹配的數(shù)據(jù),則返回null*/User findByUsername(String username);}

StoreApplication

由于這是第1次創(chuàng)建接口,還應(yīng)該配置接口的位置,所以,需要在啟動(dòng)類(StoreApplication)的聲明之前添加配置

@SpringBootApplication @MapperScan("cn.cyjt.shoot.mapper")//由于這是第1次創(chuàng)建接口,還應(yīng)該配置接口的位置,所以,需要在啟動(dòng)類(StoreApplication)的聲明之前添加配置 public class ShootApplication {public static void main(String[] args) {SpringApplication.run(ShootApplication.class, args);}}

UserMapper.xml

在src/main/resources下創(chuàng)建mappers文件夾,在該文件夾下粘貼得到UserMapper.xml文件,并進(jìn)行配置:

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"><mapper namespace="cn.cyjt.shoot.mapper.UserMapper"><resultMap id="UserEntityMap"type="cn.cyjt.shoot.entity.User"><id column="uid" property="uid" /><result column="is_delete" property="isDelete" /><result column="created_user" property="createdUser" /><result column="created_time" property="createdTime" /><result column="modified_user" property="modifiedUser" /><result column="modified_time" property="modifiedTime" /></resultMap><!-- 插入用戶數(shù)據(jù) --><!-- Integer insert(User user) --><insert id="insert" useGeneratedKeys="true" keyProperty="uid">INSERTINTO t_user (username, password,salt, gender,phone, email,avatar, is_delete,created_user, created_time,modified_user, modified_time) VALUES (#{username}, #{password},#{salt}, #{gender},#{phone}, #{email},#{avatar}, #{isDelete},#{createdUser}, #{createdTime},#{modifiedUser}, #{modifiedTime})</insert><!-- 根據(jù)用戶id更新用戶密碼 --><!-- Integer updatePasswordByUid( @Param("uid") Integer uid, @Param("password") String password, @Param("modifiedUser") String modifiedUser, @Param("modifiedTime") Date modifiedTime) --><update id="updatePasswordByUid">UPDATEt_userSETpassword=#{password},modified_user=#{modifiedUser},modified_time=#{modifiedTime}WHEREuid=#{uid}</update><!-- 根據(jù)用戶id查詢用戶數(shù)據(jù) --><!-- User findByUid(Integer uid) --><select id="findByUid" resultMap="UserEntityMap">SELECT*FROMt_userWHEREuid=#{uid}</select><!-- 根據(jù)用戶名查詢用戶數(shù)據(jù) --><!-- User findByUsername(String username) --><select id="findByUsername" resultMap="UserEntityMap">SELECT*FROMt_userWHEREusername=#{username}</select></mapper>

application.properties

由于是第1次使用,所以,需要在application.properties中配置XML文件的位置:

mybatis.mapper-locations=classpath:mappers/*.xml

UserMapperTests測(cè)試類

最后,在src/test/java下,創(chuàng)建cn.cyjt.shoot.mapper.UserMapperTests測(cè)試類,在測(cè)試類的聲明之前添加@RunWith(SpringRunner.class)和@SpringBootTest注解,并在測(cè)試類中聲明持久層對(duì)象,通過自動(dòng)裝配來注入值:

@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTests {@AutowiredUserMapper userMapper;}

然后,編寫2個(gè)測(cè)試方法,對(duì)以上完成的2個(gè)功能進(jìn)行測(cè)試

@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTests {@Autowiredprivate UserMapper mapper;@Testpublic void insert() {User user = new User();user.setUsername("root");user.setPassword("1234");Integer rows = mapper.insert(user);System.err.println("rows=" + rows);}@Testpublic void findByUsername() {String username = "root";User user = mapper.findByUsername(username);System.err.println(user);}}

規(guī)劃并創(chuàng)建異常類

ServiceException

凡操作失敗都應(yīng)該拋出某種異常,為了便于管理自定義的異常,應(yīng)該先創(chuàng)建這些異常的基類cn.cyjt.shoot.service.ex.ServiceException,繼承自RuntimeException。

package cn.cyjt.shoot.service.ex;public class ServiceException extends RuntimeException {private static final long serialVersionUID = -2879099986352308425L;public ServiceException() {super();}public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}public ServiceException(String message, Throwable cause) {super(message, cause);}public ServiceException(String message) {super(message);}public ServiceException(Throwable cause) {super(cause);} }

UsernameDuplicateException

本次“注冊(cè)”之前,需要先檢查用戶名是否已經(jīng)被占用,如果已經(jīng)被占用,則需要拋出“用戶名被占用”的異常,則需要?jiǎng)?chuàng)建cn.cyjt.shoot.service.ex.UsernameDuplicateException異常類,繼承自ServiceException;

public class UsernameDuplicateException extends ServiceException {private static final long serialVersionUID = 3164055183124220212L;public UsernameDuplicateException() {super();}public UsernameDuplicateException(String message, Throwable cause, boolean enableSuppression,boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}public UsernameDuplicateException(String message, Throwable cause) {super(message, cause);}public UsernameDuplicateException(String message) {super(message);}public UsernameDuplicateException(Throwable cause) {super(cause);} }

InsertException

在執(zhí)行“注冊(cè)”時(shí),需要向數(shù)據(jù)表中插入數(shù)據(jù),則可能失敗,則需要?jiǎng)?chuàng)建cn.cyjt.shoot.service.ex.InsertException異常類,繼承自ServiceException。

public class InsertException extends ServiceException{/*** */private static final long serialVersionUID = 878421569126542322L;public InsertException() {super();}public InsertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}public InsertException(String message, Throwable cause) {super(message, cause);}public InsertException(String message) {super(message);}public InsertException(Throwable cause) {super(cause);} }

UserServiceImpl

創(chuàng)建cn.cyjt.shoot.service.impl.UserServiceImpl業(yè)務(wù)層實(shí)現(xiàn)類,實(shí)現(xiàn)以上IUserService接口,在類的聲明之前添加@Service注解,并重寫接口中的抽象方法:

@Servicepublic abstract class UserServiceImpl implements IUserService{@Autowiredprivate UserMapper userMapper;@Overridepublic void reg(User user) {// 從參數(shù)user中獲取username// 根據(jù)username查詢用戶數(shù)據(jù):User result = userMapper.findByUsername(username)// 判斷查詢結(jié)果是否不為null// 拋出異常:throw new UsernameDuplicateException();// 執(zhí)行插入用戶數(shù)據(jù),獲取返回值:Integer rows = userMapper.insert(user)// 判斷返回的受影響行數(shù)是否不為1// 拋出異常:throw new InsertException();// 從參數(shù)user中獲取usernameString username = user.getUsername();// 根據(jù)username查詢用戶數(shù)據(jù):User result = userMapper.findByUsername(username)User result = userMapper.findByUsername(username);// 判斷查詢結(jié)果是否不為nullif (result != null) {// 拋出異常:throw new UsernameDuplicateException();throw new UsernameDuplicateException("嘗試注冊(cè)的用戶名(" + username + ")已經(jīng)被占用");}// 補(bǔ)全數(shù)據(jù)-加密后的密碼、鹽值// 1. 生成鹽值String salt = UUID.randomUUID().toString().toUpperCase();// 2. 取出用戶提交的原始密碼String password = user.getPassword();// 3. 執(zhí)行加密String md5Password = getMd5Password(password, salt);// 4. 將鹽值和加密后的密碼補(bǔ)全到user對(duì)象中user.setSalt(salt);user.setPassword(md5Password);// 補(bǔ)全數(shù)據(jù)-isDelete:0user.setIsDelete(0);// 補(bǔ)全數(shù)據(jù)-4項(xiàng)日志Date now = new Date();user.setCreatedUser(username);user.setCreatedTime(now);user.setModifiedUser(username);user.setModifiedTime(now);// 執(zhí)行插入用戶數(shù)據(jù),獲取返回值:Integer rows = userMapper.insert(user)Integer rows = userMapper.insert(user);// 判斷返回的受影響行數(shù)是否不為1if (rows != 1) {// 拋出異常:throw new InsertException();throw new InsertException("插入用戶數(shù)據(jù)時(shí)出現(xiàn)未知錯(cuò)誤!請(qǐng)聯(lián)系系統(tǒng)管理員");}}

單元測(cè)試

最后,創(chuàng)建cn.cyjt.shoot.service.UserServiceTests測(cè)試類,在類的聲明之前添加2個(gè)注解,在類中聲明業(yè)務(wù)層對(duì)象,編寫并執(zhí)行單元測(cè)試

@RunWith(SpringRunner.class)@SpringBootTestpublic class UserServiceTests {@AutowiredIUserService service;@Testpublic void reg() {try {User user = new User();user.setUsername("xxx");user.setPassword("xxx");service.reg(user);System.err.println("OK.");} catch (ServiceException e) {System.err.println(e.getClass());}}} 如果測(cè)試時(shí),提示測(cè)試方法無法運(yùn)行,可能因?yàn)?#xff1a;測(cè)試類不在根包中,測(cè)試類之前沒有添加2個(gè)注解,測(cè)試方法之前沒有@Test注解,測(cè)試方法的權(quán)限不是public,測(cè)試方法的返回值不是void,測(cè)試方法有參數(shù)。

附:

CHAR與VARCHAR的區(qū)別

CHAR是定長(zhǎng)的,即固定長(zhǎng)度,VARCHAR是變長(zhǎng)的,即長(zhǎng)度可變。

無論是使用CHAR還是VARCHAR,都必須指定長(zhǎng)度值。

假設(shè)使用20作為長(zhǎng)度值,使用CHAR(20)時(shí),如果存入的數(shù)據(jù)不足20字符,則MySQL會(huì)補(bǔ)足空格至20個(gè)字符,使用VARCHAR(20)時(shí),以實(shí)際存入的字符為準(zhǔn)!無論使用哪一種,不允許存入超出長(zhǎng)度的字符!

在使用CHAR(20)時(shí),占用的長(zhǎng)度是固定的!使用VARCHAR(20)時(shí),除了存入的字符占據(jù)的長(zhǎng)度以外,默認(rèn)情況下,MySQL還會(huì)另使用1個(gè)字節(jié)記錄實(shí)際字符長(zhǎng)度!假設(shè)在VARCHAR(20)的字段中,存入"David",則MySQL會(huì)另使用1個(gè)字節(jié)記錄5這個(gè)值!由于1個(gè)字節(jié)可以表示的數(shù)字最大是255,如果實(shí)際存入的字符數(shù)量超過255,MySQL會(huì)自動(dòng)擴(kuò)為使用2個(gè)字節(jié)來記錄實(shí)際存入的字符數(shù)!(最多使用2個(gè)字節(jié)記錄)

*有不明白的地方可以評(píng)論留言或者聯(lián)系QQ2085345123 *

接口與抽象方法

應(yīng)該為業(yè)務(wù)層設(shè)計(jì)接口,將需要實(shí)現(xiàn)的功能都聲明為接口中的抽象方法!

所以,需要先創(chuàng)建****.service.IUserService業(yè)務(wù)層接口,并在接口中聲明實(shí)現(xiàn)“注冊(cè)”功能的抽象方法。

業(yè)務(wù)接口中的抽象方法的設(shè)計(jì)原則:

返回值:僅以操作成功為前提來設(shè)計(jì)返回值類型;

方法名稱:與業(yè)務(wù)功能相關(guān)即可,例如“注冊(cè)”功能可以使用reg作為名稱,而“登錄”功能可以使用login作為名稱,一般,不推薦與持久層接口中的名稱完全相同;

參數(shù)列表:必須保證足以調(diào)用持久層中的方法,且這些參數(shù)都是控制器層可以獲取的(控制器中,數(shù)據(jù)的來源可能是用戶提交的);

所以,關(guān)于“注冊(cè)”功能的抽象方法可以是:

void reg(User user);// ---------- 關(guān)于登錄方法設(shè)計(jì)的示例 ----------User login(String username, String password) throws 異常1, 異常2;try {User user = service.login(xx, xx);// ... } catch (異常1 e) {// ... } catch (異常2 e) {// ... }

附碼:

文章不太完整,但這源碼有注釋和數(shù)據(jù)庫10.20pm里。
若有價(jià)值,點(diǎn)個(gè)贊

https://gitee.com/gzllkm/course.git

總結(jié)

以上是生活随笔為你收集整理的springboot入门(项目)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。