经过前面的学习,我们已经做到了:
- 在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>