无法在Kotlin Web应用程序中实现CORS过滤器

问题描述 投票:0回答:1

我使用以下方法创建了Kotlin Web应用程序:https://kotlinlang.org/docs/tutorials/httpservlets.html

尝试此:

import java.io.IOException
import javax.servlet.*
import javax.servlet.annotation.WebFilter

/**
*
/
@WebFilter(urlPatterns = ["/"])
class SimpleServletFilter(private var filterConfig: FilterConfig) : Filter {

@Throws(ServletException::class)
override fun init(filterConfig: FilterConfig) {
    print("init called..")
    this.filterConfig = filterConfig;
}

@Throws(IOException::class, ServletException::class)
override fun doFilter(
    servletRequest: ServletRequest, servletResponse: ServletResponse,
    filterChain: FilterChain
) {
    val request = servletRequest as HttpServletRequest
    println("CORSFilter HTTP Request: " + request.method)
    (servletResponse as HttpServletResponse).addHeader("Access-Control-Allow-Origin", "*")
    (servletResponse as HttpServletResponse).addHeader(
        "Access-Control-Allow-Methods",
        "GET, OPTIONS, HEAD, PUT, POST"
    )
    val resp = servletResponse as HttpServletResponse
    if (request.method == "OPTIONS") {
        resp.status = HttpServletResponse.SC_ACCEPTED
        return
    }
    filterChain.doFilter(request, servletResponse)
}

override fun destroy() {}
}

但是请求没有通过过滤器。

也尝试过:

import javax.ws.rs.container.ContainerRequestContext
import javax.ws.rs.container.ContainerResponseContext
import javax.ws.rs.container.ContainerResponseFilter
import javax.ws.rs.ext.Provider


@Provider
class CORSFilter : ContainerResponseFilter {
    override fun filter(requestContext: ContainerRequestContext?, responseContext: ContainerResponseContext?) {
        responseContext!!.headers.add("Access-Control-Allow-Origin", "*")
        responseContext.headers.add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
        responseContext.headers.add("Access-Control-Allow-Credentials", "true")
        responseContext.headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
        responseContext.headers.add("Access-Control-Max-Age", "1209600")
    }
}

那里没有运气。请求未通过过滤器。请签出https://kotlinlang.org/docs/tutorials/httpservlets.html这就是我要实现的。

kotlin servlets cors
1个回答
0
投票

如果要将WebFilter应用于所有URL,则应使用通配符:

@WebFilter(urlPatterns = ["/*"])
© www.soinside.com 2019 - 2024. All rights reserved.