Spring Boot笔记02 - 返回json数据

经过前面的学习,我们已经做到了:

  1. 在eclipse中能创建一个最简单的Spring Boot项目
  2. 能够新建一个控制器,并且在eclipse中调试运行
  3. 能够把这个做好的HelloWorld程序打包,并且发布到服务器上。

在今天的这个教程中,我们要做点更加复杂的事情:

  1. 响应ajax请求
  2. 返回json数据
  3. 跨域问题的解决

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

  1. 启动类继承extends WebMvcConfigurerAdapter
  2. 覆盖方法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>

参考

  1. SpringBoot解决ajax跨域问题(转载)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值