簡體   English   中英

在Jersey 1.17中指定JAXB 2上下文

[英]Specifying JAXB 2 context in Jersey 1.17

我在服務器端使用Jersey 1.17來處理REST請求,使用JAXB 2來解組XML請求內容。

上下文

這是我使用的Jersey方法。 MyDTO類使用@XmlRootElement注釋(否則,我需要使用JAXBElement類型定義參數)。

 @Path("/myService")
 @POST
 @Consumes(MediaType.APPLICATION_XML)
 public void myService(MyDTO dto) throws Exception
 {              
    // Shouldn't get this far if the XML content in the request was invalid
    System.out.println(dto);
 }

需求

默認情況下,Sun / Oracle JAXB實現在XML內容出錯時不會拋出異常。 例如,為Integer屬性提供字符串值(例如ABC)只是將值保留為null而不是拋出異常。

在JAXB 2中,可以定義ValidationEvenHandler。 使用以下處理程序處理程序,使XML解組以我需要的方式拋出異常。

public class UnmarshallerValidationEventHandler implements ValidationEventHandler {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            // This indicates JAXB that it should continue processing only if the
            // severity level is less than error. NOTE: validation event constants
            // go in ascending order in level of severity(i.e., 0 WARNING, 1: ERROR, 2 :FATAL_ERROR)
            return event.getSeverity() < ValidationEvent.ERROR;
        }

    }

我怎樣才能讓Jersey使用特定的JAXBContext實例來使用unmarshaller和我的自定義驗證事件處理程序?

或者,鑒於我的應用程序僅在Jersey方法中使用JAXB,因此為JVM實例全局定義特定的JAXBContext將是一個不錯的選擇。 怎么可能這樣呢?

Jersey用戶指南在使用自定義JAXBContext章節中介紹了這一點。 基本上你需要提供ContextResolver <T>,如:

@Provider
public class PlanetJAXBContextProvider implements ContextResolver<JAXBContext> {
    private JAXBContext context = null;

    public JAXBContext getContext(Class<?> type) {
        if(type != Planet.class)
            return null; // we don't support nothing else than Planet

        if(context == null) {
            try {
                context = JAXBContext.newInstance(Planet.class);
            } catch (JAXBException e) {
                // log warning/error; null will be returned which indicates that this
                // provider won't/can't be used.
            }
        }
        return context;
    }
}

您可以在存儲服務示例項目中查看示例用法(請參閱JAXBContextResolver )。

注意:您還可以提供ContextResolver<Marshaller>或/和ContextResolver<Unmarshaller>而不是ContextResolver<JAXBContext> ContextResolver<Unmarshaller>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM