简体   繁体   English

服务器端的跨源请求

[英]Cross Origin requests at server side

Hi I am facing issue in cross origin requests at server side when trying to open file which is retrieved from database using java.I am unaware of this cross orgin requests.When file is clicked then it is giving error as 嗨,当我尝试打开使用Java从数据库中检索的文件时,我在服务器端遇到跨源请求的问题。我不知道此跨源请求。当单击文件时,它给出了错误

jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/JR00432239/Desktop/trial/src/temp/filetest1.docx. jquery.min.js:4 XMLHttpRequest无法加载file:/// C:/Users/JR00432239/Desktop/trial/src/temp/filetest1.docx。 Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. 跨源请求仅支持以下协议方案:http,数据,chrome,chrome扩展名,https。

Can anyone please help me to resolve this issue. 谁能帮我解决这个问题。

Here is my java code: 这是我的Java代码:

package fileretrieve;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import dbConnection.Dbconn;

@MultipartConfig
public class FileRetrieve extends HttpServlet {



    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/plain");

          PrintWriter out = response.getWriter();        
          String onelevel=request.getParameter("onelevel"); 







          Connection conn = null; // connection to the database
          String message = null;
          Statement st = null;// message will be sent back to client



          try {
              // connects to the database
              conn = Dbconn.getConnection();
                st = conn.createStatement();

                 PreparedStatement ps=conn.prepareStatement("select data from files1 where board=?");
                 ps.setString(1,onelevel);                   
                 //out.print("<table width=25% border=1>");
                // out.print("<center><h1>Result:</h1></center>");
                 ResultSet rs=ps.executeQuery();                
                 /* Printing column names */
                 ResultSetMetaData rsmd=rs.getMetaData();
                 int count=0;
                 while(rs.next())
                    {
                     count=count+1;
                     FileOutputStream fos = new FileOutputStream("C:\\Users\\JR00432239\\Desktop\\trial\\src\\temp\\filetest"+count+".docx");
                     fos.write(rs.getBytes(1));
                     fos.close();

//                 out.print("<tr>");
//                 out.print("<td>"+rsmd.getColumnName(1)+"</td>");
//                    out.print("<td><a href=\"file:///C:/Users/JR00432239/Desktop/trial/src/temp/test.pdf\" target=\"_self\">"+count+"</a></td></tr>");
//                    getServletContext().getRequestDispatcher("/home.html").forward(request, response);
                     System.out.println("writing...");
                     response.getWriter().write("{\"name\":\""+count+"\",\"path\":\"C:/Users/JR00432239/Desktop/trial/src/temp/filetest"+count+".docx\"}");



                 }


//                 out.print("</table>");
//                 


          }catch (Exception e2)
            {
                e2.printStackTrace();
            }

          finally{

//            request.setAttribute("data", data);
//            RequestDispatcher rd =request.getRequestDispatcher("userview.jsp");
//            

              out.close();
            }


          // forwards to the message page
        //  getServletContext().getRequestDispatcher("/home.html").forward(request, response);
   }

}   

Here is my html code: Submit 这是我的html代码:提交

Here is my javascript page: 这是我的JavaScript页面:

$("#retrieve").click(function(){

     $.ajax({
            url : 'FileRetrieve',
            method:"POST",
            data : {
                onelevel : $('#onelevel').val()
            },

            crossDomain: true,
            success : function(responseText) {
                var data=JSON.parse(responseText)
                $("#files_data").html('')
                $("#files_data").html('<table><tr><td><button onclick="getFile()">'+data.name+'</button></td></tr></table>')

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); 
            }
        });
     return false;
 });

If you're using chrome, as a simple solution try a chrome extention like Allow-Control-Allow-Origin:* https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog 如果您使用的是chrome,作为一种简单的解决方案,请尝试使用chrome扩展,例如Allow-Control-Allow-Origin:* https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info -对话

if not fixed, run chrome using command line with the flag 如果不固定,请使用带有标志的命令行运行chrome

path/to/chrome.exe --allow-file-access-from-files

or just switch to firefox and check whether the issue is still there 或只是切换到Firefox,然后检查问题是否仍然存在

this would be a quick-fix only in the development 这只是在开发中的快速修复

EDIT 编辑

As far as I know, best thing you can do is make the files available in http server and access them using http protocol. 据我所知,最好的办法是使文件在http服务器中可用,并使用http协议访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM