So let's take a look at the code at this new method, greetByPeriod to
application. So, here I'm in Hello world
and poin.java, I've defined my new function greetByPeriod.
Still got the name argument, and it's
got a named period argument, period. And just
for variety, although the name is @Named
period. I'm calling the argument time of day,
just to show that whatever the @Named is what is required to be specified
in the request. And I'm all doing here is returning new HelloClass name, time of
day. HelloClass class, didn't actually have this
constructor, so I added it, it's pretty
simple. Here's the new construction HelloClass. Pass
the name, the period, construct a new message,
good, this would be morning, let's say, good morning
Lauren. Good morning Lauren. Okay, so let's see if it
works. I'm going to run it on the dev
server, save my changes, it's always a good thing to
do. Mkay, let's go over to the local host
in the browser. And I'm going to go straight to
the API's explorer. Oh goodness, got an error, that
never happens. Failed to retrieve API configs with status: 500.
All right, first instinct panic, second instinct go
back and check the code. And you see I
got the error showing up here too, Failed
to retrieve API configs. That means there is something
wrong with my end point function. Let's look
at hello world end points greetByPeriod all looks good,
what's the problem? Aha, it's a copy and
paste error. See here, I copy and pasted this
from the previous method sayHelloByName. And I
forgot to update the function name. So I'll
just fix that real quick. You can't have
two functions exposed with the same name. Actually
greet by period. Save it. And actually when you make changes in the Java code
and you save it. You'll usually find that
the changes get automatically propagated out to localhost.
See it says, reloading the web application, a
file has changed. So I don't need to
run it again. I'll just go straight to
local host, reload the APIs Explorer. Okay good.
This time it worked. Now drill down into my API. Here's my new one, greet by
period. Enter a name. And it's the afternoon
now. And then let's look at the response.
There it is. Good afternoon. And then Good afternoon Buttercup, because
Buttercup's the name I gave. So one other thing to look at is the code for
index.html and hello.js. Take a quick look
at those, index.html. Really what we had to do was add the,
the new imput field for period is called Period_Field and
the new button for the greeting and in Hello.js.
And enable buttons that we needed to enable to
function for the new button. Here's the new button,
input greetByPeriod. We're going to call the function greetByPeriod. We're going
to update the button label. Now we have to
define greet by period and here it is, it's
very similar to greet by name. But we get
the name field, we get the value of the name
out of the HTML, we get the period
out of the period field element. You construct
the request. And here we're calling the greetByPeriod
function. And then we're specifying the argument. The
arguments are name and period. Now because we've
called the period, we've named the period argument,
at period. This must exactly match. And then
we execute it and we call the sayHelloCallBack
as before. And again, it throws up an alert dialog box showing
us the message in the response. So, that's all there is to it.
Veamos el código de este nuevo método
greetByPeriod de la aplicación.
Aquí estoy en el endpoint
de HelloWorld java,
he definido
mi nueva función greetByPeriod.
Toma al argumento nombre,
y toma un argumento nominado periodo.
Y solo para variar,
aunque el nombre sea @Named periodo,
llamo al argumento
time of day (hora del día),
solo para mostrar
que lo que está en @Named
es lo que se requiere especificar
en la solicitud.
Y todo lo que hago aquí es retornar
new HelloClass de nombre y hora del día.
La clase HelloClass,
en realidad no tenía este constructor
así que lo agregué, es bastante simple.
Aquí está el nuevo constructor
de HelloClass.
Se le pasa el nombre, el período,
construye un nuevo mensaje,
bueno, esto sería por la mañana,
digamos buenos días Lauren.
Buenos días Lauren. De acuerdo,
veamos si funciona.
Voy a ejecutarlo
en el servidor del dispositivo
guardo mis cambios,
siempre es algo que es bueno hacer .
Bien, vamos al host local
en el navegador
Y voy a ir directamente
al explorador de API.
Oh vaya, apareció un error
que nunca ocurre.
No se pudo recuperar
configuraciones de API con el estado: 500
Bueno, primer instinto pánico,
segundo instinto
vayamos a revisar el código.
Y como ven el error también aparece aquí,
No se pudo recuperar
configuraciones de API.
Eso significa que hay algo erróneo
en la función de endpoint.
Echemos un vistazo
a los endpoints de HelloWorld,
greetByPeriod, todo se ve bien,
¿cuál es el problema?
Ajá, es un error de copiado y pegado
Vean aquí, un copiado y pegado
del método anterior sayHelloByName.
Y olvidé actualizar
el nombre de la función.
Lo arreglaré rápidamente.
No se puede tener dos funciones
expuestas con el mismo nombre.
En realidad es greetByPeriod.
Lo guardamos.
Cuando se realizan cambios
en el código de Java
y se guardan, encontraremos que
que los cambios se propagan
automáticamente al localhost.
Vean que dice,
"volviendo a cargar la aplicación web,
un archivo ha cambiado".
Así que no necesito ejecutarlo de nuevo.
Me limitaré a ir
directamente al host local,
vuelvo a cargar el Explorador de APIs.
Muy bien, esta vez funcionó.
Ahora despliego mi API.
Aquí está mi nuevo greetByPeriod.
Introduzco un nombre. Y es por la tarde
Luego observemos la respuesta.
Ahí está. Buenas tardes.
Y luego Buenas tardes Buttercup,
porque Buttercup es el nombre que di.
Otra cosa a tener en cuenta
es el código para index.html y hello.js.
Echemos un rápido vistazo, index.html.
Realmente lo que hicimos fue añadir
la nueva entrada para el campo periodo,
la nueva entrada para el campo periodo
se llama period_field
y el nuevo botón para el nuevo saludo.
Y en Hello.js, en enableButtons
necesitamos habilitar
la función para el nuevo botón.
Aquí está el nuevo botón,
input greet by period.
Vamos a llamar a la función greetByPeriod.
Vamos a actualizar la etiqueta del botón.
Ahora tenemos que definir greetByPeriod.
Y aquí está, es muy similar a greetByName.
Pero tenemos el campo nombre,
obtenemos el valor del nombre
del HTML, obtenemos el período
del elemento de campo período.
Construimos el request.
Aquí llamamos a la función greetByPeriod.
Y luego especificamos los argumentos.
Los argumentos son nombre y período.
Puesto que hemos llamado
al argumento periodo, como period,
esto debe coincidir exactamente.
Luego lo ejecutamos e invocamos
a sayHelloCallBack como antes.
Y de nuevo, se lanza
un cuadro de diálogo de alerta
que nos muestre
el mensaje de la respuesta.
Así que eso es todo.
greetByPeriodのコードを
アプリケーションに沿って見てみます
今はHelloWorldEndpoints.javaにいます
新たな関数greetByPeriodを定義しました
引数のnameがあります
periodという名の引数もあります
名前は@Named periodと少し変わっています
私はこの引数をtimeOfDayと呼びます
それは@Namedが何であろうとリクエストの中で
指定されるべきものを示すためです
ここでやっているのはnew HelloClassの
name、timeOfDayを返すことです
HelloClassのクラスには作者がいないので
新たに加えます
大変簡単です
これが新しく作ったHelloClassです
nameとperiodを渡して
新しいメッセージを作ります
Good これはmorningでしょう
そしてLauren
Good morning Laurenとなります
そうしたらdevserverで走らせてみます
今の変更を保存します 習慣にしましょう
そうしたらローカルホストに行きましょう
ブラウザから直接APIs Explorerに行きます
エラーです いつもこのようなことは起きません
“APIコンフィグの取得に失敗
status:500”と出ています
最初は焦ってしまうかもしれませんが
コードをチェックしましょう
ここにもエラーが出ているのが分かります
この表示はエンドポイント関数に
何か間違いがあることを意味しています
helloworldのエンドポイント関数の
greetByPeriodはよさそうです
何が問題でしょう? なるほど
コピー&ペーストのエラーです
見てください
前のメソッドからコピーしています
関数の名前を書き換えるのを忘れていました
すぐに正しいものに直します
2つの関数を同じ名前では表せません
実際にはgreetByPeriodです 保存しましょう
Javaコードを修正して保存すると通常は
修正が自動的にローカルホストに
伝わるのが分かります
これを見てください
もう一度実行する必要はありません
直接ローカルホストに行きます
APIs Explorerをリロードします
うまくいきました
APIをよく見てみましょう
これは私が作ったgreetByPeriodです
名前を入れます ここはafternoonです
それではレスポンスを見ましょう
ここです Good afternoon
Good afternoon Buttercupです
Buttercupは私が入れた名前です
あとindex.htmlとhello.jsのコードも
見てみましょう
index.htmlです
やらなくてはいけないことがあります
新たな入力フィールドを追加することです
period_fieldと言います
greetingのための新たなボタンを確認したら
hello.jsを見ます
enableButtonsは
新たなボタンの機能を有効にします
input_greet_by_periodは新しいボタンです
ここで関数greetByPeriodを呼びます
またボタンのラベルを書き換えます
greetByPeriodを定義する必要があります
greetByNameに似ていますが違います
name_fieldがあり
HTMLからnameの値が得られます
period_fieldのエレメントから
periodを得ることができます
リクエストを作ります これは関数です
引数を指定します
引数はnameとperiodです
periodと呼んでいたので
period引数を指定しました
periodについては正確に一致するはずです
実行します
前のようにsayHelloCallbackを呼びます
そうすると警告ダイアログが現れます
メッセージを示します これで全部です
Vamos dar uma olhada no código
para adicionar ao aplicativo
esse novo método greetByPeriod.
Aqui estou em HelloWorld e points.java.
Defini minha nova função greetByPeriod.
Ainda tenho o argumento do nome e
ele tem um argumento @Named("period").
E, apenas para variar, ainda que
o nome seja @Named("period")
vou chamar o argumento timeOfDay
apenas para mostrar que,
qualquer que seja o @Named
é o que precisa ser
especificado na solicitação.
O que estou fazendo aqui é retornar um novo
HelloClass(name, timeOfDay).
A classe HelloClass na verdade
não tinha esse construtor
então eu o adicionei,
é bem simples.
Aqui está a nova construção HelloClass.
Passe o nome, o período,
construa uma nova mensagem:
Bom, aqui seria manhã, digamos
Bom dia... Lauren. Bom dia, Lauren.
OK, vejamos se funciona.
Vou executar no servidor
de desenvolvimento
salvar minhas alterações,
é sempre bom fazer isso.
OK, vamos ao localhost no browser.
E vou direto ao Explorer do API.
Ah, céus. Deu erro.
Isso nunca acontece.
Falhou em obter configurações
de API com status: 500.
Tudo bem. A primeira reação é o pânico,
a segunda é voltar e checar o código.
E vemos que o erro também aparece aqui:
Falha em obter configurações de API.
Isso significa que tem algo errado com
minha função de ponto de extremidade.
Vamos ver os pontos de extremidade
HelloWorld, greetByPeriod...
Tudo parece em ordem.
Qual é o problema?
Arrá! É um erro de copiar e colar.
Veja aqui, eu copiei e colei isso
do método anterior, sayHelloByName
e esqueci de atualizar o nome da função.
Só vou arrumar isso bem rápido.
Não se pode ter duas funções
expostas com o mesmo nome.
O correto é greetByPeriod.
Salvar.
E, na verdade, quando você faz
alterações no código Java e as salva
normalmente vai perceber que
as alterações são automaticamente
propagadas para o localhost.
Veja que diz estar
"recarregando o aplicativo web".
"Um arquivo foi alterado".
Então, não preciso executar de novo.
Vou direto ao localhost,
recarrego o Explorer do API.
OK, ótimo.
Desta vez, funcionou.
Agora, vou fundo em meu API.
Aqui está meu novo greetByPeriod.
Insiro um nome.
E agora é de tarde.
Vamos ver a resposta.
Aqui está. Boa tarde.
Então, "Boa tarde, Buttercup",
pois Buttercup é o nome que dei.
Uma outra coisa a olhar é o código para
index.html e hello.js.
Dê uma olhada neles...
index.html.
O que tivemos de fazer foi adicionar
o novo campo de entrada para período
chamado period‗field
e o novo botão para as novas
boas-vindas, em Hello.js.
Em enableButtons, precisamos
ativar a função para o novo botão.
Aqui está o novo botão,
input‗greet‗by‗period.
Chamaremos essa função de
greetByPeriod.
Vamos atualizar o rótulo do botão.
Agora temos de definir greetByPeriod
e aqui está, muito similar a greetByName.
Mas obtemos o name‗field, obtemos
o valor do nome a partir do HTML
e obtemos o período a partir
do elemento period‗field.
Você constrói a solicitação.
E aqui chamamos a função greetByPeriod.
E especificamos o argumento.
Os argumentos são nome e período.
Agora, porque chamamos o período,
nomeamos o argumento de período @Period
isso tem de corresponder exatamente.
A seguir, executamos e chamamos
sayHelloCallBack, como antes.
E, novamente, isso lança uma
caixa de diálogo de alerta
exibindo a mensagem na resposta.
E isso é tudo.