Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to set up Access-Control-Allow-Origin to allow multiple domain name access by Java

Shulou Source: shulou.com Published: 2022-05-31 10:51:27 10月01日 Update

This article mainly explains "how Java sets Access-Control-Allow-Origin to allow multi-domain name access". The explanation in this article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn "how Java sets Access-Control-Allow-Origin to allow multi-domain name access".

Projects separated from front and rear ends will inevitably encounter cross-domain problems. There are many things to pay attention to in setting cross-domain issues, such as setting Access-Control-Allow-Origin to allow multiple domain name requests.

(1) the easiest way to allow multi-domain name access is to use wildcards, but this method allows all domain names to be accessible, which is not secure, and browsers cannot carry cookie information (you can only use real domain names with cookie information, as shown in the second method below). This approach is only recommended for testing in development without cookie information. The code is as follows:

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

(2) use array filtering.

@ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse rep = (HttpServletResponse) response; / / set to allow multiple domain name requests String [] allowDomains = {"http://www.toheart.xin","http://192.168.11.213:8080","http://localhost:8080"}; Set allowOrigins = new HashSet (Arrays.asList (allowDomains)); String originHeads = req.getHeader (" Origin ") If (allowOrigins.contains (originHeads)) {/ / configure cross-domain configuration / / enter the host ip that you allow to cross-domain (you can dynamically configure the specific allowed domain name and IP when officially launched) rep.setHeader ("Access-Control-Allow-Origin", originHeads) } Thank you for your reading. the above is the content of "how to configure Access-Control-Allow-Origin to allow multi-domain name access in Java". After the study of this article, I believe you have a deeper understanding of how to set up Access-Control-Allow-Origin in Java to allow multi-domain name access, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Multiple domain names methods domain names information questions learning content configuration security hosts things code dynamic multiple that is ideas situations arrays articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info vpn Docker Shulou Technology OPPO Reno