BBS論壇專案相關-1:相關工具Spring,MyBatis等(持更)

2020-08-11 20:21:38

BBS論壇專案相關-1:相關工具Spring,MyBatis等(持更)

Spring 入門

Springboot的入口

@SpringBootApplication
public class CommunityApplication {
    public static void main(String[] args) {
        SpringApplication.run(CommunityApplication.class, args);
    }
}

@SpringBootApplication : 是Sprnig Boot專案的核心註解,目的是開啓自動設定,底層包含多個註解。其底層包括@ComponentScan、 @EnableAutoConfiguration
、@SpringBootConfiguration 、@Inherited 註解【宣告的此註解使用了Inherited元註解,表示此註解用在類上時,會被子類所繼承】、@Documented 註解、@Retention() 註解、@Target() 註解

@ComponentScan 註解:元件掃描,會掃描組態檔所在的包及子包;掃描@Controller,@Service,@Component,@repository等註解註釋的類

@ComponentScan(excludeFilters = {
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

對於測試類,因爲與組態檔不在同一個包下,所以需要自己設定,爲了跟主檔案搭配一樣的組態檔,可用@ContextConfiguration(classes = CommunityApplication.class)引入主檔案設定類。
可以類實現ApplicationContextAware介面,重寫setApplicationContext方法,獲取參數中傳遞過來的ApplicationContext的spring容器,從而獲得bean;

public class CommunityApplicationTests implements ApplicationContextAware {
	private ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}

Spring MVC

MVC:Model:模型層,View:表現層 Controller:控制層 核心元件:DispatcherSevlet

Spring MVC流程:

待補充…

Thymeleaf
Thymeleaf 模板引擎,生成動態HTML,倡導自然模板,即以HTML檔案爲模板
Thymeleaf預設開啓快取,需要先把快取關掉,不然頁面有快取,重新整理會有延時。
spring.thymeleaf.cache=false;

獲取請求數據
HttpServltRequest

@RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response) {
        // 獲取請求數據
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ": " + value);
        }
        System.out.println(request.getParameter("code"));

        // 返迴響應數據
        response.setContentType("text/html;charset=utf-8");
        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.write("<h1>牛客網</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

get和post亂碼:
post採用的編碼由頁面決定即contentType(「text/html」,charset=GBK),點選submit提交表單時,瀏覽器會根據contentType的charset編碼格式對post的表單參數進行編碼傳給伺服器,在伺服器端同樣用contentType編碼對其解碼,所以post一般不會亂碼。可以設定request.setCharacterEncoding(charset);設定編碼,通過request.getParameter()獲取參數。
get通過將請求數據附加到url後面傳參數,數據容易出現亂碼。url拼接後,瀏覽器對其進行encode,然後發送給伺服器,Tomcat伺服器會通過URIEncoding對其進行解碼,預設爲ISO-8859-1來解碼,若頁面設定爲UTF-8,解碼時就會出錯。可在接收數據時設定new String(request.getParameter(「name」).getBytes(「iso-8895-1」),「utf-8」);

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

GET:用於獲取伺服器數據,返回實體主體
POST:對提交請求進行處理,可能造成新的資源建立或已有數據的修改,包含在請求體中。
向瀏覽器響應數據
html:1) 直接返回ModelAndView物件;2)返回字串作爲view,將model作爲參數傳入,將數據放在model裡。
json:非同步請求中,通過json字串完成java物件到JS物件的轉換,任何語言都有字串,所以可以用json字串作爲各種語言之間的中間轉換。
加上@responseBody註解返回json物件

Mybatis

核心元件:
SqlSessionFactory:用於建立SqlSession的工廠類
SqlSession:MyBatis核心元件,用於向數據庫執行SQL
主組態檔:XML組態檔,可以對MyBatis的底層行爲做出詳細的設定
Mapper介面:Dao介面,在MyBatis中稱爲Mapper
Mapper對映器:用於編寫SQL,並將SQL和實體類對映的元件,採用xml,註解都可實現。

常用Mybatis標籤:

    <sql id="selectFields">
        id, username, password, salt, email, type, status, activation_code, header_url, create_time
    </sql>
    <select id="selectById" resultType="User">
        select <include refid="selectFields"></include>
        from user
        where id = #{id}
    </select>

@Param註解是Mybatis提供的,作爲Dao層的註解,用於給參數取別名,可以與SQL中的欄位名相對應,如果只有一個參數,且在< if >中使用,必須加別名
待補充…
數據庫連線步驟

專案偵錯技巧

設定日誌級別,將日誌輸出到不同終端
logback

package org.slf4j;
public interface Logger{
  public void trace(String message);
  public void debug(String message);
  public void info(String message);
  public void warn(String message);
  public void error(String message);
}

可直接從log工廠中獲取logger,將類傳入作爲logger的名字

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class LoggerTests {

    private static final Logger logger = LoggerFactory.getLogger(LoggerTests.class);
    @Test
    public void testLogger() {
        System.out.println(logger.getName());
        logger.debug("debug log");
        logger.info("info log");
        logger.warn("warn log");
        logger.error("error log");
    }
}

一般日誌會直接列印在控制檯不會儲存,需要設定儲存:

logging.level.com.nowcoder.community=debug
logging.file=d:/work/data/nowcoder/community.log

一般是將不同級別的日誌存在不同的檔案,便於檢視,一般用logback-spring.xml設定

版本控制

程式碼備份,儲存版本,可以上傳到遠端倉庫,程式碼共用
分佈式版本控制,本地倉庫和遠端倉庫,防止伺服器垮掉,先提交到本地倉庫,再提交到遠端倉庫。
Git常用命令列
對git設定:git config --list檢視原本的設定;
git config --global user.name 「xxx」
git config --global user.email 「xxx」
提交到本地倉庫
git init 初始化,建立一個git倉庫,會在當前目錄生成一個.git檔案
git status檢視狀態,是否提交
git add 新增
git rm 刪除
git commit -m 提交的說明 提交
git diff filename 如果檔案修改了但還沒提交,可通過該命令檢視修改的不同
git log 檢視日誌
git reset 檢視回退
git rflog 檢視命令歷史
git branch 檢視分支命令,帶*號的就是當前分支
git checkout 分支名 切換到指定分支
git merge 分支名 合併某分支的內容到當前分支
git branch -d 分支名 刪除分支
提交到遠端倉庫
ssh-keygen -t rsa -C 「郵箱」 建立祕鑰,保證安全傳輸
git remote add origin https://git.newcoder.com/334190970/mavendemo.git 新增遠端倉庫地址
git remote remove origin 移除遠端倉庫
git push -u origin master 把本地倉庫的內容推播到遠端倉庫,-u表示第一次推播master分支上的所有內容,之後就不用加了
git pull 從遠端倉庫更新內容到本地倉庫
IDE中VCS欄的git項初始化專案到本地倉庫及提交專案
push推播到遠端倉庫

數據庫設計(待補充)

貼文:貼文id,標題,內容,型別(0-普通,1-置頂), 狀態(0-正常,1-精華,2-拉黑),評論數量(冗餘儲存,這樣查詢時不用關聯表),分數。