java前后端分离ajax访问跨域问题解决办法

时间:2022-08-28 11:32:08

进行代码设计时候,有时需要前后端进行分类调试,ajax请求会出现跨域问题,具体解决办法如下,仅供参考:

添加一个过滤方法:

package com.lp.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.HttpServletResponse;


public class SessionListener 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", "*");
		chain.doFilter(request, response); 
		
		
	}

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


}
web进行配置:

<filter>
    <filter-name>SessionListener</filter-name>
    <filter-class>com.lp.filter.SessionListener</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>SessionListener</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
这样就能解决ajax跨域问题。