Вызов API-интерфейсов REST из внешнего интерфейса Vuejs с сообщением «Доступ к XMLHttpRequest в ### из источника ### был заблокирован политикой CORS: в запрошенном ресурсе отсутствует заголовок« Access-Control-Allow-Origin ».»Я не могу найти решение, специфичное для Apache-cxf без Spring. Большинство решений для трикотажа или весны.
Я пытался использовать аннотацию @CrossOriginResourceSharing с allowAllOrigins = true. Также попытался установить заголовок с помощью фильтра ContainerResponseFilter с @Provider annotaion
public class MyApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public MyApplication() {
//singletons.add(CorsFilter.class);
singletons.add(new OrderReceiver());
}
@Override
public Set<Class<?>> getClasses() {
return empty;
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
----------------------------------------------------------------------
@Path("/orders")
@CrossOriginResourceSharing(
allowAllOrigins = true,
allowCredentials = true,
maxAge = 1209600 )
public class OrderReceiver {
private Map<Integer, EventItem> eventList = new ConcurrentHashMap<Integer, EventItem>();
private AtomicInteger idCounter = new AtomicInteger();
public OrderReceiver() {
}
// This maps to http post request. Its used to add a new item
// The incoming request is in XML but it is converted to Shopping cart java
// object by JAXB and this method gets the same object. The @Consumes
// annotation
// signifies that the incoming request type is in XML format.
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response addItem(EventItem item) {
item.setId(idCounter.incrementAndGet());
eventList.put(item.getId(), item);
System.out.println("Created Event " + item.getId());
return Response.status(200)
.entity("Event with id " + item.getId() + " created").build();
}
// This maps to http get request. Its used to get an item
// The returning object is marshaled to XML by JAXB.
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_XML)
public EventItem getItem(@PathParam("id") int id) {
EventItem item = eventList.get(id);
if (item == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
System.out.println("Getting Event " + item.getId());
return item;
}
@GET
@Path("/total")
@Produces(MediaType.TEXT_HTML)
public Integer getTotalEvents() {
Integer size = eventList.size();
System.out.println("Total Events: " + size);
return size;
}
// This maps to http put request. Its used to update an item
// XML is deserialized to ShoppingItem object
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response updateItem(EventItem itemToUpdate) {
EventItem currentItem = eventList.get(itemToUpdate.getId());
if (currentItem == null)
throw new WebApplicationException(Response.Status.NOT_FOUND);
System.out.println("Updating Event " + currentItem.getId());
currentItem.setTarget(itemToUpdate.getTarget());
currentItem.setAquirer(itemToUpdate.getAquirer());
currentItem.setAnnounceDate(itemToUpdate.getAnnounceDate());
return Response.status(200)
.entity("Event with id " + currentItem.getId() + " updated")
.build();
}
// This maps to http delete request. It is used to delete an item
// The returning object is serialized to XML
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_XML)
public EventItem deleteItem(@PathParam("id") int id) {
if (!eventList.containsKey(id))
throw new WebApplicationException(Response.Status.NOT_FOUND);
EventItem deletedItem = eventList.remove(id);
System.out.println("Removed Event " + deletedItem.getId());
return deletedItem;
}
}
-----------------------------------------------------------------------
@Provider
public class CorsFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add(
"Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add(
"Access-Control-Allow-Credentials", "false");
responseContext.getHeaders().add(
"Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
responseContext.getHeaders().add(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
---------------------------------------------------------------------------
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.ssrapp.service.MyApplication
</param-value>
</init-param>
<!-- <init-param>
<param-name>javax.ws.rs.container.ContainerResponseFilter</param-name>
<param-value>com.ssrapp.service.CorsFilter</param-value>
</init-param> -->
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>