ssm框架跨域ajax案例,ssm框架解决跨域问题

ssm框架解决跨域问题

一:自定义一个Filter。package com.fyq.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.fyq.utils.ConstantUtils;

// 设置跨域[http升级为https后引起跨域问题]

public class CorsFilter implements Filter {

private boolean isCross = false;

@Override

public void init(FilterConfig filterConfig) throws ServletException {

String isCrossStr = filterConfig.getInitParameter("IsCross");

isCross = isCrossStr.equals("true") ? true : false;

// System.out.println(isCrossStr);

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

if (isCross) {

// HttpServletRequest httpServletRequest = (HttpServletRequest) request;

HttpServletResponse httpServletResponse = (HttpServletResponse) response;

// System.out.println("拦截请求: " + httpServletRequest.getServletPath());

httpServletResponse.setHeader("Access-Control-Allow-Origin", ConstantUtils.CROSS_ORIGIN);

httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

httpServletResponse.setHeader("Access-Control-Max-Age", "0");

httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");

httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); // 设置cookie

httpServletResponse.setHeader("XDomainRequestAllowed", "1");

}

chain.doFilter(request, response);

}

@Override

public void destroy() {

isCross = false;

}

}

二:在web.xml中配置如下

SimpleCORSFilter

com.fyq.filter.CorsFilter

IsCross

true

SimpleCORSFilter

/*

三:在spring-mvc.xml中配置如下。

allowed-origins="*"

allowed-methods="POST, GET, OPTIONS, DELETE, PUT"

allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"

allow-credentials="true" />

注意:

一:有个比较坑的问题,可能你这样设置后还是无法解决跨域问题。如果你的请求是这样写的,那么恭喜你中奖了,还是无法解决跨域问题。@RequestMapping(value="/userlogin", method=RequestMethod.GET)

正确的写法如下:@RequestMapping("/userlogin")

不能指定请求的类型,具体原因我没想太明白。希望能帮忙到各位小伙伴们。

二:这样设置后,解决了跨域问题,但是如果是ajax请求的话,无法从session中获取到值。如登录后将用户的信息放入到session里面,但是你却无法获取到session里面的值,解决办法如下。加上xhrFields:{withCredentials:true},crossDomain:true即可。$.ajax({

type:"post",

xhrFields:{withCredentials:true},

crossDomain:true,

url:"",

data:"",

success: function(data){

}

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值