四、SpringBoot Web應(yīng)用-1 (基礎(chǔ))

1儒将、簡介

使用SpringBoot
1)吏祸、創(chuàng)建SpringBoot應(yīng)用,選中我們需要的模塊钩蚊;

2)贡翘、SpringBoot已經(jīng)默認(rèn)將這些場(chǎng)景配置好了,只需要在配置文件中指定少量配置就可以運(yùn)行起來

3)砰逻、自己編寫業(yè)務(wù)代碼鸣驱;

2、對(duì)靜態(tài)資源的規(guī)則

官方文檔:靜態(tài)資源

1)默認(rèn)情況下

  • Spring Boot將從類路徑中的/static/public/resources/META-INF/resources)目錄或者根目錄中提供靜態(tài)內(nèi)容ServletContext蝠咆。
  • 它使用ResourceHttpRequestHandlerSpring MVC踊东,因此您可以通過添加自己WebMvcConfigurerAdapteraddResourceHandlers方法來修改該行為并覆蓋該 方法。
  • 在獨(dú)立的Web應(yīng)用程序中勺美,還啟用了容器中的默認(rèn)servlet递胧,并充當(dāng)后備,從ServletContextif 的根目錄提供內(nèi)容赡茸,決定不處理它缎脾。大多數(shù)情況下這不會(huì)發(fā)生(除非你修改默認(rèn)的MVC配置)因?yàn)镾pring總是能夠通過它來處理請(qǐng)求DispatcherServlet

2) 修改默認(rèn)

  • 修改默認(rèn)靜態(tài)資源路徑/**
spring.mvc.static-path-pattern = / resources / **
  • 修改歡迎界面
spring.resources.static-locations = /index.html
  • Webjars
    具有路徑的所有資源/webjars/** 如果以Webjars格式打包占卧,將從jar文件中提供遗菠。
    Webjars需要在pom.xml中引入包
    資源鏈接

src/main/webapp如果您的應(yīng)用程序?qū)⒋虬鼮閖ar,請(qǐng)不要使用該目錄华蜒。雖然這個(gè)目錄是一個(gè)通用標(biāo)準(zhǔn)辙纬,但它只適用于war包裝,如果你生成一個(gè)jar叭喜,它將被大多數(shù)構(gòu)建工具默默忽略贺拣。

3、模板引擎

1)引入thymeleaf

  • 引入
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            2.1.6
</dependency>
  • 切換默認(rèn)版本
<properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
        <!-- thymeleaf2   layout1-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

2)Thymeleaf使用

  • 配置源碼
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");

    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";
可以看出他使用的是`html`頁面
并且其網(wǎng)頁也要放入`classpath:/templates/`路徑之中
  • 只要我們把HTML頁面放在classpath:/templates/捂蕴,thymeleaf就能自動(dòng)渲染譬涡;

1.導(dǎo)入thymeleaf的名稱空間

  <html lang="en" xmlns:th="http://www.thymeleaf.org">

2.使用thymeleaf語法

  <!DOCTYPE html>
  <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
      <meta charset="UTF-8">
      <title>Title</title>
    </head>
    <body>
      <h1>成功!</h1>
      <!--th:text 將div里面的文本內(nèi)容設(shè)置為 -->
      <div th:text="${hello}">這是顯示歡迎信息      </div>
    </body>
  </html>

3)語法規(guī)則

  1. th:任意html屬性啥辨;來替換原生屬性的值


    2018-02-04_123955.png
  2. 表達(dá)式

Simple expressions:(表達(dá)式語法)
    Variable Expressions: ${...}:獲取變量值劝贸;OGNL顶考;
            1)、獲取對(duì)象的屬性抡四、調(diào)用方法
            2)瓣颅、使用內(nèi)置的基本對(duì)象:
                #ctx : the context object.
                #vars: the context variables.
                #locale : the context locale.
                #request : (only in Web Contexts) the HttpServletRequest object.
                #response : (only in Web Contexts) the HttpServletResponse object.
                #session : (only in Web Contexts) the HttpSession object.
                #servletContext : (only in Web Contexts) the ServletContext object.
                
                ${session.foo}
            3)、內(nèi)置的一些工具對(duì)象:
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

    Selection Variable Expressions: *{...}:選擇表達(dá)式:和${}在功能上是一樣;
        補(bǔ)充:配合 th:object="${session.user}:
   <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
    </div>
    
    Message Expressions: #{...}:獲取國際化內(nèi)容
    Link URL Expressions: @{...}:定義URL;
            @{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表達(dá)式
            <div th:insert="~{commons :: main}">...</div>
            
Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(數(shù)學(xué)運(yùn)算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布爾運(yùn)算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比較運(yùn)算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:條件運(yùn)算(三元運(yùn)算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _ 

4帚湘、SpringMVC自動(dòng)配置

官方文檔:SpringMVC自動(dòng)配置

1)Spring MVC auto-configuration

以下是SpringBoot對(duì)SpringMVC的默認(rèn)配置:(WebMvcAutoConfiguration)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 自動(dòng)配置了ViewResolver(視圖解析器:根據(jù)方法的返回值得到視圖對(duì)象(View),視圖對(duì)象決定如何渲染(轉(zhuǎn)發(fā)蒿囤?重定向客们?))
    • ContentNegotiatingViewResolver:組合所有的視圖解析器的;
    • ==如何定制:我們可以自己給容器中添加一個(gè)視圖解析器材诽;自動(dòng)的將其組合進(jìn)來;==
  • Support for serving static resources, including support for WebJars (see below).靜態(tài)資源文件夾路徑,webjars

  • Static index.html support. 靜態(tài)首頁訪問

  • Custom Favicon support (see below). favicon.ico

    ?

  • 自動(dòng)注冊(cè)了 of Converter, GenericConverter, Formatter beans.

    • Converter:轉(zhuǎn)換器恒傻; public String hello(User user):類型轉(zhuǎn)換使用Converter
    • Formatter 格式化器脸侥; 2017.12.17===Date;

2)擴(kuò)展SpringMVC

編寫一個(gè)配置類(@Configuration)盈厘,是WebMvcConfigurerAdapter類型睁枕;不能標(biāo)注@EnableWebMvc

//使用WebMvcConfigurerAdapter可以來擴(kuò)展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器發(fā)送 /atguigu 請(qǐng)求來到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

3)全面接管SpringMVC

SpringBoot對(duì)SpringMVC的自動(dòng)配置不需要了,所有都是我們自己配置沸手;所有的SpringMVC的自動(dòng)配置都失效了

我們需要在配置類中添加@EnableWebMvc即可外遇;

5、如何修改SpringBoot的默認(rèn)配置

  • 模式:

? 1)SpringBoot在自動(dòng)配置很多組件的時(shí)候契吉,先看容器中有沒有用戶自己配置的(@Bean跳仿、@Component)如果有就用用戶配置的,如果沒有捐晶,才自動(dòng)配置菲语;如果有些組件可以有多個(gè)(ViewResolver)將用戶配置的和自己默認(rèn)的組合起來;

? 2)在SpringBoot中會(huì)有非常多的xxxConfigurer幫助我們進(jìn)行擴(kuò)展配置

? 3)惑灵、在SpringBoot中會(huì)有很多的xxxCustomizer幫助我們進(jìn)行定制配置

6山上、Restful風(fēng)格

1)Restful風(fēng)格注解

    @PostMapping
    @DeleteMapping
    @GetMapping
    @PutMapping

例如:@PostMapping中都配置了(簡化了寫法)

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
    method = {RequestMethod.POST}
)

2)默認(rèn)訪問首頁

//使用WebMvcConfigurerAdapter可以來擴(kuò)展SpringMVC的功能
//@EnableWebMvc   不要接管SpringMVC
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器發(fā)送 /atguigu 請(qǐng)求來到 success
        registry.addViewController("/atguigu").setViewName("success");
    }

    //所有的WebMvcConfigurerAdapter組件都會(huì)一起起作用
    @Bean //將組件注冊(cè)在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return adapter;
    }
}

3)登陸

1.禁用模板引擎的緩存

# 禁用緩存
spring.thymeleaf.cache=false 

2.頁面修改完成以后ctrl+f9:重新編譯;

  • 登陸錯(cuò)誤消息的顯示
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

4)攔截器進(jìn)行登陸檢查

  • 編寫攔截器HandlerInterceptor
**
 * 登陸檢查英支,
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目標(biāo)方法執(zhí)行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登陸佩憾,返回登陸頁面
            request.setAttribute("msg","沒有權(quán)限請(qǐng)先登陸");
            //重定向
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else{
            //已登陸,放行請(qǐng)求
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
  • 注冊(cè)自定義攔截器 寫在自定義配置類中
/**
 * 聲明這是一個(gè)配置類
 * */
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    //所有的WebMvcConfigurerAdapter組件都會(huì)一起起作用
    @Bean//將組件注冊(cè)到容器中
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");

            }

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                /**
                 * addInterceptor   添加攔截器
                 * addPathPatterns  添加攔截路徑 --  /**表示所有
                 * excludePathPatterns  添加例外路徑
                 *
                 * */
                registry.addInterceptor(new LoginState()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");
            }
        };
        return adapter;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末干花,一起剝皮案震驚了整個(gè)濱河市妄帘,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌把敢,老刑警劉巖寄摆,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異修赞,居然都是意外死亡婶恼,警方通過查閱死者的電腦和手機(jī)桑阶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來勾邦,“玉大人蚣录,你說我怎么就攤上這事【炱” “怎么了萎河?”我有些...
    開封第一講書人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蕉饼。 經(jīng)常有香客問我虐杯,道長,這世上最難降的妖魔是什么昧港? 我笑而不...
    開封第一講書人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任擎椰,我火速辦了婚禮,結(jié)果婚禮上达舒,老公的妹妹穿的比我還像新娘。我一直安慰自己叹侄,他們只是感情好巩搏,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開白布睦擂。 她就那樣靜靜地躺著述呐,像睡著了一般思犁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,255評(píng)論 1 308
  • 那天刃鳄,我揣著相機(jī)與錄音愉烙,去河邊找鬼。 笑死解取,一個(gè)胖子當(dāng)著我的面吹牛步责,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播禀苦,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼蔓肯,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了振乏?” 一聲冷哼從身側(cè)響起蔗包,我...
    開封第一講書人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎慧邮,沒想到半個(gè)月后调限,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體舟陆,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年旧噪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吨娜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡淘钟,死狀恐怖宦赠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情米母,我是刑警寧澤勾扭,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站铁瞒,受9級(jí)特大地震影響妙色,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜慧耍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一身辨、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧芍碧,春花似錦煌珊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至踪危,卻和暖如春蔬浙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背贞远。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來泰國打工畴博, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人兴革。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓绎晃,卻偏偏與公主長得像,于是被迫代替她去往敵國和親杂曲。 傳聞我的和親對(duì)象是個(gè)殘疾皇子庶艾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359

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