一、首先angularJs实现跨域请求java思路
首先我先介绍一下Html端(前端),然后介绍一下后端java(后端采用MVC模式)。
二、$Http跨域请求方式跨域请求
前端代码:
后端代码,关于
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(); }}