springmvc + vue 设置支持跨域请求

springmvc 添加过滤器

<mvc:interceptor>
   <mvc:mapping path="/**"/>
    <mvc:exclude-mapping path="/commonController.do?**" /> 
    <bean class="org.jeecgframework.core.interceptors.CrossInterceptor"/>
mvc:interceptor>

创建CrossInterceptor类,继承HandlerInterceptor,重写preHandle方法

package org.jeecgframework.core.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CrossInterceptor implements HandlerInterceptor {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");     //* 允许所有域名访问
        response.setHeader("Access-Control-Allow-Methods", "*");    //* 允许所有方法访问
        response.setHeader("Access-Control-Max-Age", "3600");       //预检请求的有效期
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Credentials","true"); //是否允许浏览器携带用户身份信息(cookie)
        return true;
    }
}

配置web.xml文件

不设置 dispatchOptionsRequest 的话post请求还是会出现跨域问题;

<servlet>
	<description>spring mvc servletdescription>
	<servlet-name>springMvcservlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
	<init-param>
		<param-name>dispatchOptionsRequestparam-name>
		<param-value>trueparam-value>
	init-param>
	<load-on-startup>1load-on-startup>
servlet>

配置后,在vue项目中直接访问,不会再出现跨域问题
springmvc + vue 设置支持跨域请求_第1张图片

你可能感兴趣的:(Java,vue,vue.js,servlet,java)