Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> web-service клиент + JSP + ModelAttribute 
V
    Опции темы
Kiti
Дата 28.10.2012, 22:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 13
Регистрация: 29.7.2003

Репутация: нет
Всего: 1



Доброго времени суток!

Описываю суть проблемы:

1) Есть следующий wsdl-файл:
Код

<?xml version="1.0" encoding="UTF-8" standalone="no"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://krams915.blogspot.com/ws/schema/oss" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://krams915.blogspot.com/ws/schema/oss" targetNamespace="http://krams915.blogspot.com/ws/schema/oss">
  <wsdl:types>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://krams915.blogspot.com/ws/schema/oss">
         
    <simpleType name="char2">
        <restriction base="string">
            <maxLength value="2"/>
        </restriction>
    </simpleType>
    
    <simpleType name="char12">
        <restriction base="string">
            <maxLength value="12"/>
        </restriction>
    </simpleType>
    
    <simpleType name="char20">
        <restriction base="string">
            <maxLength value="2"/>
        </restriction>
    </simpleType>
    <simpleType name="date">
        <restriction base="string">
            <maxLength value="10"/>
        </restriction>
    </simpleType>
    
    <complexType name="personName">
        <sequence>
            <element name="id" type="tns:char2"/>
            <element name="name" type="tns:char12"/>
            <element name="surname" type="tns:char20"/>
            <element name="bdate" type="tns:date"/>
        </sequence>
    </complexType>
    
    <complexType name="personAddress">
        <sequence>
            <element name="city" type="tns:char12"/>
            <element name="state" type="tns:char20"/>
        </sequence>
    </complexType>
    
    <complexType name="personResult">
        <sequence>
            <element name="license" type="tns:char2"/>
            <element name="descr" type="tns:char20"/>
        </sequence>
    </complexType>
 
  <element name="personRequest" tns:maxOccurs="1" tns:minOccurs="1">
    <complexType>
        <sequence>
            <element name="personName" type="tns:personName"/>
            <element name="personAddress" type="tns:personAddress"/>
        </sequence>
    </complexType>
  </element>
     
  <element name="personResponse" tns:maxOccurs="1" tns:minOccurs="1">
    <complexType>
        <sequence>
            <element name="person_result" type="tns:personResult"/>
        </sequence>
    </complexType>
  </element>
</schema>
  </wsdl:types>
  <wsdl:message name="personResponse">
    <wsdl:part element="tns:personResponse" name="personResponse">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="personRequest">
    <wsdl:part element="tns:personRequest" name="personRequest">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="personService">
    <wsdl:operation name="person">
      <wsdl:input message="tns:personRequest" name="personRequest">
    </wsdl:input>
      <wsdl:output message="tns:personResponse" name="personResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="personServiceSoap11" type="tns:personService">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="person">
      <soap:operation soapAction=""/>
      <wsdl:input name="personRequest">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="personResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="personServiceService">
    <wsdl:port binding="tns:personServiceSoap11" name="personServiceSoap11">
      <soap:address location="/"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>


2) На основе этого wsdl-файла и используя wsimport были сгенерированы исходные классы для клиента
класс запроса PersonRequest:
Код

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "personName",
    "personAddress"
})
@XmlRootElement(name = "personRequest")
public class PersonRequest {

    @XmlElement(required = true)
    protected PersonName personName;
    @XmlElement(required = true)
    protected PersonAddress personAddress;

    public PersonName getPersonName() {
        return personName;
    }

    public void setPersonName(PersonName value) {
        this.personName = value;
    }

    public PersonAddress getPersonAddress() {
        return personAddress;
    }

    public void setPersonAddress(PersonAddress value) {
        this.personAddress = value;
    }

}


класс PersonName:
Код

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "personName", propOrder = {
    "id",
    "name",
    "surname",
    "bdate"
})
public class PersonName {

    @XmlElement(required = true)
    protected String id;
    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = true)
    protected String surname;
    @XmlElement(required = true)
    protected String bdate;

    public String getId() {
        return id;
    }

    public void setId(String value) {
        this.id = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String value) {
        this.surname = value;
    }

    public String getBdate() {
        return bdate;
    }

    public void setBdate(String value) {
        this.bdate = value;
    }

}

класс PersonAddress аналогичен, ничего экстраординарного.

3) Есть контроллер, который должен обрабатывать входные данные с jsp-страницы:
Код

@Controller
@RequestMapping("/main")
public class MainController {
 
 protected static Logger logger = Logger.getLogger("controller");
  
 @Resource(name="webServiceTemplate")
 private WebServiceTemplate webServiceTemplate;
  
    @RequestMapping(method = RequestMethod.GET)
    public String getAdminPage(Model model) {
     logger.debug("Received request to show subscribe page");
 
     model.addAttribute("subscriptionAttribute", new PersonRequest());

     return "subscribepage";
 }

    @RequestMapping(value = "/subscribe", method = RequestMethod.POST)
    public String doSubscribe(@ModelAttribute("subscriptionAttribute") PersonRequest request,  Model model) {
     logger.debug("Received request to subscribe");

     try {
         PersonResponse response = (PersonResponse) webServiceTemplate.marshalSendAndReceive(request);
         logger.debug(response.getPersonResult().getLicense());
         logger.debug(response.getPersonResult().getDescr());
          
         if (response.getPersonResult().getLicense().equals("SUCCESS") == true) { 
          model.addAttribute("response", "Success! " + response.getPersonResult().getDescr());
         } else {
          model.addAttribute("response", "Failure! " + response.getPersonResult().getDescr());
         }
       
     } catch (SoapFaultClientException sfce) {
      logger.error("We sent an invalid message", sfce);
      model.addAttribute("error", "Validation error! We cannot process your subscription");
       
     } catch (Exception e) {
      logger.error("Unexpected exception", e);
      model.addAttribute("error", "Server error! A unexpected error has occured");
     }
     return "subscribepage";
 }
 
}


4) и сама jsp-страница
Код

<html>
<head>
<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h1>
Subscribe Page</h1>
<p>${response}</p>
<p>${error}</p>
<c:url var="saveUrl" value="/complextype/main/subscribe" />
<form:form modelAttribute="subscriptionAttribute" method="POST" 
action="${saveUrl}">
 <table>
<tr>
   <td><form:label path="id">Id:</form:label></td>
   <td><form:input path="id"/></td>
  </tr>
...
</html>


Вопрос в следующем:

на jsp-странице я ссылаюсь на modelAttribute="subscriptionAttribute", в MainController modelAttribute присваивается объект PersonRequest
и на jsp-странице я имею доступ к полям PersonRequest, но PersonRequest у меня сложного типа (complexType) и его поля являются объектами других классов

Что нужно сделать для того чтобы jsp-страница  "видела" классы PersonName и PersonAddress?

PM MAIL   Вверх
Kiti
  Дата 29.10.2012, 20:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 13
Регистрация: 29.7.2003

Репутация: нет
Всего: 1



Ответ оказался тривиален.
в JSP необходимо вместо:
Код

<td><form:input path="id"/></td>


нужно писать:
Код

<td><form:input path="personName.id"/></td>


т.е. структура следующая: объект.поле
только нужно внимание обращать на то чтобы совпадали регистры!
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java EE (J2EE) и Spring | Следующая тема »


 




[ Время генерации скрипта: 0.0730 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.