Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the Cross-domain problem by SpringBoot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to solve cross-domain problems in SpringBoot", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to solve cross-domain problems in SpringBoot" article.

What is cross-domain?

Cross-domain: refers to the fact that browsers cannot execute scripts from other sites. It is caused by the same origin policy of the browser and is the security restriction imposed by the browser on javascript.

For example, if a page wants to obtain b page resources, if the protocols, domain names, ports and sub-domains of an and b pages are different, the access actions are cross-domain, and browsers generally restrict cross-domain access for security reasons, that is, cross-domain requests for resources are not allowed. Note: cross-domain restrictions on access are actually browser restrictions. It's important to understand this!

Homologous policy: it means that the protocol, domain name and port should all be the same, and one of the differences will result in cross-domain.

The way java resolves CORS cross-domain requests

For CORS cross-domain requests, there are mainly the following ways to choose:

Return the new CorsFilter

Rewrite WebMvcConfigurer

Use the annotation @ CrossOrigin

Manually set the response header (HttpServletResponse)

Custom web filter to realize cross-domain

Note:

CorFilter / WebMvConfigurer / @ CrossOrigin requires SpringMVC 4.2 or above, corresponding to springBoot 1.3 or above.

The first two methods above belong to global CORS configuration, and the latter two belong to local CORS configuration. If local cross-domain rules are used, global cross-domain rules will be overridden, so you can use @ CrossOrigin annotation for finer-grained cross-domain resource control.

In fact, no matter which solution, the ultimate goal is to modify the response header, add the data required by the browser to the response header, and then achieve cross-domain.

Returns the new CorsFilter (global cross-domain)

In any configuration class, return a new CorsFIlter Bean and add a mapping path and a specific CORS configuration path.

Configurationpublic class GlobalCorsConfig {@ Bean public CorsFilter corsFilter () {/ / 1. Add CORS configuration information CorsConfiguration config = new CorsConfiguration (); / / release which original domains config.addAllowedOrigin ("*"); / / whether to send Cookie config.setAllowCredentials (true); / / release which request methods config.addAllowedMethod ("*"); / / release which original request header information config.addAllowedHeader ("*") / / which header information is exposed config.addExposedHeader ("*"); / / 2. Add the mapping path UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource (); corsConfigurationSource.registerCorsConfiguration ("/ *", config); / / 3. Return a new CorsFilter return new CorsFilter (corsConfigurationSource);}} rewrite WebMvcConfigurer (global cross-domain)

@ Configurationpublic class CorsConfig implements WebMvcConfigurer {@ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ * *") / / whether to send Cookie .allowCredentials (true) / / which original domains are released .allowedOrigins ("*") .allowedMethods (new String [] {"GET", "POST", "PUT") "DELETE"}) .allowedHeaders ("*") .exposedHeaders ("*") }} use annotations (local cross-domain)

Use the annotation @ CrossOrigin:, on the controller (on the class) to indicate that all methods of the class are allowed to cross domains.

@ RestController@CrossOrigin (origins = "*") public class HelloController {@ RequestMapping ("/ hello") public String hello () {return "hello world";}}

Use the annotation @ CrossOrigin on the method:

@ RequestMapping ("/ hello") @ CrossOrigin (origins = "*") / / @ CrossOrigin (value = "http://localhost:8081") / / specify a specific ip to allow cross-domain public String hello () {return" hello world ";} manually set the response header (locally cross-domain)

Use the HttpServletResponse object to add a response header (Access-Control-Allow-Origin) to authorize the original domain, where the value of Origin can also be set to "*" to indicate full release.

@ RequestMapping ("/ index") public String index (HttpServletResponse response) {response.addHeader ("Access-Allow-Control-Origin", "*"); return "index";} Cross-domain implementation using custom filter

First write a filter that can be named MyCorsFilter.java

Package cn.wideth.aop;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Component;@Componentpublic class MyCorsFilter implements Filter {public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res Response.setHeader ("Access-Control-Allow-Origin", "*"); response.setHeader ("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader ("Access-Control-Max-Age", "3600"); response.setHeader ("Access-Control-Allow-Headers"); chain.doFilter (req, res) } public void init (FilterConfig filterConfig) {} public void destroy () {}} the above is the content of this article on "how to solve cross-domain problems in SpringBoot". I believe everyone has a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report