Spring MVC + JAXB: ServletException: невозможно найти объект для маршалинга в модели - PullRequest
0 голосов
/ 15 августа 2011

У меня есть веб-сервис, который возвращает список объектов перечислимого типа. Перечисление было аннотировано @XmlRootElement, а также другим типом оболочки, который содержит список этих перечислимых типов объектов плюс еще один строковый член.

@XmlRootElement(name = "indicator")
public enum IndicatorEnum
{
FROST_DAYS,
ICING_DAYS,
MAX_TEMPS_MUCH_ABOVE_AVG,
UNKNOWN;

public static IndicatorEnum fromInt(final int value)
{
    switch (value)
    {
        case 1:
            return FROST_DAYS;
        case 2:
            return ICING_DAYS;
        case 3:
            return MAX_TEMPS_MUCH_ABOVE_AVG;
        default:
            return UNKNOWN;
    }
}

public static IndicatorEnum fromString(final String dataType)
{
    if ("FROST_DAYS".equals(dataType))
    {
        return FROST_DAYS;
    }
    else if ("ICING_DAYS".equals(dataType))
    {
        return ICING_DAYS;
    }
    else if ("MAX_TEMPS_MUCH_ABOVE_AVG".equals(dataType))
    {
        return MAX_TEMPS_MUCH_ABOVE_AVG;
    }
    return UNKNOWN;
}

public String getValueUnits()
{
    switch (this)
    {
        case FROST_DAYS:
            return "days";
        case ICING_DAYS:
            return "days";
        case MAX_TEMPS_MUCH_ABOVE_AVG:
            return "percentages";
        default:
            return "UNKNOWN VALUE UNITS";
    }
}

public String toDisplayString()
{
    switch (this)
    {
        case FROST_DAYS:
            return "Frost Days";
        case ICING_DAYS:
            return "Icing Days";
        case MAX_TEMPS_MUCH_ABOVE_AVG:
            return "Max Temps Much Above Average";
        default:
            return "UNKNOWN";
    }
}

@Override
public String toString()
{
    switch (this)
    {
        case FROST_DAYS:
            return "FROST_DAYS";
        case ICING_DAYS:
            return "ICING_DAYS";
        case MAX_TEMPS_MUCH_ABOVE_AVG:
            return "MAX_TEMPS_MUCH_ABOVE_AVG";
        default:
            return "UNKNOWN";
    }
}
}

@XmlRootElement(name = "available_indicators_for_station")
public class AvailableIndicatorsForStationBean
{

private List<IndicatorEnum> availableIndicators;
private String stationCode;

/**
 * Default, no-arg constructor.
 */
public AvailableIndicatorsForStationBean()
{
}

/**
 * Constructor.
 * 
 * @param stationCode
 * @param availableIndicators
 */
public AvailableIndicatorsForStationBean(final String stationCode,
                                         final List<IndicatorEnum> availableIndicators)
{
    this.stationCode = stationCode;
    this.availableIndicators = availableIndicators;
}

@XmlElement(name = "available_indicators")
public List<IndicatorEnum> getAvailableIndicators()
{
    return availableIndicators;
}

@XmlElement(name = "station_code")
public String getStationCode()
{
    return stationCode;
}

public void setAvailableIndicators(final List<IndicatorEnum> availableIndicators)
{
    this.availableIndicators = availableIndicators;
}

public void setStationCode(final String stationCode)
{
    this.stationCode = stationCode;
}
}

У меня есть класс контроллера, который возвращает модель и вид, например:

@RequestMapping(method = RequestMethod.GET, value = "/available_indicators_for_station_xml")
public ModelAndView getAvailableIndicatorsXml(@RequestParam("station_code") final String stationCode)
{
    // validate the parameters
    if ((stationCode == null) || stationCode.isEmpty())
    {
        throw new RuntimeException("Missing required request parameter: \'station_code\'");
    }

    // find the matching list of Observations entities
    List<IndicatorEnum> availableIndicators = stationDao.findAvailableIndicatorsForStation(stationCode);

    // convert the list of indicators to a JAXB bindable model object
    AvailableIndicatorsForStationBean availableIndicatorsForStationBean = new AvailableIndicatorsForStationBean(stationCode,
                                                                                                                availableIndicators);

    // pass it on as a model and view
    return new ModelAndView(jaxb2MarshallingView, "available_indicators_for_station", availableIndicatorsForStationBean);
}

Когда я делаю запрос к веб-сервису, я получаю сообщение об ошибке с маршалингом JAXB:

javax.servlet.ServletException: Unable to locate object to be marshalled in model: {org.springframework.validation.BindingResult.available_indicators_for_station=org.springframework.validation.BeanPropertyBindingResult: 0 errors, available_indicators_for_station=com.abc.rest.model.AvailableIndicatorsForStationBean@9eb530}
    org.springframework.web.servlet.view.xml.MarshallingView.renderMergedOutputModel(MarshallingView.java:100)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1063)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:801)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Может кто-нибудь посоветовать, что я делаю не так? Заранее спасибо за любые предложения.

1 Ответ

1 голос
/ 20 января 2012

Я столкнулся с этим исключением, javax.servlet.ServletException: невозможно найти объект, который нужно маршалировать в модели, поскольку у объекта, который я поместил в модель, были открытые члены, которые я не хотел сериализовать, но которые я не аннотировал как @ XmlTransient

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...