想要实现ajax跨域请求。

我这里使用的filter实现

声明一个过滤器

package com.wyn.moduls.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.wondersgroup.moduls.log.GetRequestAndReponse;


public class AjaxKyFilter  implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpServletResponse =(HttpServletResponse)response;
        // 指定允许其他域名访问 
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 响应类型 
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
        // 响应头设置 
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        
        
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

}

然后将该过滤器注册进web.xml中。

posted on 2018-09-04 20:05  王衙内  阅读(211)  评论(0编辑  收藏  举报