Pure html cross-domain access to java interfaces

Keywords: JSON Java

What is cross-domain?

Cross-domain means that html access addresses and interface addresses are in different domains. As long as one of the domain names, protocols, and ports is satisfied, cross-domain means cross-domain.

Why not cross-domain?

Because of security issues, such as when a user visits a bank website, the user's information is in the browser's cookies, and then he visits some shy websites on a whim. The website can get cookies with all kinds of privacy information. If the bank's website supports cross-domain, some unhappy people can do some bad things with the user's information..

But sometimes cross-domain access is required, but now http request headers are disabled by default, so some configuration is required

Method one (interface configuration filter filtering):

    <!--json Cross-domain Configuration-->
    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.base.filter.SimpleCORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>

Corresponding java class

/***
*<p>Functional Description: Cross-domain Resource Sharing Filter </p>
*<ul>
*<li>@param </li>
*<li>@return </li>
*<li>@throws </li>
*<li>@author jackson</li>
*<li>@date 17-9-28 11:19 a.m. </li>
*</ul>
*/
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}

Posted by cshinteractive on Thu, 02 Jul 2020 07:35:54 -0700