方式一
package com.xyl.xylshiro.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
res.setHeader("Access-Control-Max-Age", "3600");
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
方式二
package com.funxyl.xyladmin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration config = new CorsConfiguration();
//允许所有域名进行跨域调用
config.addAllowedOrigin("*");
//允许跨越发送cookie
config.setAllowCredentials(true);
//放行全部原始头信息
config.addAllowedHeader("*");
//允许所有请求方法跨域调用
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
注解介绍
- @controller 控制器(注入服务):用于标注控制层,相当于struts中的action层
- @service 服务(注入dao):用于标注服务层,主要用来进行业务的逻辑处理
- @repository(实现dao访问):用于标注数据访问层,也可以说用于标注数据访问组件,即DAO组件
- @component
(把普通pojo实例化到spring容器中,相当于配置文件中的):泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。 - @Configuration可理解为用spring的时候xml里面的标签用于定义配置类
- @Bean可理解为用spring的时候xml里面的标签可被用于AnnotationConfigWebApplicationContext类进行扫描并用于构建bean定义,初始化Spring容器。