跨域解决

跨域,前台调用后台接口掉不通,从后台解决跨域问题

1:普通的web项目,写个过滤器

在web项目的web.xml里添加过滤器
<!--     <filter> -->
<!--           <filter-name>cors</filter-name> -->
<!--           <filter-class>com.test.CORSFilter</filter-class> -->
<!--     </filter> -->
<!--     <filter-mapping> -->
<!--           <filter-name>cors</filter-name> -->
<!--           <url-pattern>/*</url-pattern> -->
<!--     </filter-mapping>     -->

 

==================过滤类的写法开始============

package com.test;

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;

public class CORSFilter implements Filter {
      public void doFilter(ServletRequest request, ServletResponse response,
              FilterChain chain) throws IOException, ServletException {
              HttpServletResponse httpServletResponse = (HttpServletResponse) response;
              httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
              httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
              httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
              httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
              chain.doFilter(request, response);
  }
    public void init(FilterConfig filterConfig) {
    }
    public void destroy() {
    }
}

==================过滤类的写法结束============

 

2:springboot项目

springboot需要写一个过滤类,和启动类放在同一目录下

==================过滤类的写法开始============

package com.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(360000);
    }
}

==================过滤类的写法结束============

 

posted @ 2019-02-19 15:56  雪儿蛇王  阅读(119)  评论(0编辑  收藏  举报