How does Spring Boot solve the cross domain problem of uploading pictures from rich text
- 2021-11-13 07:44:51
- OfStack
Spring Boot Solves Cross-domain Uploading of Rich Text Pictures
When the front end is separated from the front end, the front end browser may have read the data when the interface written in the background is called in the front end, but when the front end code ajax requests, the console printing error of the page across domains will appear in the request callback. At this time, it can be solved only by configuring the header request under the background 1
I use SpringBoot, explain how to configure SpringBoot to solve the cross-domain problem of pages under 1
Create 1 WebMvcConfig class
It is relatively convenient to configure the configuration information about web in the form of annotations
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 Configure
* @author Chenbin
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
private final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);
/**
* Solve the problem of path resource mapping
*
* @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/");
}
/**
* Use fastJson Substitute Jackjson Analyse JSON Data
*
* @return
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
/*
* Convert to JSON String, default :
* WriteNullListAsEmpty List If the field is null, Output is [], Instead of null
* WriteNullStringAsEmpty Character type field if null, The output is "" , Instead of null
* WriteMapNullValue Whether the output value is null Fields of , Default to 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);
}
/**
* This Filter Solve the problem of cross-domain page access
*/
@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 data return needs to introduce Alibaba FastJson, which can be introduced in pom. xml file by yourself
This is not enough, it is necessary
Create an Filter class for cross-domain page processing
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;
// Solve the problem of cross-domain page access
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() {
}
}
After these two classes are configured, restart the service and interact with the front end again, so this cross-domain problem will not occur, because a request header Access-Control-Allow-Origin is added to the Filter class
springboot file upload across domains
Front end
// Cross-domain authentication
axios.defaults.withCredentials = false
axios.defaults.crossDomain = true
Back end
2 classes are copied in
Start Class Add Package Scan
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 Configuration class for the protocol.
* Inheritance WebMvcConfigurerAdapter And overrides the method addCorsMappings .
* addCorsMappings The method is used to increase the Cros Method of protocol configuration. The default implementation is an empty implementation. That is, in the default configuration environment, the Cros Of the configuration of the protocol.
*/
@Configuration
public class CrosConfiguration extends WebMvcConfigurerAdapter {
@Autowired
ProcessInterceptor processInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Add an interceptor ( Of the interceptors, only preHandle Return true Continue to execute when 1 Interceptor or controller Otherwise, return directly )
// registry.addInterceptor(logInterceptor).addPathPatterns("/**");
registry.addInterceptor(processInterceptor).addPathPatterns("/**");
//registry.addInterceptor(csrCheckInterceptor).addPathPatterns("/**");
//registry.addInterceptor(menuAuthInterceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
/**
* Is the process of registration, registration Cors The contents of the agreement.
* Such as: Cors Which requests are supported by the protocol URL Which request types are supported, and what timeout time is for processing at the time of request.
* @param registry - Is used to register Cros Of the content of the agreement 1 A registrar.
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")// All the requested addresses of the current site support cross-domain access.
.allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS") // What types of cross-domain requests are supported by the current site.
.allowCredentials(true) // Support cross-domain user credentials
.allowedHeaders("*")
.allowedOrigins("*") // All external domains are accessible across domains. If it is localhost It is difficult to configure, because when cross-domain requests are made, the resolution of external domains may be localhost , 127.0.0.1 , hostname
.maxAge(3600); // The timeout is set to 1 Hours. The unit of time is seconds.
}
}
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", "*");
// Whether to allow the browser to carry user identity information ( cookie ) , Set to true, You must set a domain name , Wildcard characters cannot be used
// 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 {
}
}