Java Web基础入门,Springboot入门(6)

2019-06-15 00:00:00 java 基础 入门

《Java Web基础入门,Springboot入门(6)》

《Java Web基础入门,Springboot入门(6)》


前言

语言都是相通的,只要搞清楚概念后就可以编写代码了。而概念是需要学习成本的。

本文首发于博客园-Ryan Miao. 由于限制2000字,只能分多篇。


跨域

Cross-origin resource sharing (CORS) is a W3C specification implemented by most browsers that allows you to specify in a flexible way what kind of cross domain requests are authorized, instead of using some less secure and less powerful approaches like IFRAME or JSONP.

CORS是浏览器的一种安全保护,隔离不同域名之间的可见度。比如,不允许把本域名下cookie发送给另一个域名,否则cookie被钓鱼后,黑客就可以模拟本人登陆了。更多细节参考MDN

为什么浏览器要拒绝cors?
摘自[博客园]()

《Java Web基础入门,Springboot入门(6)》

cors执行过程摘自自由的维基百科
《Java Web基础入门,Springboot入门(6)》

首先,本地模拟跨域请求。

我们当前demo的域名为localhost:8081,现在新增一个本地域名, 在HOSTS文件中新增:

127.0.0.1   corshost

然后,访问http://corshost:8081,即本demo。

新增src\main\resources\static\cors.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Cors</title>
</head>
<body>

<script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="http://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

<script>
    $.ajax({ url: "http://localhost:8081/hello", success: function(data){
        console.log(data);
    }});
</script>
</body>
</html>

访问之前创建的hello接口,可以看到访问失败,

Failed to load http://localhost:8081/hello: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://corshost:8081' is therefore not allowed access.

这是浏览器正常的行为。

但,由于前后端分离,甚至分开部署,域名肯定不会是同一个了,那么就需要支持跨域。Springboot支持跨域,解决方案如下:

在需要跨域的method上,添加一个@CrossOrigin注解即可。

@CrossOrigin(origins = {"http://corshost:8081"})
@ResponseBody
@GetMapping("/hello")
public String hello(){
    return "{\"hello\":\"world\"}";
}

如果是全局配置允许跨域,新建com.test.demo.config.CorsConfiguration

package com.test.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by Ryan on 2017/11/18/0018.
 */
@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://domain2.com")
                        .allowedMethods("PUT", "DELETE")
                        .allowedHeaders("header1", "header2", "header3")
                        .exposedHeaders("header1", "header2")
                        .allowCredentials(false).maxAge(3600);
            }
        };
    }
}


部署

刚开始看Springboot的时候看到推荐使用fat jar部署,于是记录下来。后面看到公司的生产环境中既有使用war也有使用jar的,为了方便,非不得已,还是使用jar来部署。

首先,打包:

gradlew clean build

然后,可以看到,在build/libs下有两个jar,springboot-demo-0.1.0.jar.originalspringboot-demo-0.1.0.jar。后面这个就是springboot插件打包好的fat jar,前一个是gradle打包的源jar。接着就可以直接运行这个jar,prod也是如此。

java -jar build/libs/springboot-demo-0.1.0.jar --spring.profiles.active=prod

后面通过参数来指定配置文件的环境,这种命令行参数的优先级要高于配置在base里的,所以会覆盖变量,因此,最终采用的就是prod这个环境配置。

下一篇,引入MySQL。

相关文章