2011-12-19 2 views
0

Я использую TypeBinder с ключевым словом @As в своем действии контроллера. И независимо от того, что я делаю, метод связывания никогда не называется.Пользовательский Binder не работает в PlayFramework

Что определяет связующее, которое используется?

Я также включил мой журнал для ВСЕХ, и я понял, что Binder.bindInternal никогда не называется.

вот мой связующий

public class EmailTypeBinder implements TypeBinder<Email> { 

    @Override 
    public Email bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception { 
     System.out.println("Inside email type binder"); 
     return new Gson().fromJson(value, Email.class);  
    } 

} 

Вот действия контроллера

public static void send(@As(binder=EmailTypeBinder.class) Email email) { 
     try { 
     for(String key1:DataParser.parsers.keySet()) { 
      System.out.println("Key: " + key1 + " value: " + DataParser.parsers.get(key1).getClass().getName()); 
     } 

     for(String key : params.all().keySet()) { 
      System.out.println("Key: " + key + " value: " + params.get(key)); 
     } 

     System.out.println("ContentType: " + request.contentType); 
     if(request.body == null) { 
      System.out.println("request.body is null"); 
     } 

     System.out.println("Available bytes: " + request.body.available()); 

     InputStreamReader reader = new InputStreamReader(request.body); 
     String str; 

     BufferedReader br = new BufferedReader(reader); 
     while ((str = br.readLine()) != null) { 
      System.out.println("You entered String : " + str); 
     } 

     if(email == null) { 
      System.out.println("email is null"); 
     } else { 
      System.out.println(email.getMessage()); 
     } 

    }catch(Exception e) { 
     e.printStackTrace(); 
    } 

Вот ответ от вызова контроллеру

Key: application/xml value: play.data.parsing.TextParser 
Key: multipart/form-data value: play.data.parsing.ApacheMultipartParser 
Key: application/json value: play.data.parsing.TextParser 
Key: application/x-www-form-urlencoded value: play.data.parsing.UrlEncodedParser 
Key: body value: {email:{"from":"","subject":"Test Posted Subject","message":"This is my POSTED message","groups":[],"groupLists":["COS"]}} 
ContentType: application/json 
Available bytes: 0 
email is null 

В моих маршрутов я имею

POST /send         Application.send 

Клиент на самом деле Groovy, но это не имеет значения, потому что я также пытался сделать его моделью, просто обычным объектом в этом проекте. В любом случае вы можете думать о

public static void post(Email email) { 

    def http = new HTTPBuilder('http://localhost:9000') 

    // perform a GET request, expecting JSON response data 
    http.request(POST, ContentType.JSON) { req -> 
     uri.path = '/send' 

     body = "{email:" + new Gson().toJson(email) + "}"; 


     // response handler for a success response code: 
     response.success = { resp, json -> 
      println "status: ${resp.statusLine}" 

      // parse the JSON response object: 
      println " ${json}" 
     } 

     // handler for any failure status code: 
     response.failure = { resp -> 
     println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}" 
     } 
    } 
} 

вот мой класс Email, но я не уверен, что его отношение

class Email implements Serializable { 

// factory methods 
public static Email createSimple(String subject, String message) { 
    return new Email("", subject, message); 
} 
public static Email create(String from, String subject, String message) { 
    return new Email(from, subject, message);  
} 

public static Email createWithTemplate(String from, String subject, String message, String template) { 
    Email email = new Email(from, subject, message); 
    email.setTemplate(template); 
    return email; 
} 


public String getFrom() { 
    return from;   
} 

public String getSubject() { 
    return subject; 
} 

public String getMessage() { 
    return message; 
} 

public Set<String> getGroupLists() { 
    return groupLists; 
} 

public Set<String> getGroups() { 
    return groups; 
} 

public void addGroupList(String groupList) { 
    groupLists.add(groupList); 
} 
public void addGroup(String group) { 
    groups.add(group); 
} 

private void setTemplate(String template) { 
    this.template = template; 
} 

// we must use the factory methods to create us 
private Email(String from, String subject, String message){ 
    this.from = from; 
    this.subject = subject; 
    this.message = message; 
} 

// only used for Gson JSON serialization/deserialization 
public Email(){} 

private String from; 
private String subject; 
private String message; 
private String template; 
private Set<String> groups = new HashSet<String>(); 
private Set<String> groupLists = new HashSet<String>(); 

}

Единственный способ, которым я могу получить этот рабочий использует ApiPlugin от Пример главы 4 в Поваренной книге Play Framework Я могу использовать это, но структура говорит, что она должна иметь возможность обрабатывать ее просто путем определения TypeBinder, но это не так.

ответ

0

Кажется, что вы передаете свой объект электронной почты как объект json, но связующие работают с параметрами формы. Попробуйте указать свой объект в качестве параметра формы или использовать gson в игре для десериализации объекта

Смежные вопросы