1. 序列化和反序列化
1. @ResponseBody 和 @RequestBody
雖然總提序列化,但是我們很少深刻體會到,那是因爲在web項目中,方便的註解替我們解決了。
@RestController 的效果 = @Controller + @ResponseBody
@ResponseBody註解在Controller層的某個方法,表示返回給前端的對象要進行序列化。
@RequestBody註解在Controller層的某個方法的參數上,表示這個從前端傳來的json字符串要反序列化爲對象。
2. ObjectMapper類
用readValue方法反序列化, 舉個例子如下。
public class Student{
private String name;
private int age;
// 省略getter 和 setter
}
@Autowired
ObjectMapper objectMapper;
String str = "{"name":"Bob", "age": 24}";
Student student = objectMapper.readValue(str, Student.class);
用writeValueAsString方法序列化,舉個例子如下:
@Autowired
ObjectMapper objectMapper;
Student student = new Student();
student.setName("Bob");
student.setAge(24);
String str = objectMapper.writeValueAsString(student);
3. Jackson 的一些功能註解
@JsonIgnore 註解在屬性上,表示序列化的時候,會將此屬性忽略。
@JsonProperty ("另一個名字")註解在屬性上,表示將該屬性名在序列化的時候,用另一個名字,而不是屬性本名。
@JsonIgnoreProperties({"屬性名1","屬性名2",,,,}) 註解在類上,表示序列化時,忽略掉多個屬性。
@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss", timezone="GMT+8") 註解在時間屬性上,表示時間的序列化格式,和時區,一般我們是北京時間,所以要加個8,才正常。
4. springboot 日期格式、時區的解決
方法1. 在所有類的日期屬性都添加上註解:@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss", timezone="GMT+8")
方法2. 在springboot的配置文件yml中配置即可:
spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
2. 國際化
1. 首先要建立如下文件和目錄,可以看到命名上有關聯,命名分爲基礎名,和擴展名,基礎名可以自定義,但是擴展名就需要從固定的那些裏面選擇,比如本例的基礎名是login,擴展名有en_US,zh_CN等等,分別表示英文、中文。
先創建i18n目錄。
在i18n目錄下面,添加。然後出現如下窗口,填寫基礎名,“+”號代表添加擴展名,這樣重複三次,創建三個properties文件:
properties文件的內容就是翻譯:
login 和 login_zh_CN
title=用戶登陸
user.welcome=歡迎
user.username=登陸用戶
user.password=登陸密碼
user.login=登陸
login_en_US
title=User Login
user.welcome=Welcome
user.username=Username
user.password=Password
user.login=Sign In
然後在application.yml文件裏配置國際化:
spring:
messages:
basename: classpath:/i18n/login #表示路徑下面文件名以login開頭的文件,同時login.properties爲默認文件,可以配置多個,用逗號隔開
fallback-to-system-locale: true #就會找服務器的語言環境對應的配置文件。如果spring.messages.fallback-to-system-locale=false,就找login.properties這個默認的配置文件。
然後再配置一個默認解析器(默認按照哪種語言),默認攔截器(按照url中的參數來決定使用什麼語言):
@Configuration
public class InternationalizationConfiguration extends WebMvcConfigurerAdapter {
/**
* 默認解析器 其中locale表示默認語言
*/
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.CHINA);
return localeResolver;
}
/**
* 默認攔截器 其中lang表示切換語言的參數名 ?lang=en_CN,其實感覺就是配置文件裏的basename + lang 構成語言properties文件名,然後讀取文件裏的語言
*/
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor);
}
};
}
}
再寫一個工具類,用於獲取語言的翻譯:
@Component
public class InternationalizationUtils {
@Autowired
private static MessageSource messageSource;
/**
* 獲取單個國際化翻譯值
*/
public static String get(String msgKey) {
try {
return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
} catch (Exception e) {
return msgKey;
}
}
}
最後測試: String str = InternationalizationUtils.get("title");
3. Thymeleaf 模板
1.首先添加maven依賴:
<!--thymeleaf 模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
順便說明一下,我在測試的時候,高版本的thymeleaf無法下載,只能用2.1.0版本的。
2. 在application.yml配置(總之在你的配置文件裏配置):
spring:
#-------------------------------------------------------------
thymeleaf:
prefix: classpath:/templates/ #Controller層返回給用戶的時候,去哪個目錄下找頁面呢,就是這個目錄(默認)
suffix: .html #後綴的意思(默認),Controller層不用return xx.html,而是 return xx,就會自動到templates目錄下去找xx.html文件去了
mode: HTML5 #模式是H5(默認)
encoding: UTF-8 #編碼格式( 默認)
cache: false #關閉緩存,默認是false
mvc:
static-path-pattern: /static/** #這個是給mvc設置靜態路徑,以便mvc在查找靜態資源時,就去這個路徑找。
3.測試一下,可以直接僅返回視圖頁面,也可以返回模型與視圖,體驗一下:
@RestController
public class UserController {
@RequestMapping("login")
public String getLoginPage(){
return "index";
}
@RequestMapping("error404")
public ModelAndView get404(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("username", "Alice");
modelAndView.setViewName("error/404");
// return "error/404";
return modelAndView;
}
}
4. 錯誤頁面
其實使用springboot最大的好處就是默認自帶了很多配置,不至於讓開發者去配置,那麼要使用這些默認的配置,就需要遵守springboot的一些規則,比如項目的目錄結構,如下:
當我們web客戶端發起一個無法mapping的url請求時,自然就會拋出404的異常,那麼返回給客戶端什麼響應呢,如果使用了模板引擎,就會自動到靜態資源下的templates目錄下的error目錄下查找是否有404.html(若沒有,則找4xx.html),然後返回給用戶,如果沒有使用引擎,則在靜態資源裏直接找。