2

由于现在 web.xml 将动态生成,因此我需要在其顶部添加一个简单的过滤器类,而无需编写或使用插件。我需要什么代码,我应该把它放在哪里?

或者我能否以某种方式获得 grails 将为 web.xml 生成的模板,并且我可以修改和覆盖它?

我在文档中看到

grails.war.resources = { stagingDir, args ->
    copy(file: "grails-app/conf/custom-web.xml",
         tofile: "${stagingDir}/WEB-INF/web.xml")
}

但首先:这个函数会在 application.yml 中起作用吗?

第二:我仍然需要一个合适的 web.xml 模板来改变......

谢谢!

4

3 回答 3

4

根据cfrick的建议,我尝试了这个,(适用于grails 3)

创建一个过滤器,例如 [grails-project]/src/main/java/hello/SimpleCORSFilter.java (创建 'java' 目录,或在 [grails-project/src/main/groovy 目录中创建一个 SimpleCORSFilter.groovy)

您可以使用其中一个弹簧导轨中的示例。

package hello;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
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");
        // I used this instead
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
}

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

然后在 [grails-project]/grails-app/conf/spring/resources.groovy 中,添加过滤器,例如

import hello.SimpleCORSFilter

// Place your Spring DSL code here
beans = {
    myFilter(SimpleCORSFilter)
}

此外,在 grails 文档中,订购您的过滤器:

import hello.SimpleCORSFilter
import org.springframework.boot.context.embedded.FilterRegistrationBean
import org.springframework.core.Ordered

myFilter(FilterRegistrationBean) {
    filter = bean(SimpleCORSFilter)
    urlPatterns = ['/*']
    order = Ordered.HIGHEST_PRECEDENCE
}
于 2015-03-24T08:21:51.973 回答
0

我知道这不是实际问题的答案,但添加过滤器“springboot”样式只是@Bean为它提供了一个。例如,您可以将其放入grails-app/conf/spring/resources.groovy. 更多细节可以在:如何在 Spring Boot 中添加过滤器类?

Grails 3 拥抱 Springboot 并随之告别基于 XML 的配置(不是说它被禁止,而是不鼓励)

于 2015-02-12T12:00:23.527 回答
-3

You can use install-templates command, which will copy templates to src/templates directory, there you will find web.xml template inside war directory, you can customize it

See http://www.grails.org/doc/latest/ref/Command%20Line/install-templates.html

于 2015-02-10T13:43:50.207 回答