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ī)則
1)默認(rèn)情況下
- Spring Boot將從類路徑中的
/static
(/public
或/resources
或/META-INF/resources
)目錄或者根目錄中提供靜態(tài)內(nèi)容ServletContext
蝠咆。 - 它使用
ResourceHttpRequestHandlerSpring MVC
踊东,因此您可以通過添加自己WebMvcConfigurerAdapter
的addResourceHandlers
方法來修改該行為并覆蓋該 方法。 - 在獨(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ī)則
-
th:任意html屬性啥辨;來替換原生屬性的值
2018-02-04_123955.png 表達(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)配置
1)Spring MVC auto-configuration
以下是SpringBoot對(duì)SpringMVC的默認(rèn)配置:(WebMvcAutoConfiguration)
-
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
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
)盈厘,是WebMvcConfigurerAdapte
r類型睁枕;不能標(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;
}
}