AngularJs跨域请求Java的实现---博客园老牛大讲堂
一、首先angularJs实现跨域请求java思路
首先我先介绍一下Html端(前端),然后介绍一下后端java(后端采用MVC模式)。
二、$Http跨域请求方式跨域请求
前端代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <!--博客园老牛大讲堂--> <script src="../js/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="siteCtrl"> <script> //博客园老牛大讲堂 //总的来说下面的模块是固定的。跨域就按下面写 var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { var k=$http({ method:'post', url: "http://127.0.0.1:8080/A/B", data:{id:"1",name:"老牛大讲堂"}, headers:{'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { console.log(obj);//输出的结果是请求的参数object var str = []; for(var p in obj){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); }, responseType:"text" }); //博客园老牛大讲堂 k.success(function(data){ console.log(data);//请求后的输出数据 console.log(data.firstName);//根据属性得到数据的值 //博客园老牛大讲堂 }); }); </script> </body> </html>
后端代码,关于java的json包装
package Serlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tools.A; public class B extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //http://127.0.0.1:8080/A/B?id=1&name=张三 //这个是访问路径加参数
//博客园老牛大讲堂
//下面加的头部是必须的,这是要求谁可以请求,谁不能请求 response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type"); response.setHeader("Access-Control-Allow-Credentials", "true"); //博客园老牛大讲堂 String id=new String(request.getParameter("id").getBytes("ISO-8859-1"),"GBK"); String name=new String(request.getParameter("name").getBytes("ISO-8859-1"),"GBK"); System.out.println("用户的id是:"+id+"他的名字是:"+name); //博客园老牛大讲堂 String jsoncallback = "{\"firstName\":\"Brett\"}";//模拟一个固定的json数据,将来要用第三方jar包进行包装。 PrintWriter out = response.getWriter(); out.println(jsoncallback); out.flush(); out.close(); } }