浏览器在执行脚本的时候,都会检查这个脚本属于哪个页面,即检查是否同源,只有同源的脚本才会被执行;而非同源的脚本在请求数据的时候,浏览器会报一个异常,提示拒绝访问。
①、http://www.123.com/index.html 调用 http://www.123.com/welcome.jsp 协议、域名、端口号都相同,同源。
②、https://www.123.com/index.html 调用 http://www.123.com/welcome.jsp 协议不同,非同源。
③、http://www.123.com:8080/index.html 调用 http://www.123.com:8081/welcome.jsp 端口不同,非同源。
④、http://www.123.com/index.html 调用 http://www.456.com/welcome.jsp 域名不同,非同源。
⑤、http://localhost:8080/index.html 调用 http://127.0.0.1:8080/welcom.jsp 虽然localhost等同于 127.0.0.1 但是也是非同源的。
同源策略限制的情况:
1、Cookie、LocalStorage 和 IndexDB 无法读取
2、DOM 和 Js对象无法获得
3、AJAX 请求不能发送
注意:对于像 img、iframe、script 等标签的 src 属性是特例,它们是可以访问非同源网站的资源的。
我们创建了两个 web 项目JavaWeb01 和 JavaWeb02 分别部署在tomcat1和Tomcat2上上,这两个 Tomcat 的端口号设置是不一样的,一个是 8080,一个是8081,所以这两个项目构成了非同源。那么我们从客户端(浏览器)输入访问部署在 Tomcat2 上的项目 JavaWeb2,然后在该项目中通过 ajax 去请求部署在 Tomcat1 上的项目数据,能够访问的到呢?
①、在 JavaWeb02 项目中,有一个 jsp 文件,我们通过在浏览器访问该 JSP 文件去获取 JavaWeb01 项目中的数据


1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8" isELIgnored="false"%>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
6 + path;
7 %>
8 <!DOCTYPE html>
9 <head>
10 <title>Title</title>
11 </head>
12 <script type="text/javascript" src="<%=basePath%>/js/jquery-3.3.1.min.js"></script>
13 <script type="text/javascript">
14 $(document).ready(function(){
15 $.ajax({
16 type:"get",
17 async:false,
18 url:"http://localhost:8080/JavaWeb01/getPassWordByUserNameServlet?userName=Tom",
19 dataType:"json",
20 success:function (data) {
21 alert(data['passWord']);
22 },
23 error:function () {
24 alert("error");
25 }
26
27 });
28 })
29
30 </script>
31 <body>
32
33 </body>
34 </html>


1 package com.ys.servlet;
2
3 import com.alibaba.fastjson.JSONObject;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.annotation.WebServlet;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11
12 /**
13 * Create by YSOcean
14 */
15 @WebServlet("/getPassWordByUserNameServlet")
16 public class UserServlet extends HttpServlet{
17 @Override
18 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
19 String userName = req.getParameter("userName");
20 String passWord = null;
21 if(userName != null){
22 passWord = "123";
23 }
24 JSONObject jsonObject = new JSONObject();
25 jsonObject.put("passWord",passWord);
26 resp.getWriter().println(jsonObject.toJSONString());
27 }
28 }
浏览器给我们返回了一个错误,这就是浏览器同源策略导致的跨域访问会报错。那么该如何解决呢?
1 //*表示支持所有网站访问,也可以额外配置相应网站
2 resp.setHeader("Access-Control-Allow-Origin", "*");
1 $.ajax({
2 type:"get",
3 async:false,
4 url:"http://localhost:8080/JavaWeb01/getPassWordByUserNameServlet?userName=Tom",
5 dataType:"jsonp",//数据类型为jsonp
6 jsonp:"backFunction",//服务端用于接收callBack调用的function名的参数
7 success:function (data) {
8 alert(data["passWord"]);
9 },
10 error:function () {
11 alert("error");
12 }
13
14 });
1 @WebServlet("/getPassWordByUserNameServlet")
2 public class UserServlet extends HttpServlet{
3 @Override
4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
5 String userName = req.getParameter("userName");
6 String passWord = null;
7 if(userName != null){
8 passWord = "123";
9 }
10 JSONObject jsonObject = new JSONObject();
11 jsonObject.put("passWord",passWord);
12 //1、第一种方法:*表示支持所有网站访问,也可以额外配置相应网站
13 //resp.setHeader("Access-Control-Allow-Origin", "*");
14
15 //2、第二种方法:jsonp
16 String backFunction = req.getParameter("backFunction");
17 resp.getWriter().println(backFunction+"("+jsonObject.toJSONString()+")");
18
19 //resp.getWriter().println(jsonObject.toJSONString());
20 }
21 }
我们将这段路径单独复制出来:
http://localhost:8080/JavaWeb01/getPassWordByUserNameServlet?userName=Tom&backFunction=jQuery33107285685756141047_1532791502227&_=1532791502228
也就是说对于上面的JSONP 请求,其实jQuery会转化为:
1 <script type="text/javascript"
2 src="http://localhost:8080/JavaWeb01/getPassWordByUserNameServlet?userName=Tom&backFunction=jQuery33107285685756141047_1532791502227&_=1532791502228">
3 </script>
1 $.ajax({
2 type:"get",
3 async:false,
4 url:"http://localhost:8081/JavaWeb02/ToGetPassWordServlet?userName=Tom",
5 dataType:"json",
6 success:function (data) {
7 alert(data['passWord']);
8 },
9 error:function () {
10 alert("error");
11 }
12
13 });
package com.ys.servlet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Create by YSOcean
*/
@WebServlet("/ToGetPassWordServlet")
public class ToGetPassWordServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户名
String userName = req.getParameter("userName");
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建get请求
HttpGet hget = new HttpGet("http://localhost:8080/JavaWeb01/getPassWordByUserNameServlet?userName="+userName);
CloseableHttpResponse httpResponse = httpClient.execute(hget);
int code = httpResponse.getStatusLine().getStatusCode();
if(code == 200){
String result = EntityUtils.toString(httpResponse.getEntity());
resp.getWriter().print(result);
}
httpResponse.close();
httpClient.close();
}
}
利用nginx反向代理,将请求分发到部署到相应项目的tomcat服务器,当然也不存在跨域问题。
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/