欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spingmvc 解决跨域问题

程序员文章站 2022-03-18 20:35:04
前后端联调接口时,会报跨域错误 无法访问接口1.在spingContext.xml文件中添加xmlns:mvc="http://www.springframework.org/schema/mvc"http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd2.com.sense.ivr.controller.LoginHandlerInterc...

前后端联调接口时,会报跨域错误 无法访问接口

1.在spingContext.xml文件中添加

xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

spingmvc 解决跨域问题

2.com.sense.ivr.controller.LoginHandlerInterceptor为拦截类

<!-- 访问拦截  -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.sense.ivr.controller.LoginHandlerInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
package com.sense.ivr.controller;


import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 
 * 类名称:LoginHandlerInterceptor.java 类描述:
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
		response.addHeader("Access-Control-Allow-Headers", "Content-Type");
		response.addHeader("Access-Control-Max-Age", "1800");
		return true;
	}

	public void out (HttpServletResponse httpServletResponse, String response){
		try {
			//httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.setContentType("application/json; charset=utf-8");
			PrintWriter out = httpServletResponse.getWriter();
			out.print(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

本文地址:https://blog.csdn.net/weixin_42152292/article/details/111985567

相关标签: spring mvc java