美文网首页
Servlet 跨域访问的问题

Servlet 跨域访问的问题

作者: _大风起兮云飞扬_ | 来源:发表于2019-07-18 10:58 被阅读0次

    0、创建Servlet

    使用MyEclipse的New向导直接生成Servlet即可。

    1、访问Servlet返回JSON数据

    写法如下:

        <script type="text/javascript">
            function getAjax() {
                $.ajax({
                    async: false,
                    type: 'post',
                    url: "http://localhost:8080/SdWebservice/servlet/PurchaseDataServlet",
                    data: {"corpId":"04","year":"2018","areaUnit":"10000"},
                    dataType: 'json',
                    success:function(data) {
                        alert(data.rtn + "\r\n" + data.msg);
                    }
                });
             }
        </script>
    

    2、跨域访问

    若要访问其他项目的Servlet,需要解决Servlet跨域访问的问题,访问代码如下:

        <script type="text/javascript">
            function getAjax() {
                var snVal = document.getElementById("sn").value;
                $.ajax({
                    async: false,
                    type: "post",
                    url: "http://www.xxx.com/projname/servlet/GeoGpsServlet",
                    data: {"sn": snVal},
                    //dataType: 'json',
                    dataType: 'jsonp',  // Servlet跨域访问
                    jsonp: 'callback',  // Servlet跨域访问
                    success: function(data) {
                        console.log(data);
                        alert("id=" + data.id + "\r\nsn=" + data.sn + "\r\nlon=" + data.lon + "\r\nlat=" + data.lat);
                    }
                });
             }
        </script>
    

    后台需要对返回的JSON字符串进行简单处理

    public class GeoGpsServlet extends HttpServlet {
        
        ...
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String c = request.getParameter("callback"); ////////// 看这里 //////////
            
            // 得到查询参数
            String sn = request.getParameter("sn");
            
            // 得到5分钟之前的时间
            Date now = new Date();
            long start = now.getTime() - 5 * 60 * 1000;
            Date startTime = new Date(start);
            
            StringBuilder sb = new StringBuilder();
            sb.append("from GeoGps ");
            sb.append("where sn='").append(sn).append("' ");
            sb.append("and createTime>? ");
            sb.append("order by createTime desc ");
            
            String jsonStr = "{}";
            List<GeoGps> list = geoGpsService.getListByHql(sb.toString(), startTime);
            if (null != list && !list.isEmpty()) {
                GeoGps gps = list.get(0);
                Gson gson = new Gson();
                jsonStr = gson.toJson(gps);
            }
            
            //response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(c + "(" + jsonStr + ")"); ////////// 看这里 //////////
            out.flush();
            out.close();
        }
    }
    

    3、跨域访问htts的Servlet

    服务端需要加上

            response.setHeader("Access-Control-Allow-Origin", "*");
    

    4、Struts2拦截器

    Struts2的拦截器会对Servlet进行拦截,原先的web.xml

      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    

    把上面的写法替换如下:

      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
      </filter-mapping>
      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.jsp</url-pattern>
      </filter-mapping>
      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.html</url-pattern>
      </filter-mapping>
      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.htm</url-pattern>
      </filter-mapping>
    

    相关文章

      网友评论

          本文标题:Servlet 跨域访问的问题

          本文链接:https://www.haomeiwen.com/subject/gkvklctx.html