SpringBoot 入門配置篇(二)

上一篇學習了SpringBoot的一些基本必學用法檩坚,這一篇來學習一下SpringBoot相關(guān)配置。

前言

本篇文章的主要內(nèi)容:

  • 配置Https
  • 配置攔截器
  • 配置頁面轉(zhuǎn)向
  • 配置資源指向
  • 配置favicon.ico
  • 配置banner

配置Https

  1. 生成證書

通過keytool命令來生成树绩,如果提示命令不存在,需要配置java環(huán)境變量硬耍,然后根據(jù)提示輸入秘鑰口令和相關(guān)信息影所,最后會得到一個keystore.p12文件,把它復制到項目resources目錄下赶袄。

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

命令中-alias設(shè)置別名揽涮,-storetype 設(shè)置證書格式,-keyalg設(shè)置加密算法饿肺,-keysize設(shè)置證書大小蒋困,-keystore設(shè)置證書文件地址,-validity設(shè)置有效天數(shù)敬辣。

  1. 配置application.yml
server:
  port: 8443
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: 123456
    key-store-type: PKCS12
    key-alias: tomcat
    enabled: true

修改port為8443雪标,添加ssl里面信息就填我們剛才命令設(shè)置的

  1. 添加ConnectorConfig.java
@Configuration
public class ConnectorConfig {
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(getHttpConnector());
        return tomcat;
    }

    private Connector getHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8088);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}

創(chuàng)建ConnectorConfig.java配置文件到config目錄下并復制以上代碼零院。代碼collection.addPattern("/*")設(shè)置所有路徑都配置https,如果只想設(shè)置/users下的路徑配置https村刨,只需要改/*/users/*即可告抄。

以上就是配置https的相關(guān)步驟,很簡單吧嵌牺。

配置攔截器

配置攔截器有很多用途打洼,這里就舉一個最常見的例子。我們在瀏覽網(wǎng)頁的時候髓梅,如果未登錄拟蜻,就會自動跳轉(zhuǎn)到登錄界面,下面我們通過Api接口來簡單的實現(xiàn)一下這個功能枯饿。

  1. 添加SessionInterceptor攔截器
@Component("sessionInterceptor")
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("SessionInterceptor preHandle");
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            return true;
        } else {
            PrintWriter printWriter = response.getWriter();
            printWriter.write("{code: 501, message:\"not login!\"}");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("SessionInterceptor postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("SessionInterceptor afterCompletion");
    }

}

preHandle()該方法將在請求處理之前進行調(diào)用,返回true會執(zhí)行下一個Interceptor,返回false則不會執(zhí)行下一個Interceptor也不會執(zhí)行Controller里的方法,先聲明的Interceptor的preHandle方法會先執(zhí)行酝锅。這里去獲取session中user的信息,如果存在則不攔截奢方,否則輸出501錯誤搔扁。

postHandle()該方法將在當前請求進行處理之后調(diào)用,且preHandle方法返回為true,先聲明的Interceptor的postHandle方法會后執(zhí)行

afterCompletion()該方法將在請求完成之后調(diào)用,同樣且需要preHandle方法返回為true,一般用于進行資源清理

  1. 添加WebMvcConfig
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private SessionInterceptor sessionInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/register", "/user/login", "/error");
    }
}

addPathPatterns("/**")設(shè)置攔截所有路徑地址。

excludePathPatterns()設(shè)置過濾不需要攔截的路徑地址蟋字,這里配置了注冊稿蹲、登錄和錯誤地址。

  1. 添加login接口

MyUserMapper.xml

<select id="login" resultMap="userMap">
    select * from user_t
    where username = #{userName} and password = #{password}
</select>

MyUserMapper.java, 因為注冊接口沒有做唯一限制鹊奖,所有有可能查詢多個苛聘,這里就用List來接收

List<MyUser> login(@Param("userName") String userName, @Param("password") String password);

MyUserServices.java

public List<MyUser> login(String userName, String password) {
    return userMapper.login(userName, password);
}

MyUserController.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ResponseResult<MyUser> login(HttpServletRequest request, String userName, String password) {
    ResponseResult<MyUser> responseResult;
    try {
        List<MyUser> myUser = myUserServices.login(userName, password);
        if (myUser != null && myUser.size() > 0) {
            request.getSession(true).setAttribute("user", myUser.get(0));
            responseResult = new ResponseResult<>(200, "login success", myUser.get(0));
        } else {
            responseResult = new ResponseResult<>(501, "login failure: invalid userName or password", null);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseResult = new ResponseResult<>(501, "login failure: " + e.getMessage(), null);
    }
    return responseResult;
}

getSession(true)指的是如果不存在則會創(chuàng)建一個,存在則直接返回忠聚。登錄成功后通過setAttribute設(shè)置user信息session设哗,之后攔截器就能通過getAttribute("user")來獲取到了。

至此两蟀,基本功能就已經(jīng)實現(xiàn)了网梢,當調(diào)用/user/login登錄接口成功后,再去調(diào)用其它接口不會返回501提示赂毯,否則除"/user/register", "/user/login", "/error"這幾個之外的接口都會提示501未登錄提示战虏!

配置頁面轉(zhuǎn)向

  1. 靜態(tài)頁面轉(zhuǎn)向

很多時候我們需要在Controller中寫類似下面的這樣代碼,沒有業(yè)務邏輯党涕,只有返回一個地址烦感,通過瀏覽器訪問 http://localhost:8088/hello 地址就能轉(zhuǎn)向?qū)猺esources下靜態(tài)頁面路徑下的hello.html頁面了。

@RequestMapping("/hello")
public String test() {
    return "hello.html";
}

這樣的功能可以在WebMvcConfig簡單的配置實現(xiàn)膛堤,添加代碼如下:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/hello").setViewName("hello.html");
}
  1. 靜態(tài)頁面路徑

優(yōu)先級訪問從高到低依次如下:

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/

上面classpath指的是與java文件夾同級的resources文件夾

  1. 動態(tài)頁面轉(zhuǎn)向

添加依賴包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

添加了thymeleaf之后手趣,通過瀏覽器訪問 http://localhost:8088/hello 地址就會轉(zhuǎn)向?qū)猼emplates路徑下的hello.html頁面。同時可以省去后綴名.html

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/hello").setViewName("hello");
}
  1. 動態(tài)頁面?zhèn)髦?/li>

添加index.html到templates文件夾下, 里面有一個name參數(shù)需要從controller中映射

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <link th:src="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet">
    <link th:src="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet">
    <title>Title</title>
</head>
<body>
<script th:src="@{jquery-1.10.2.min.js}" type="text/javascript"></script>
<script th:src="@{bootstrap/js/bootstrap.min.js}" ></script>
Hello <span th:text="${name}"></span>!
</body>
</html>

添加IndexController.java到controller文件夾, 通過Model對象來設(shè)置name的屬性值

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String hello(Model model) {
        model.addAttribute("name", "Soaic");
        return "index";
    }
}

最后在瀏覽器訪問 http://localhost:8088/index 地址就能看到Hello Saoic!骑祟。

配置資源映射

如果想訪問項目中的靜態(tài)資源回懦,除了把資源放到上面那些靜態(tài)資源地址目錄下,還可以通過配置來設(shè)置次企。只需要在WebMvcConfig中重寫addResourceHandlers方法怯晕,代碼如下:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/");
}

配置后通過地址 http://localhost:8088/images/xxx 就能訪問resources/images/目錄下的資源了

配置favicon.ico

  1. 設(shè)置favicon的開關(guān)

在application.yml中配置

spring:
  mvc:
    favicon:
      enabled: true
  1. 添加favicon.ico到默認靜態(tài)資源目錄

ico 制作的網(wǎng)上有很多,這里就不多說了缸棵。

  1. 在html文件中添加
<head>
    <link rel="shortcut icon" href="/static/favicon.ico" />
</head>

我這里是把favicon.ico放在static目錄下了舟茶。有些瀏覽器第三步不用做,只要放進了靜態(tài)資源目錄就能顯示顯示出來堵第。

配置banner

每次項目啟動的時候吧凉,控制臺會顯示一個字符拼接的圖形,顯示這個圖形的配置很簡單踏志。

制作一個banner.txt, 網(wǎng)上有很多可以找找阀捅,大家可以找找看,然后復制到resources資源根目錄下针余,然后啟動項目就能看到了饲鄙。

                      _ooOoo_
                     o8888888o
                     88" . "88
                     (| ^_^ |)
                     O\  =  /O
                  ____/`---'\____
                .'  \\|     |  `.
               /  \\|||  :  |||  \
              /  _||||| -:- |||||-  \
              |   | \\\  -  / |   |
              | \_|  ''\---/''  |   |
              \  .-\__  `-`  ___/-. /
            ___`. .'  /--.--\  `. . ___
          ."" '<  `.___\_<|>_/___.'  >'"".
        | | :  `- \`.;`\ _ /`;.`/ - ` : | |
        \  \ `-.   \_ __\ /__ _/   .-` /  /
  ========`-.____`-.___\_____/___.-`____.-'=======
                       `=---='
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        佛祖保佑       永不宕機     永無BUG

上面是我在網(wǎng)上找的一個,大家可以拿去試試

以上就是本篇文章的全部內(nèi)容圆雁,希望對大家有所幫助忍级,下篇再見!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末伪朽,一起剝皮案震驚了整個濱河市轴咱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌烈涮,老刑警劉巖朴肺,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異跃脊,居然都是意外死亡宇挫,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門酪术,熙熙樓的掌柜王于貴愁眉苦臉地迎上來器瘪,“玉大人,你說我怎么就攤上這事绘雁∠鹛郏” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵庐舟,是天一觀的道長欣除。 經(jīng)常有香客問我,道長挪略,這世上最難降的妖魔是什么历帚? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任滔岳,我火速辦了婚禮,結(jié)果婚禮上挽牢,老公的妹妹穿的比我還像新娘谱煤。我一直安慰自己,他們只是感情好禽拔,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布刘离。 她就那樣靜靜地躺著,像睡著了一般睹栖。 火紅的嫁衣襯著肌膚如雪硫惕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天野来,我揣著相機與錄音恼除,去河邊找鬼。 笑死曼氛,一個胖子當著我的面吹牛缚柳,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播搪锣,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼秋忙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了构舟?” 一聲冷哼從身側(cè)響起灰追,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎狗超,沒想到半個月后弹澎,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡努咐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年苦蒿,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片渗稍。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡佩迟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出竿屹,到底是詐尸還是另有隱情报强,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布拱燃,位于F島的核電站秉溉,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜召嘶,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一父晶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧弄跌,春花似錦诱建、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽茎匠。三九已至格仲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間诵冒,已是汗流浹背凯肋。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留汽馋,地道東北人侮东。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像豹芯,于是被迫代替她去往敵國和親悄雅。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容