angularjs跨域请求

跨域

       浏览器的同源策略限制了一个源(origin)中加载文本或脚本与来自其它源(origin)中资源的交互方式。如果两个页面的协议(protocol)、端口(如果指定)、和主机任一不相同,则他们就不是同源的,在他们之间进行请求则认为是跨域。

如何解决

     跨域的解决方案主要有JSONP、改变domain、CORS等等,因为项目适用于使用CORS,这里只讨论CORS。

服务端处理

response.addHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
response.setHeader("Access-Control-Allow-Headers", "accept,content-type,cache-control,if-modified-since,pragma,x-requested-with");

   Access-Control-Allow-Headers部分可通过chrome调试查看页面发送的信息修改。

   如果是用spring框架的话可继承WebMvcConfigurerAdapter,添加HandlerInterceptor,在自定义HandlerInterceptor里面添加处理即可。

   angularjs会首先发送一个OPTIONS请求,其次才会真正请求数据,具体原理查看最后的引用链接。

spring JSONP支持

 

	/**
	 * <p>http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonp</p>
	 * <p>spring4.1.0 later</p>
	 * @author whua
	 *
	 */
	@ControllerAdvice
	public static class JsonpCallbackAdvice extends AbstractJsonpResponseBodyAdvice {
		 public JsonpCallbackAdvice(){
		       super("callback");
		    }
	}

angularjs处理

   

angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
 
  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
      
    for(name in obj) {
      value = obj[name];
        
      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }
      
    return query.length ? query.substr(0, query.length - 1) : query;
  };
 
  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});

参考

1. http://www.cnblogs.com/y896926473/p/5754287.html

2. http://blog.csdn.net/jiang0946316/article/details/53645396

3.http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/


myTestCase


import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


//
/**
 * 
 * @author wangh
 * 
 */
@Service
@EnableAutoConfiguration
@Configuration
public class ItfMonitor extends WebMvcConfigurerAdapter implements ApplicationListener<ContextRefreshedEvent> {

	public static final Logger log = LogManager.getLogger(ItfMonitor.class);

	@Autowired
	public JdbcTemplate jdbcTemplate;

	@Autowired
	public ExecutorService executorService;

	@Autowired
	public RegHandler regHandler;

	@Bean
	public ExecutorService configPools() {
		return Executors.newFixedThreadPool(10);
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		registry.addInterceptor(regHandler).addPathPatterns("/**");
	}

	public static class SingletonCls{
		private static int obj = -1;
		
		public static int getObj(){
			synchronized (SingletonCls.class) {
				obj += 1;	
			}
			return obj;
		}
	}
	
	@Transactional
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		if(SingletonCls.getObj() > 0 ){
			return;
		}

		try {
			//add flow column
			
		} catch (Exception ex) {
			
			if (log.isInfoEnabled()) {
			}
			
			System.out.println("服务启动完毕!!!");
		}
	}

	@Scope("prototype")
	@Component
	public static class RegHandler implements HandlerInterceptor, Runnable {

		public RegHandler() {

		}

		@Autowired
		public JdbcTemplate jdbcTemplate;

		@Autowired
		public ExecutorService executorService;

		@Autowired
		PlatformTransactionManager transactionManager;

		HandlerMethod hm;
		Map<String, String[]> reqPms;

		public RegHandler(JdbcTemplate jdbcTemplate, ExecutorService executorService) {
			this.jdbcTemplate = jdbcTemplate;
			this.executorService = executorService;
		}

		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
			
		    //添加跨域处理
			response.addHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
			response.setHeader("Access-Control-Allow-Headers", "accept,content-type,cache-control,if-modified-since,pragma,x-requested-with");

			if (handler instanceof HandlerMethod) {

				this.hm = (HandlerMethod) handler;
				this.reqPms = request.getParameterMap();

				executorService.submit(this);
				
				
			}

			log.info(request.getRequestURI());

			return true;
		}

		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

		}

		@Override
		public void run() {

			TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
			try {
				//todo
				transactionManager.commit(status);
				return;
			} catch (Exception e) {
				transactionManager.rollback(status);
				e.printStackTrace();
				return;
			}

		}

	}


	@Transactional
	@RestController
	@RequestMapping("/ItfMonitor")
	public static class ItfRestCtr {
		@Autowired
		public JdbcTemplate jdbcTemplate;

		@RequestMapping("/getItfDetail")
		public Object getItfDetail(String cnname, String enname, String servicename, int hitnum) {
			final String sql = "select * from t_itfmonitor_detail where cnname =? and enname =? and servicename = ? and hitnum=?";
			return jdbcTemplate.queryForList(sql, cnname, enname, servicename, hitnum);

		}
	}
	
	
	/**
	 * <p>http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonp</p>
	 * <p>spring4.1.0 later</p>
	 * @author whua
	 *
	 */
	@ControllerAdvice
	public static class JsonpCallbackAdvice extends AbstractJsonpResponseBodyAdvice {
		 public JsonpCallbackAdvice(){
		       super("callback");
		    }
	}
	

}



  

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值