新建cors filter文件,
package cn.ac.iscas.pebble.ufe.tools; 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; import org.springframework.stereotype.Component; @Component public class SimpleCORSFilter implements Filter { 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", "x-requested-with"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
然后在web.xml里添加如下内容:
<filter> <filter-name>cors</filter-name> <filter-class>cn.ac.iscas.pebble.ufe.tools.SimpleCORSFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
此为,在代码返回的地方,需要给response添加header,如下:
response.addHeader("Access-Control-Allow-Origin", "*");
至此即可访问:demo如下:
<html> <head> </head> <body height="100%" width="100%"> <table class="bordered" id="devicetable"> <thead> <tr> <th width="20%">check</th> <th width="30%">DeviceID</th> <th width="50%">DeviceName</th> </tr> </thead> <tbody /> </table> <script type="text/javascript"> var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc = xmlhttp.responseXML; y=xmlDoc.getElementsByTagName("deviceid"); x=xmlDoc.getElementsByTagName("devicename"); for(i=0; i<x.length;i++) { var tr1=document.getElementById(‘devicetable‘).insertRow(); var c0=tr1.insertCell(0); var c1=tr1.insertCell(1); var c2=tr1.insertCell(2); c0.innerHTML="<input type=‘checkbox‘ name=‘ck‘/>"; c1.innerHTML=y[i].firstChild.nodeValue; c2.innerHTML=x[i].firstChild.nodeValue; } } } xmlhttp.open("GET","http://localhost:8080/UFE/service/monitorydevice",true); xmlhttp.send(); </script> </body> </html>
时间: 2024-10-09 21:55:58