Springmvc resolving cross-domain requests

Source: Internet
Author: User

1, creating a class

Package com.hzc.util;

Import java.io.IOException;
Import Javax.servlet.FilterChain;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Org.springframework.web.filter.OncePerRequestFilter; public class Crossfilter extends Onceperrequestfilter {@Override protected void dofilterinternal (Httpservletreque St Request, httpservletresponse Response, Filterchain Filterchain) throws Servletexception, Ioexce ption {//if (Request.getheader ("Access-control-request-method")! = NULL &&//"OPTIONS". Equals (R Equest.getmethod ())) {//CORS "pre-flight" Request Response.AddHeader ("Access-control-allow-origin", "*")
        ;
        Response.AddHeader ("Access-control-allow-methods", "GET, POST, PUT, DELETE");
        Response.AddHeader ("Access-control-allow-headers", "Content-type"); Response.AddHeader ("Access-control-max-age", "1800");//min//} filterchain.dofilter (request, response);
 }

}

2. Configure Web. xml

<filter>
    <filter-name>cors</filter-name>
    <filter-class> com.hzc.util.crossfilter</filter-class>
</filter>
<filter-mapping>
    < filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping >

At this point, the option requests access by the Crossfilter filter and gives the cross-domain response header, as well as the Dooption method in the Frameworkservlet. View the browser console, discover that the option request returns support for cross-domain information, and subsequent post requests enter the controller.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.