天天看點

記一次SpringBoot 開發中所遇到的坑和解決方法

記一次SpringBoot 開發中所遇到的坑和解決方法

mybatis傳回Integer為0,自動轉型出現空指針異常

當我們使用Integer去接受資料庫中表的資料,如果傳回的資料中為0,那麼Integer便為

null

,這時候将Interger自動轉型為int,則會出現空指針異常

這個時候,我們可以在Service層對Integer的資料進行判斷,如果為空,就把它指派為0

// 在pojo中,如果Integer canJoinNun為null 就把值設定為0
if (publishMsg.getCanJoinNum() == null) {
   publishMsg.setCanJoinNum();
}
           

關于開啟druid的監控界面

maven包的引入:

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.0.0</version>
</dependency>
<!-- 要引入log4j,不然druid會報錯 -->
<dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.17</version>
</dependency>
           

配置檔案:

spring:
  	datasource:
      url: jdbc:mysql://localhost:3306/test?useAffectedRows=true&allowMultiQueries=true
      username: # 賬号
      password: # 密碼
      driver-class-name: com.mysql.cj.jdbc.Driver
      platform: mysql
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
         # 下面為連接配接池的補充設定,應用到上面所有資料源中
         # 初始化大小,最小,最大
         initialSize: 
         minIdle: 
         maxActive: 
         # 配置擷取連接配接等待逾時的時間
         maxWait: 
         # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接配接,機關是毫秒
         timeBetweenEvictionRunsMillis: 
         # 配置一個連接配接在池中最小生存的時間,機關是毫秒
         minEvictableIdleTimeMillis: 
         validationQuery: select 'x'
         testWhileIdle: true
         testOnBorrow: false
         testOnReturn: false
         # 打開PSCache,并且指定每個連接配接上PSCache的大小
         #    pool-prepared-statements: true
         #    max-open-prepared-statements: 20
         # 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用于防火牆
         filters: stat,wall,log4j
         # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
         connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
         # 配置DruidStatFilter
         web-stat-filter:
         enabled: true
         url-pattern: "/*"
         exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
         # 配置DruidStatViewServlet
         stat-view-servlet:
         enabled: true
         url-pattern: "/druid/*"
         # IP白名單(沒有配置或者為空,則允許所有通路)
         #          allow: ****
         # IP黑名單 (存在共同時,deny優先于allow)
         #          deny: ****
         #  禁用HTML頁面上的“Reset All”功能
         reset-enable: false
         # 登入名
         login-username: admin
         # 登入密碼
         login-password: 
           

向mysql插入中文字元串,插入成功之後資料顯示==?==

​ 這個問題有點奇葩,我在本地的manjaro環境中進行開發,插入中文字元串沒有問題,但是當我把springboot應用部署到Ubuntu伺服器上時,便出現插入中文字元串,最後卻顯示==?==的情況。

解決方法:在jdbc的連結後面加上characterEncoding=utf8即可

​ 不過,還是不懂為什麼在本地不加characterEncoding=utf8也沒問題。

關于跳轉的問題

場景:此時我有一個xxx.com的域名,我用nginx做代理,将xxx.com/project_A/**的請求轉到springboot的project_A項目中。這時候我們不可能在每一個路由RequestMapping中,前面都加上一個project_A吧。

nginx的配置:

server {
   listen 80;
   server_name xxx.com;
   root /usr/tomcat/webapps;
   charset utf-8;
   location /project_A {
   proxy_pass http://127.0.0.1:8080/project_A;
   proxy_cookie_path /project_A /;

   }
}
           

這時候,nginx便會将所有的以==xxx.com/project_A/==轉到project_A的項目中。

那麼在前端的thymeleaf中,應該怎麼修改呢?

css引用:使用th:href="@{……}" target="_blank" rel="external nofollow"

js引用:使用th:src="@{……}"

在ajax請求中,請求路由的寫法:

<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
$.ajax({
   url: /*[[@{/publish/getContent}]]*/,
   async: false,
   data: form.serialize(),
   complete: function (msg) {
      console.log("完成!");
   },
   success: function (result) {
      console.log(result);	
   }
})
/*]]>*/
</script>
           
Tips: js内聯代碼中需要加入

……

代碼塊,thymeleaf才能正确解析一些運算符(<等)和操作符号&/&&等。

當我們這樣使用的時候,他就能夠在模闆解析的時候自動将project_A,加載在引用的前面。例如:前面的css引用解析的時候就會變成

在後端的RequestMapping中,并不需要去修改裡面的值,甚至說,

return "redirect:/page/index"

都不需要去修改。但是,卻有一個奇葩,那就是在攔截器中的那個重定向:

response.sendRedirect("/login/index");
           

因為在攔截器中,我們隻能夠return true或者false,是以我們進行重定向就得使用response.sendRedirect進行重定向,如果我們這樣使用,那麼它進行重定向就會重定向到xxx.com/login/index去,而不是xxx.com/project_A/login/index

是以我們不得不更改為

response.sendRedirect("/project_A/login/index");

不過我總感覺應該會有其他方法去解決這個問題,因為這樣做的話,一旦更改,就必須得重新改代碼或者檔案。如果有的話,可以在評論區留言,謝謝。

資料庫的時間問題

在mybatis中,向資料庫插入時間直接使用java.util.Date即可。

springboot mybatis下劃線轉駝峰

本來以為能夠自己轉的,然後發現自己想多了,╮(╯▽╰)╭

mybatis:
   #  mapper的位置
   mapper-locations: classpath:mapper/*.xml
   configuration:
      # 開啟下劃線轉駝峰
      map-underscore-to-camel-case: true
           

Springboot MySql分頁AOP

場景:有多個網頁,但是每個網頁的每一頁都隻顯示資料庫的10條資料,這個時候我們便需要進行分頁。但是如果每次去select資料是,都去寫一次分頁,這毫無疑問,是一個重複的勞動力。OK,既然OOP是重複的勞動力,那麼我們便使用AOP吧。

maven引入

<!-- Mybatis分頁依賴-->
<dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper-spring-boot-starter</artifactId>
   <version>1.2.10</version>
</dependency>
<!--springboot的AOP-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
           

MyService獲得資料裡面的資料

// Mapper
   @Autowired
   private GetMsgMapper getMsgMapper;

   @Override
   public Object getJoinMsgsWithPage(Integer page, String id) {
      return getMsgMapper.getJoinMsgs(id);
   }
           

切面的寫法

@Component 	// 注入到IOC容器裡面
@Aspect		//是之成為切面類
public class PageSql {

   // 定義每頁拿出多少資料
   public static final Integer PAGE_NUM = ;
   
   // 切入的點 切com.xxx.service.serviceImpl包下所有類中以WithPage結尾的方法
   @Pointcut("execution(public * com.xxx.service.serviceImpl.*.*WithPage(..))")
   public void serviceFindFunction() {
   }

   @Around("serviceFindFunction()")
   public Object serviceImplAop(ProceedingJoinPoint point) throws Throwable {
      // 獲得切入點的參數
      Object[] args = point.getArgs();
      // 在我的使用中,第一個參數是page,也就是取第幾頁的資料
      PageHelper.startPage((Integer) args[], PAGE_NUM);
      // 執行原來的方法得到資料
      Object object = point.proceed(args);
      // 假如拿到的資料是List的這種類型,則就進行分頁,否則就直接傳回
      if (object instanceof List) {
         List objList = (List) object;
         PageInfo pageInfo = new PageInfo<>(objList);
         return pageInfo;
      }
      return object;
   }
}
           

這樣,當我們在Controller裡面去調用的時候就很爽了

調用示例:

PageInfo pageInfo = (PageInfo)MyService.getJoinMsgsWithPage(, "8888");
           

在這裡面,傳回的pageInfo就是已經經過分頁的資料了。

自己蠢了的地方 404 NOT FOUND

在将springboot項目部署到伺服器上面的時候,剛開始隻想試試能不能夠部署成功,然後就暫時沒有将本地的資料庫部署上去。再然後,就陷入了為啥本地能運作而遠端不能運作的死循環了。到後面才發現,因為無法連結資料庫,project都沒有啟動。╮(╯▽╰)╭

記一次SpringBoot 開發中所遇到的坑和解決方法

img

轉載于:https://www.cnblogs.com/xiaohuiduan/p/10743718.html