in webapp/WEB-INF/web.xml<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class></filter><filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");
chain.doFilter(req, res);
}
四、
maven-Archetype-wepapp提供两种支持
tomcat7-maven-plugin
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/servletdemo</path>
<port>8082</port>
<server>tomcat</server>
<url>http://localhost:8080/manager/text</url>
<!-- Enable CORS -->
<tomcatWebXml>src/test/resources/tomcat.web.xml</tomcatWebXml>
</configuration>
</plugin>
jetty-maven-plugin
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.2.v20150730</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/servletdemo</contextPath>
<!--Fix file locking problem with jettyrun Enable CORS-->
<defaultsDescriptor>src/test/resources/jetty.web.xml</defaultsDescriptor>
</webApp>
<httpConnector>
<!-- mvn -Djetty.port=8082 jetty:run -->
<port>8082</port>
</httpConnector>
</configuration>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>9.3.2.v20150730</version>
</dependency>
</dependencies>
</plugin>
五、
框架配置
如springmvc支持注解及xml配置