这篇适用于已分别搭建好Vue和SSM的人群
-
后端SSM添加过滤器代码处理跨域请求(我的是放在src/filter/CorsFilter.java)
package filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import java.io.IOException; public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; // 不使用*,自动适配跨域域名,避免携带Cookie时失效 String origin = request.getHeader("Origin"); if(StringUtils.isNotBlank(origin)) { response.setHeader("Access-Control-Allow-Origin", origin); } // 自适应所有自定义头 String headers = request.getHeader("Access-Control-Request-Headers"); if(StringUtils.isNotBlank(headers)) { response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Expose-Headers", headers); } // 允许跨域的请求方法类型 response.setHeader("Access-Control-Allow-Methods", "*"); // 预检命令(OPTIONS)缓存时间,单位:秒 response.setHeader("Access-Control-Max-Age", "3600"); // 明确许可客户端发送Cookie,不允许删除字段即可 response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
2.后端SSM配置文件中配置过滤器(我的是配在WebContent/WEB-INF/web.xml配置文件中)
filter-class: 是你的CorsFilter.java路径
<!--配置允许跨域访问--> <filter> <filter-name>CorsFilter</filter-name> <filter-class>filter.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3.后端SSM配置前端过滤器(我的是放在WebContent/WEB-INF/web.xml配置文件中)
配置此过滤器作用:让SSM只识别前端发送的xxx.do请求,
相对应的后端控制器中@RequestMapping(xxx.do)需设置成如此
<!-- 配置前端过滤器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value/> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
就解决啦,哦耶!