JavaScript访问远程Servlet的跨域问题
在很久之前就看到过使用JSONP解决JavaScript跨域的问题,但一直不明白怎么使用。今天重新又看了下算是有点了眉目,能够正常的获取远程Servlet的返回数据了。
1. 服务端:
ServiceServlet.java
1 package webservice.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 public class ServiceServlet extends HttpServlet { 11 private static final long serialVersionUID = -1671938285703384549L; 12 13 @Override 14 protected void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 this.doPost(request, response); 17 } 18 19 @Override 20 protected void doPost(HttpServletRequest request, HttpServletResponse response) 21 throws ServletException, IOException { 22 // JSON字符串 23 String json = "{'key1':'val1','key2':'val2','key3':'val3'}"; 24 25 String result = request.getParameter("callback") + "(" + json + ")"; 26 27 response.setContentType("text/javascript"); 28 response.getWriter().print(result); 29 } 30 31 }
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 5 id="WebApp_ID" version="2.5"> 6 <display-name>Webservice Servlet</display-name> 7 8 <servlet> 9 <servlet-name>ServiceServlet</servlet-name> 10 <servlet-class>webservice.servlet.ServiceServlet</servlet-class> 11 </servlet> 12 <servlet-mapping> 13 <servlet-name>ServiceServlet</servlet-name> 14 <url-pattern>/ServiceServlet</url-pattern> 15 </servlet-mapping> 16 </web-app>
2. 客户端:
client.jsp
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 3 <html> 4 <head> 5 <title>Ajax跨域</title> 6 <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script> 7 </head> 8 9 <script type="text/javascript"> 10 var url = "http://localhost:8080/ws/ServiceServlet"; 11 12 $.ajax({ 13 type: "post", // 或者 "get" 14 url: url, 15 dataType: "jsonp", 16 jsonp: "callback", 17 success: function(json) { 18 alert(json.key1); 19 } 20 }); 21 22 $.get(url, {"callback": "?"}, function(json) { 23 alert(json.key2); 24 },"jsonp"); 25 26 $.post(url, {"callback": "?"}, function(json) { 27 alert(json.key3); 28 },"jsonp"); 29 </script> 30 <body> 31 </body> 32 </html>
对于以上内容,如果存在问题请指正。如果有更好的解决方式请分享出来共同学习。