浏览器的同源策略限制了一个源(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请求,其次才会真正请求数据,具体原理查看最后的引用链接。
/**
* http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonp
* spring4.1.0 later
* @author whua
*
*/
@ControllerAdvice
public static class JsonpCallbackAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpCallbackAdvice(){
super("callback");
}
}
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
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/
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 {
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 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);
}
}
/**
* http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonp
* spring4.1.0 later
* @author whua
*
*/
@ControllerAdvice
public static class JsonpCallbackAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpCallbackAdvice(){
super("callback");
}
}
}