跨域请求页面跳转

1.jsp->java(编码)->java

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>

</head>
<body>
<a onclick="testWbAPI()">share</a>

<script>
    function testWbAPI(){
        //var url = "http://127.0.0.1:6080/helloworld/receiveWBAPI?userId=111&content="+encodeURI("我哦我我");
        var url = "/myweb/ShareWBAPI?userId=111&content="+encodeURI("我哦我我");
        window.open(url);

        /*$.ajax({
               type: "POST",
               //url: "/myweb/ShareWBAPI",
               url:"http://127.0.0.1:6080/helloworld/receiveWBAPI",
               data: "userId=11111",
               success: function(msg){
                 alert( "Data Saved: " + msg );
               },
               error:function(x,a,s){
                   alert(x+a+s)
               }
            }); */
    }
</script>
</body>
</html>
package bookstore;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;

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 org.apache.commons.httpclient.*;

import org.apache.commons.httpclient.methods.PostMethod;

/**
 * Servlet implementation class ShareWBAPI
 */
@WebServlet("/ShareWBAPI")
public class ShareWBAPI extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShareWBAPI() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String POST_URL="http://127.0.0.1:6080/helloworld/receiveWBAPI"; 

        response.sendRedirect(POST_URL+"?userId=111&content="+URLEncoder.encode(new String(request.getParameter("content").getBytes("iso-8859-1"),"utf-8"), "gbk"));
    }

}
package test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class receiveWBAPI
 */
public class receiveWBAPI extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public receiveWBAPI() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/shareWbAPI.jsp").forward(request, response);
    }

}
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body >
<a onclick="showPara()">share</a>
<div>userId<%=request.getParameter("userId") %></div>
<div>content<%=new String(request.getParameter("content").getBytes("iso-8859-1"),"gbk") %></div>
</body>
</html>

2.jsp->Ajava->Bjava(sendRedirect,实际未跳转)->Ajava(跳转)

Ajava

package bookstore;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;

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 org.apache.commons.httpclient.*;

import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * Servlet implementation class ShareWBAPI
 */
@WebServlet("/ShareWBAPI")
public class ShareWBAPI extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShareWBAPI() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String POST_URL="http://127.0.0.1:6080/helloworld/receiveWBAPI";
//        URL postUrl = new URL(POST_URL);
//           HttpURLConnection connection = (HttpURLConnection) postUrl
//                   .openConnection();
//           connection.setDoOutput(true);
//           connection.setDoInput(true);
//           connection.setRequestMethod("POST");
//           connection.setUseCaches(false);
//           connection.setInstanceFollowRedirects(true);
//           connection.setRequestProperty("Content-Type",
//                   "application/x-www-form-urlencoded");
//
//           connection.setRequestProperty(key, value)
//           /**//*
//            * 与readContentFromPost()最大的不同,设置了块大小为5字节
//            */
//           connection.setChunkedStreamingMode(5);
//           connection.connect();
//
//           /**//*
//            * 注意,下面的getOutputStream函数工作方式于在readContentFromPost()里面的不同
//            * 在readContentFromPost()里面该函数仍在准备http request,没有向服务器发送任何数据
//            * 而在这里由于设置了ChunkedStreamingMode,getOutputStream函数会根据connect之前的配置
//            * 生成http request头,先发送到服务器。
//            */
//           DataOutputStream out = new DataOutputStream(connection
//                   .getOutputStream());
//           String content = "userId=11111&content=" + URLEncoder.encode("一个大肥人", "utf-8");
//           out.writeBytes(content);
//
//           out.flush();
//           out.close();

        PostMethod postMethod = new PostMethod(POST_URL);
        postMethod.addParameter("userId","1111");
        postMethod.addParameter("content","主题");   

        HttpClient client = new HttpClient();
        client.setConnectionTimeout(1000 * 60);
        int status=0;
        try {
        status = client.executeMethod(postMethod);
        } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        if(status==HttpStatus.SC_OK) {   

        } else {
        }
        postMethod.releaseConnection();   

         //因为Bjava,redirect所以返回302,
        if ((status == HttpStatus.SC_MOVED_TEMPORARILY) ||(status == HttpStatus.SC_MOVED_PERMANENTLY) ||(status == HttpStatus.SC_SEE_OTHER) || (status == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            //读取新的URL地址
            Header header = postMethod.getResponseHeader("location");
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals("")))
                    newuri ="/";
                    GetMethod redirect = new GetMethod(newuri);
                    client.executeMethod(redirect);
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+newuri); //跳转页面效果
                    System.out.println("Redirect:"+ redirect.getStatusLine().toString());
                    redirect.releaseConnection();             }
            else                 System.out.println("Invalid redirect");         }
        }

    }

Bjava

package test;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class receiveWBAPI
 */
public class receiveWBAPI extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public receiveWBAPI() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.sendRedirect("/helloworld/shareWbAPI.jsp"+"?userId"+request.getParameter("userId")+"&content="+URLEncoder.encode(new String(request.getParameter("content").getBytes("iso-8859-1"),"gbk"),"gbk"));

    }

}
时间: 2024-10-09 19:24:52

跨域请求页面跳转的相关文章

js跨域请求页面的时候如果不做处理会报错

当执行ajax请求的时候, 如果url域名和服务器域名不一致,在执行请求时就会报跨域的bug,解决办法很简单,如下 $.ajax({ type: "GET", url: "", dataType: 'jsonp', success:function(data){ 加上dataType:'jsonp'这一行就可以了:

【转】同源策略和跨域请求解决方案

一.一个源的定义 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源.举个例子: 下表给出了相对http://a.xyz.com/dir/page.html同源检测的示例: URL 结果 原因 http://a.xyz.com/dir2/other.html 成功 协议,端口(如果有指定)和域名都相同 http://a.xyz.com/dir/inner/another.html 成功 协议,端口(如果有指定)和域名都相同 https://a.xyz.com/secure

对同源策略与多页面通讯、跨域请求的深入探索

为了网页的安全,现在主要的浏览器都遵循了同源策略.同源策略究竟有哪些规范?怎么体现安全作用?个人总结同源策略的一个首要宗旨是: 阻止能向外传输信息的模块(如javascript)获取到来自不同源的资源,不能获取也就从源头阻止了资源和其中信息的泄露. 很重要的一点是,同源策略阻止的是跨域资源的获取,而不是阻止跨域的请求,请求可以正常发出,但返回的内容被阻止,无法让JS脚本获取 针对javascript,且看几个直观的现象:1.一个页面的javascript能获取到其他页面的window.但在非同源

Nginx服务器中处理AJAX跨域请求的配置方法讲解

Nginx 实现AJAX跨域请求AJAX从一个域请求另一个域会有跨域的问题.那么如何在nginx上实现ajax跨域请求呢?要在nginx上启用跨域请求,需要添加add_header Access-Control*指令.如下所示: ? 1 2 3 4 5 6 7 8 9 10 11 12 location /{ add_header 'Access-Control-Allow-Origin' 'http://other.subdomain.com'; add_header 'Access-Cont

[转]Ajax跨域请求

一.编一个服务器端servlet @RequestMapping("/haha") @ResponseBody String haha(String haha, HttpServletRequest req, HttpServletResponse resp) { //resp.addHeader("Access-Control-Allow-Origin", "null"); System.out.println(haha); System.ou

Django之跨域请求同源策略

同源策略: 首先基于安全的原因,浏览器是存在同源策略这个机制的,同源策略阻止从一个源加载的文档或脚本获取或设置另一个源加载的文档的属性. 而如果我们要跳过这个策略,也就是说非要跨域请求,那么就需要通过JSONP或者CORS来实现了. 一个源的定义 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源. 举个例子: 下表给出了相对http://a.xyz.com/dir/page.html同源检测的示例: URL 结果 原因 http://a.xyz.com/dir2/oth

springboot shiro 前后端分离,解决跨域、过虑options请求、shiro管理session问题、模拟跨域请求

一.解决跨域.过虑options请求问题 1.创建过虑类 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; im

JSonP跨域请求

我们在通过自己的页面或程序通过ajax请求其它网站或服务时,会存在一个ajax直接请求普通文件存在跨域无权限访问的问题,甭管你是静态页面.动态网页.web服务.WCF,只要是跨域请求,一律不准.不过我们又发现,Web页面上调用js文件时则不受是否跨域的影响(不仅如此,我们还发现凡是拥有"src"这个属性的标签都拥有跨域的能力,比如<script>.<img>.<iframe>).   于是可以判断,当前阶段如果想通过纯web端(ActiveX控件.服

跨域请求资源的几种方式

跨域请求资源的几种方式 由于浏览器同源策略,凡是发送请求URL的协议.域名.端口三者之间任意一与当前页面地址不同即为跨域. (1)JSONP(jsonp跨域get请求) 这种方式主要是通过动态创建一个script标签,浏览器对script的资源引用没有同源限制,同时资源加载到页面后会立即执行:(创建script标签向不同域提交http请求的不会被拒绝的方法,jsonp标签的src属性是没有跨域限制的) 实际项目中JSONP通常用来获取json格式数据,这时前后端通常约定一个参数callback,