Spring boot通过过滤器使用CORS实现JavaWeb跨域请求

本文介绍了一种通过配置Spring Boot过滤器解决跨域问题的方法,并提供了一个具体的实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题场景:对于我写好的API接口,h5页面要通过Ajax请求接口获取数据。由于浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面所谓同源是指,域名,协议,端口均相同,就不会被执行,因此存在跨域问题。

解决流程:主要代码如下:

package com.tsingche.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  跨域过滤器
 * Created by Administrator on 2017/3/23.
 */

@WebFilter(filterName="CorsFilter",urlPatterns="/*")
public class CorsFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("*********************************过滤器初始化**************************");
    }

    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", "x-requested-with");
        System.out.println("*********************************过滤器被使用**************************");
        chain.doFilter(req, res);
    }

    public void destroy() {
        System.out.println("*********************************过滤器被销毁**************************");
    }
    


}
package com.tsingche;

import com.tsingche.web.filter.CorsFilter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Administrator on 2017/3/23.
 */
@Configuration//标明这个是SpringBoot的配置类,可以通过类配置代替原有的XML配置方式
@EnableAutoConfiguration //启动bean自动注入
public class StarsFilterConfiguration extends SpringBootServletInitializer {
    /*FilterRegistrationBean 用来配置urlpattern 来确定哪些路径触发filter */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(AuthFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }

    /*使用annotation tag来取代*/
    @Bean()
    public CorsFilter AuthFilter() {
        return new CorsFilter();
    }
}
package com.tsingche.services;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
//@ServletComponentScan//这个就是扫描相应的Servlet包;
@ComponentScan(basePackages = {"com.tsingche"})
public class MejorServicesApplication extends WebMvcConfigurerAdapter {

	public static void main(String[] args) {
		SpringApplication.run(MejorServicesApplication.class, args);
	}
}


前端页面如下

汽车数据读取 <script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
参数名参数值单位
进气歧管压力Kpa
节气门位置%
点火提前角°
发动机负荷%
剩余油量%
车速km/h
转速Rpm
冷却液温度
进气温度
进气流量g/s
故障码

由于对注解不熟悉,filter始终不生效,多番尝试终于开启了,还是要多关注注解背后的原理。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值