本身第一次寫博客,但願把工做中遇到的問題總結一下,和你們一塊兒談論、學習java
如今項目作得是一個定製傢俱的供應鏈管理系統,咱們是先後臺分離的工做模式(前臺angularjs,後臺java-ssm框架),先後臺分離面臨的第一個問題就是跨域問題。jquery
跨域問題通常有兩種常見的解決方式,一是jsonp,二是服務器端配置cors策略,二者相比cors更強大,jsonp只支持get請求,cors支持全部類型的http請求,jsonp的優點在於支持老式瀏覽器,以及能夠向不支持cors的網站請求數據。angularjs
在項目中我採用的是配置cors,具體作法:建立實體類ScmcCors實現Filter接口,代碼以下web
@Component
public class ScmcCors implements Filter{ajax
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}json
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers"," Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);跨域
}瀏覽器
@Override
public void destroy() {
// TODO Auto-generated method stub
}服務器
}cookie
在web.xml文件添加配置
<filter>
<filter-name>cors</filter-name>
<filter-class>com.wishome.controller.ScmcCors</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
好了,到此跨域問題已經解決,但在項目進行的過程當中遇到了新的問題—session丟失,在網上找了很久總算是知道緣由了,原來默認的狀況下,cors作到跨域以後是沒有供應憑證(cookie、HTTP認證及客戶端SSL證明等)。咱們可使用ajax配置項 withCredentials來解決這個問題:
jquery的ajax:
$.ajax({
xhrFields: {
withCredentials: true // 要在這裏設置
},
url: "",
type:"post",
data:set,
dataType:"json",
success:function(data){
},error:function(){
}
});
angularjs咱們能夠在$http這樣配置:
angular.module('myApp').config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}])
配置結束以後,須要更改後臺的ScmcCors實體類:
//修改doFilter方法
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://abc.com");//將*改成請求域的域名,必須加http
response.setHeader("Access-Control-Allow-Credentials", "true");//新增credentials設置
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers"," Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
如今,跨域問題,以及跨域帶來的session丟失問題已經徹底解決,很差的地方還請多多指正!