- Springboot web實(shí)際上就是在SpringMvc上做了進(jìn)一步的封裝,同時(shí)引入自己的很多特性和思想,使開發(fā)進(jìn)一步簡化。
- 擴(kuò)展:(1)如果Spring Boot提供的Sping MVC不符合要求,則可以通過一個(gè)配置類(注解有@Configuration的類)加上@EnableWebMvc注解來實(shí)現(xiàn)完全自己控制的MVC配置。(2)通常情況下,Spring Boot的自動配置是符合我們大多數(shù)需求的,在你既需要保留Spring Boot提供的便利,有需要增加自己的額外的配置的時(shí)候,可以定義一個(gè)配置類并實(shí)現(xiàn)WebMvcConfigurer或者繼承WebMvcConfigurationSupport 類,無需使用@EnableWebMvc注解。
一、Springboot整合thymleaf模板
1、Springboot模板簡介
- Spring Boot提供了默認(rèn)配置的模板引擎主要有以下幾種:Thymeleaf
、FreeMarker、Velocity、Groovy、Mustache等模板引擎 - 當(dāng)你使用上述模板引擎中的任何一個(gè),它們默認(rèn)的模板配置路徑為:src/main/resources/templates;靜態(tài)資源放置在src/main/resources/static目錄下面。
2、使用案例
(1)引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)controller類
@Controller
public class ThymleafController {
@RequestMapping("/index")
public String index(ModelMap map) {
// 加入一個(gè)屬性,用來在模板中讀取
map.addAttribute("host", "http://blog.didispace.com");
// return模板文件的名稱,對應(yīng)src/main/resources/templates/index.html
return "index";
}
}
(3)在templates下面創(chuàng)建thymleaf文件,index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>
(4)核心配置文件中配置
- Thymeleaf的默認(rèn)參數(shù)配置
# Enable template caching.
spring.thymeleaf.cache=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.content-type=text/html
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true
# Template encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names=
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
可以參考博文:http://tengj.top/2017/03/13/springboot4/
二、文件上傳和下載
- 上傳到本地服務(wù)器
(1)客戶端
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="files" /><br/><br/>
<input type="submit" value="Submit" />
</form>
<a href="/download">download</a>
(2)文件上傳和下載controller類
@RestController
public class UpAndDownFileController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest request, MultipartFile[] files) {
try {
//獲取web項(xiàng)目的全路徑
// String uploadDir = request.getSession().getServletContext().getRealPath("/");
//獲取自定義目錄
String uploadDir = "F://a";
File file = new File(uploadDir);
if (!file.exists()) {
file.mkdir();
}
for (int i = 0; i < files.length; i++) {
if (files[i] != null) {
//進(jìn)行文件上傳
uploadFile(uploadDir, files[i]);
}
}
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
private void uploadFile(String dir, MultipartFile file) throws IOException {
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String fileName = UUID.randomUUID() + fileSuffix;
File serverFile = new File(dir + fileName);
file.transferTo(serverFile);
}
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "a.txt";// 設(shè)置文件名,根據(jù)業(yè)務(wù)需要替換成要下載的文件名
if (fileName != null) {
//設(shè)置文件路徑
String realPath = "f://a";
File file = new File(realPath , fileName);
if (file.exists()) {
//response.setContentType("application/octet-stream");
response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設(shè)置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
- 上傳到圖片服務(wù)器(下次討論)
三、Springboot web靜態(tài)問價(jià)路徑規(guī)則
- Spring Boot默認(rèn)提供靜態(tài)資源目錄位置需置于classpath下,目錄名需符合如下規(guī)則:
/static
/public
/resources
/META-INF/resources
- SpringBoot默認(rèn)給我們配置了靜態(tài)資源的地址轉(zhuǎn)發(fā),我們只需要將靜態(tài)文件放到/resources/static目錄下,就可以直接訪問了但是這樣往往會暴露給用戶我們的項(xiàng)目結(jié)構(gòu),針對這一點(diǎn)我們需要修改靜態(tài)資源的路徑.
@Configuration
public class Chapter9Configuration extends WebMvcConfigurationSupport
{
//自定義靜態(tài)資源文件路徑,訪問http://localhost/resources/a.js則
//會直接定位到項(xiàng)目根目錄下面的/my/static/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("classpath:/my/static/");
}
}
四、攔截器使用
- 攔截器是一個(gè)重要的概念,可以做很多的事情。攔截器主要是在進(jìn)入接口方法之前和執(zhí)行完接口返回?cái)?shù)據(jù)給前臺之前進(jìn)行響應(yīng)的邏輯操作。攔截器可以完成比如:日志的記錄,ip黑白名單攔截,ip限流、用戶登錄狀態(tài)攔截,安全攔截等等。
- 注意在整個(gè)項(xiàng)目中只有一個(gè)WebMvcConfigurationSupport類出現(xiàn),否則其他不生效
(1)簡單使用
1、創(chuàng)建攔截器
public class MyInterceptor implements HandlerInterceptor {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("在DispatcherServlet渲染頁面之前執(zhí)行");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("在完成所有請求處理后,也就是說在渲染完頁面后,返回前臺之前執(zhí)行");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("執(zhí)行handler之前執(zhí)行");
return true;
}
}
2、在配置中進(jìn)行攔截器注冊
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
//注冊自定義攔截器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
(2)應(yīng)用舉例
- 日志記錄(AOP也可以實(shí)現(xiàn))
- ip攔截和限流
- 用戶登錄驗(yàn)證(token驗(yàn)證)
- 黑白名單驗(yàn)證
參考博文:http://tengj.top/2017/03/30/springboot6/
五、跨域
六、監(jiān)聽器使用
七、fastjson使用
- 例如使用列表返回的時(shí)候就有可能需要使用下面的配置,但是如果先使用JSON.toJSONString方法轉(zhuǎn)為string后再傳就可以不需要下面的方法
@Configuration
public class FastJson extends WebMvcConfigurationSupport {
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
//消除對同一對象循環(huán)引用的問題,默認(rèn)為false(如果不配置有可能會進(jìn)入死循環(huán))
SerializerFeature.DisableCircularReferenceDetect,
//List字段如果為null,輸出為[],而非null
SerializerFeature.WriteNullListAsEmpty,
//字符類型字段如果為null,輸出為"",而非null
SerializerFeature.WriteNullStringAsEmpty,
//Boolean字段如果為null,輸出為false,而非null
SerializerFeature.WriteNullBooleanAsFalse,
//是否輸出值為null的字段,默認(rèn)為false。
SerializerFeature.WriteMapNullValue
);
//處理中文亂碼問題(不然出現(xiàn)中文亂碼)
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastJsonHttpMessageConverter);
}
}
- 原理
八、其他(用的少)
- 嵌入servlet
- 嵌入jsp
參考博文:http://tengj.top/2017/03/13/springboot5/