web.xml配置跨域

Java代码  
  1. REQUEST:  
  2. OPTIONS /resources/l.jsp HTTP/1.1  
  3. Host: localhost:18086  
  4. Connection: keep-alive  
  5. Access-Control-Request-Method: POST  
  6. Origin: http://localhost:8080  
  7. User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36  
  8. Access-Control-Request-Headers: accept, x-requested-with, content-type  
  9. Accept: */*  
  10. Referer: http://localhost:8080/static/product/ProductInput.html?wef11ssss  
  11. Accept-Encoding: gzip,deflate,sdch  
  12. Accept-Language: zh-CN,zh;q=0.8,en;q=0.6  
  13. RESPONSE :  
  14. HTTP/1.1 200 OK  
  15. Date: Thu, 16 Oct 2014 09:44:35 GMT  
  16. Access-Control-Allow-Origin: http://localhost:8080  
  17. Access-Control-Allow-Credentials: true  
  18. Vary: Origin  
  19. Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD  
  20. Access-Control-Allow-Headers: accept, x-requested-with, content-type  
  21. Content-Length: 0  
  22. Server: Jetty(9.3.0.M0)  
 

 

 跨域请求时:浏览器会首先发送一个请求,目标服务返回是否允许访问:

request 会带有:

Java代码  
  1. OPTIONS /resources/l.jsp HTTP/1.1   
  2. Access-Control-Request-Method: POST //请求的参数  
  3. Origin: http://localhost:8080 //请求来源域  
  4. Access-Control-Request-Headers: accept, x-requested-with, content-type //真正请求时  

允许 跨域请求则返回:

Java代码  
  1. Access-Control-Allow-Origin: http://localhost:8080 //允许请求的域来源  
  2. Access-Control-Allow-Credentials: true   
  3. Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD //允许请求的方法  
  4. Access-Control-Allow-Headers: accept, x-requested-with, content-type//允许请求时的header  

浏览器接到返回数据后,才会发送实际请求。 

 

服务器需要能够处理跨域请求,返回对应的header. 

 

cors-filter 是一个Filter ,参够实现服务端的cors功能。

jar包下载地址:http://software.dzhuvinov.com/cors-filter.html

配置:

web.xml:

Java代码  
  1. <filter>  
  2.       <filter-name>CORS</filter-name>  
  3.       <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>  
  4.       <init-param>  
  5.           <param-name>cors.supportedMethods</param-name>  
  6.           <param-value>GET, POST, HEAD, PUT, DELETE</param-value>  
  7.       </init-param>  
  8.       <init-param>  
  9.           <param-name>cors.maxAge</param-name>  
  10.           <param-value>3600</param-value><!--单位秒-->  
  11.       </init-param>  
  12.       <init-param>  
  13.           <param-name>cors.exposedHeaders</param-name>  
  14.           <param-value>Content-Range</param-value><!--允许客户端js访问的header-->  
  15.       </init-param>  
  16.   </filter>  
  17.   <filter-mapping>  
  18.       <filter-name>CORS</filter-name>  
  19.       <url-pattern>/*</url-pattern>  
  20.   </filter-mapping>  

 

详细配置见:http://software.dzhuvinov.com/cors-filter-configuration.html

 

  • java-property-utils-1.9.1.jar (7.7 KB)

  • cors-filter-2.1.2.jar (26.9 KB)

你可能感兴趣的:(java)