Spring Boot 如何解决富文本上传图片跨域问题
作者:如漩涡 发布时间:2021-09-20 06:08:58
标签:SpringBoot,富文本,上传图片,跨域
Spring Boot 解决富文本上传图片跨域
在前后端分离的情况下,后台所写的接口在前端调用的时候,可能前端浏览器已经读取到了数据,但是在前端代码ajax请求的时候,请求回调里会出现页面跨域的控制台打印错误,这个时候只需要后台配置一下头部请求就可以解决
我用的是SpringBoot,讲解一下如何配置SpringBoot来解决页面跨域问题
创建一个WebMvcConfig类
将关于web的配置信息都用注解的形式来配置,相对比较方便
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.uhope.web.codegenerator.filter.ServiceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.nio.charset.Charset;
/**
* Spring MVC 配置
* @author Chenbin
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
private final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);
/**
* 解决路径资源映射问题
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
/**
* 使用fastJson代替Jackjson解析JSON数据
*
* @return
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
/*
* 转换为JSON字符串,默认:
* WriteNullListAsEmpty List字段如果为null,输出为[],而非null
* WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null
* WriteMapNullValue 是否输出值为null的字段,默认为false
*/
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
fastConverter.setDefaultCharset(Charset.forName("UTF-8"));
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
/**
* 这个Filter 解决页面跨域访问问题
*/
@Bean
public FilterRegistrationBean omsFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new ServiceFilter());
registration.addUrlPatterns("/*");
registration.setName("MainFilter");
registration.setAsyncSupported(true);
registration.setOrder(1);
return registration;
}
}
其中JSON数据返回需要引入阿里巴巴FastJson这个依赖,可以自行去pom.xml文件中引入
这样还不够,还需要
创建一个Filter类,做页面跨域的处理
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Chenbin
*/
public class ServiceFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
// 解决页面跨域访问问题
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Credentials", "true");
resp.setHeader("Access-Control-Allow-Methods", "*");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
resp.setHeader("Access-Control-Expose-Headers", "*");
filterChain.doFilter(req, resp);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
这两个类配置好了以后,重启服务,再与前端交互就不会出现这样的跨域问题了,因为在Filter这个类里加了一个请求头Access-Control-Allow-Origin
springboot文件上传跨域
前端
//跨域认证
axios.defaults.withCredentials = false
axios.defaults.crossDomain = true
后端
2个类复制进去
启动类添加包扫描
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Cros协议的配置类。
* 继承WebMvcConfigurerAdapter,并且重写方法addCorsMappings。
* addCorsMappings方法是用于增加Cros协议配置的方法。默认的实现是空实现。也就是说,在默认的配置环境中,是不进行Cros协议的配置的。
*/
@Configuration
public class CrosConfiguration extends WebMvcConfigurerAdapter {
@Autowired
ProcessInterceptor processInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加 * ( * 中只有preHandle返回true时才继续执行下一个 * 或者controller,否则直接返回)
// registry.addInterceptor(logInterceptor).addPathPatterns("/**");
registry.addInterceptor(processInterceptor).addPathPatterns("/**");
//registry.addInterceptor(csrCheckInterceptor).addPathPatterns("/**");
//registry.addInterceptor(menuAuthInterceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
/**
* 就是注册的过程,注册Cors协议的内容。
* 如: Cors协议支持哪些请求URL,支持哪些请求类型,请求时处理的超时时长是什么等。
* @param registry - 就是用于注册Cros协议内容的一个注册器。
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")// 所有的当前站点的请求地址,都支持跨域访问。
.allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS") // 当前站点支持的跨域请求类型是什么。
.allowCredentials(true) // 是否支持跨域用户凭证
.allowedHeaders("*")
.allowedOrigins("*") // 所有的外部域都可跨域访问。 如果是localhost则很难配置,因为在跨域请求的时候,外部域的解析可能是localhost、127.0.0.1、主机名
.maxAge(3600); // 超时时长设置为1小时。 时间单位是秒。
}
}
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author:Administrator
* @date:2019/10/9
*/
@Component
public class ProcessInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
httpServletResponse.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type,Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
String origin = httpServletRequest.getHeader("Origin");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
// 是否允许浏览器携带用户身份信息(cookie),设置为true,必须设置域名,不能使用通配符
// httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
// httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
// httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
// httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
String method = httpServletRequest.getMethod();
if (method.equals("OPTIONS")) {
httpServletResponse.setStatus(200);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
来源:https://blog.csdn.net/m0_37701381/article/details/80388728


猜你喜欢
- pom.xml增加依赖包 <dependency> <groupId>io.springf
- SingleClick:@Retention(AnnotationRetention.RUNTIME)@Target(AnnotationT
- 本文实例讲述了Android下2d物理引擎Box2d用法。分享给大家供大家参考。具体如下:程序运行的时候需要加载Jbox2d的库,可到以下地
- 官方文档 8.0Spring为不同缓存做了一层抽象,这里通过阅读文档以及源码会对使用以及原理做一些学习笔记。1.简介
- 1、下载SpringMVC框架架包,下载地址: 点击下载 点击打开地址如图所示,点击下载即可 然后把相关的jar复制到lib下导
- 概述在使用maven进行Java项目的开发过程中,难免会有些公共的私有库,这些库是不太方便放到中央仓库的,可以通过Nexus搭建一个私有仓库
- 本文实例分析了Android编程之TextView的字符过滤功能。分享给大家供大家参考,具体如下:TextView可以设置接受各式各样的字符
- 从刚接触c#编程到现在,差不多快有一年的时间了。在学习过程中,有很多地方始终似是而非,直到最近才弄明白。本文将先介绍用法,后评断功能。一、委
- 1、获取Class对象在 Java API 中,提供了获取 Class 类对象的三种方法:第一种,使用 Class.forName 静态方法
- 星期天小哼和小哈约在一起玩桌游,他们正在玩一个非常古怪的扑克游戏——“小猫钓鱼”。游戏的规则是这样的:将一副扑克牌平均分成两份,每人拿一份。
- 摘要:这个问题算是老生常谈了,我也是一段时间没弄过了,所以感觉有些忘了,就记录一下。一、后端通过shiro在session中存储数据://
- 本文实例分析了C#反射内存的处理。分享给大家供大家参考。具体分析如下:这段时间由于公司的项目的要求,我利用c#的反射的机制做了一个客户端框架
- 这篇文章主要介绍了如何使用java修改文件所有者及其权限,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- Maven导入thymeleaf依赖飘红1、运行环境操作系统:win10jdk版本:1.8idea版本:2020.1maven版本:3.3.
- 本文实例讲述了Android实现Service重启的方法。分享给大家供大家参考。具体如下:做APP的时候,我们可能需要一个后台服务一直在运行
- 前言前几天多名用户反馈同一个问题,在小新平板上无法上网课,点击上课按钮后就退回到首页了。同事了解了一下发现小新平板现在销量特别好,于是赶紧申
- 本文实例讲述了android中ListView数据刷新时的同步方法。分享给大家供大家参考。具体实现方法如下:public class Mai
- 本文实例为大家分享了javaweb多文件上传及zip打包下载的具体代码,供大家参考,具体内容如下项目中经常会使用到文件上传及下载的功能。本篇
- 上一集中我们说到需要用Java来制作一个知乎爬虫,那么这一次,我们就来研究一下如何使用代码获取到网页的内容。首先,没有HTML和CSS和JS
- 一、引言在许多编程语言中,都有函数回调这一概念。C 和 C++ 中有函数指针,因此可以将函数作为参数传给其它函数,以便过后调用。而在 Jav