当前位置 主页 > 网站技术 > 代码类 >

    Java服务器端跨域问题解决方案

    栏目:代码类 时间:2020-01-03 18:09

    这篇文章主要介绍了java服务器端跨域问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    现在很多开发的 API 都支持 ajax 直接请求,这样就会导致跨域的问题,解决跨域的问题一方面可以从前端,另一方面就是服务器端。

    一、Controller类名上方添加@CrossOrigin 注解通过此方式注解则Controller中的所有通过@RequestMapping注解的方法都可以进行跨域请求。 代码如下:

    @CrossOrigin()
      @RequestMapping("/demoController")
      @Controller
      public class DemoController {
      @Autowired
      IDemoService demoService;
    
      @RequestMapping(value = "/test", method = RequestMethod.POST)
      @ResponseBody
      public ResultModel test(HttpServletRequest request)
          throws Exception {
        return “right”;
      }
    }

    二、让所有的controller类继承自定义的BaseController类,该类中将对返回的头部做些特殊处理。

    public abstract class BaseController {
     /**
       * description:send the ajax response back to the client side
       * @param responseObj
       * @param response
       */
      protected void writeAjaxJSONResponse(Object responseObj, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
    
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    
        /**
         * for ajax-cross-domain request TODO get the ip address from
         * configration(ajax-cross-domain.properties)
         */
        response.setHeader("Access-Control-Allow-Origin", "*");
    
        response.setDateHeader("Expires", 0); // Proxies.
    
        PrintWriter writer = getWriter(response);
    
        writeAjaxJSONResponse(responseObj, writer);
      }
     /**
       *
       * @param response
       * @return
       */
      protected PrintWriter getWriter(HttpServletResponse response) {
        if(null == response){
          return null;
        }
    
        PrintWriter writer = null;
    
        try {
          writer = response.getWriter();
        } catch (IOException e) {
          logger.error("unknow exception", e);
        }
    
        return writer;
      }
    
      /**
       * description:send the ajax response back to the client side.
       *
       * @param responseObj
       * @param writer
       * @param writer
       */
      protected void writeAjaxJSONResponse(Object responseObj, PrintWriter writer) {
        if (writer == null || responseObj == null) {
          return;
        }
        try {     writer.write(JSON.toJSONString(responseObj,SerializerFeature.DisableCircularReferenceDetect));
        } finally {
          writer.flush();
          writer.close();
        }
      }
    }
    接下来就是我们自己业务的 controller 了,其中主要是要调用 writeAjaxJSONResponse(result, response); 这个方法
    @Controller
    @RequestMapping(value = "/account")
    public class AccountController extends BaseController {
    @RequestMapping(value = "/add", method = RequestMethod.POST)
      public void addAccount(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        ViewerResult result = new ViewerResult();
         //实现自己业务逻辑代码
        writeAjaxJSONResponse(result, response);
      }
    
    }
    好了,这种简单的方式就实现了。