Spring Boot筆記02
阿新 • • 發佈:2019-02-20
經過前面的學習,我們已經做到了:
- 在eclipse中能建立一個最簡單的Spring Boot專案
- 能夠新建一個控制器,並且在eclipse中除錯執行
- 能夠把這個做好的HelloWorld程式打包,並且釋出到伺服器上。
在今天的這個教程中,我們要做點更加複雜的事情:
- 響應ajax請求
- 返回json資料
- 跨域問題的解決
1. Hello World
的json版
Spring boot預設使用的是Jackson來處理json資料的。我們先來寫個Hello World的json版。先建立一個空的Spring boot專案,然後:
1.1. 建立pojo類
這裡,我把pojo類單獨放到一個pojo
package com.martin.pojo;
public class Student {
private Integer id;
private String name;
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "[Student Id: " + id +", name: " + name + ", gender: " + gender + "]";
}
}
1.2. 建立Controller類
這裡我們把Controller類放到一個單獨的controller
包下:
package com.martin.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.martin.pojo.Student;
@RestController
public class StudentController {
@RequestMapping("/getStudent")
public Student getStudent() {
Student student = new Student();
student.setId(1);
student.setGender("女");
student.setName("陳好");
return student;
}
}
1.3. 建立執行類
由於我們把controller類單獨放到一個包裡,我們需要給執行類新增一個掃描功能,讓它能掃描到controller
包
package com.martin.smdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@ComponentScan(value = {"com.martin.controller"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
1.4. 使用axios來訪問ajax測試
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
axios.get('http://localhost:8080/getStudent').then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
</script>
</body>
</html>
這裡我們並沒有用jQuery這個庫來處理ajax請求,而是使用了vue.js作者推薦的axios。這個庫更加小,更加可愛。
2. CORS解決方案
如果剛剛的測試程式在不同的域名下,你一定會遇到CORS問題,解決方案如下:
package com.martin.smdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@SpringBootApplication
@RestController
@ComponentScan(value = {"com.martin.controller"})
public class App {
@RequestMapping("/")
@ResponseBody
public String hello() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
3.使用fastjson
3.1. 繼承WebMvcConfigurerAdapter
法
- 啟動類繼承extends WebMvcConfigurerAdapter
- 覆蓋方法configureMessageConverters
public class App extends WebMvcConfigurerAdapter{
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastConverter =
new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}
3.2. 注入Bean: HttpMessageConverters
法
在執行類中,注入:
@Bean
public HttpMessageConverters fConvertersastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter =
new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
測試的頁面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<p>姓名:{{user.name}}</p>
<p>id:{{user.id}}</p>
<p>性別:{{user.gender}}</p>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
user: ''
},
created: function() {
let self = this;
axios.get('http://localhost:8080/getStudent').then(
function(response){
self.user = response.data;
}
).catch(function(error){
console.log(error);
});
}
});
</script>
</body>
</html>