0

I have written a font file in the response in my code.The response code is working fine.But when i call that code from its url,i get the following error: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at" and it automatically turns off my server.

But sometimes same code works......but maximun time it does not work. I am using tomcat 7 with netbeans 7 and jdk1.6 package Here is the part of my code. Hope i get my ans as i am really confused what to search for.

 File file = new File(SubsettedSavedPath);
byte[] buffer = new byte[(int)file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(buffer, 0, buffer.length);
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,Access-Control-    Allow-Origin,FTPConectionClosed,CopyStreamException,Access-Control-Allow-Methods,Access-Control-Max-Age");
response.setContentType("font/ttf");
System.out.println("File Size"+file.length());


response.setContentLength((int) file.length());
OutputStream os = response.getOutputStream();

try {

os.write(buffer);

os.flush();
} catch (Exception excp) {


excp.printStackTrace();
} finally {
os.close();
fis.close();
}
mahesh
  • 21
  • 1
  • 5

3 Answers3

0

Try to use Access-Control-Allow-Origin with the concrete domain instead of *.

heinob
  • 19,127
  • 5
  • 41
  • 61
0

Use Access-Control-Allow-Origin value equal to requested domain name instead of * .

String uri = request.getScheme() + request.getServerName();

response.setHeader("Access-Control-Allow-Origin", uri);

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
0

Tomcat 7 has an integrate library for setting the cors filter. You do not have to import any library for the following to work:

Just set the allowed 'cors.allowed.origins' websites in web.xml. You can put multiple comma separated values.

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>http://www.the-target-domain.com</param-value>
    </init-param>       
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

In JavaScript I do a GET call to "http://www.the-target-domain.com/...".

By setting the CorsFilter in the web.xml configuration, I assure Firefox that it is ok for the JavaScript to access that site.

There is a great answer by Pere Barceló, that you can set directly in Apache Tomcat http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter

similar uestions: Set CORS header in Tomcat Access-Control-Allow-Origin: * in tomcat

Community
  • 1
  • 1
Andreas Panagiotidis
  • 2,763
  • 35
  • 32