问题描述
我在后端环境中使用nodeJS,并且大多数API都已准备就绪。 由于 ,我想在前端使用Vaading。 我查看了Bakery示例,并设计了一个登录页面,该页面将用户凭据发送到我的后端API。 这是用于将POST请求发送到服务器的代码。
public void submit(String username, String password) throws IOException {
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost(URL);
HttpResponse response;
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode() == 200) {
System.out.println("Okey!");
// The response contains token. How can I store this token?
// Also, How can I use the stored token for future Authentication:Bearer?
}
}
catch(Exception ex) {
System.out.println(ex);
}
finally {
httpClient.close();
}
}
我想将响应的令牌存储在某个地方(我可以将其存储在React中的cookie对象中。但是,我对这种语言不熟悉),然后从该存储中获取令牌(cookie可能, 如何在Java中实现Cookie)网络? ),每次我提出请求时。
1楼
您使用哪个版本的Vaadin? 如果您使用Vaadin> = 10 :如何使用会话?
您可以将令牌保存在VaadinSession中,并在每次请求时从那里读取令牌。
我创建了一个最小示例,其中(单击按钮时)我检查令牌是否已保存在会话中。 如果是,它将打印在通知中。 如果没有,则将其保存到会话中。 代码如下:
@Route("")
public class MainView extends VerticalLayout {
public MainView() {
Button button = new Button("Click me", event -> {
Object token = VaadinSession.getCurrent().getAttribute("token");
if (token == null) {
Notification.show("No token found in session. Now storing token = 123456");
VaadinSession.getCurrent().setAttribute("token", "123456");
} else {
Notification.show("Found token in session: " + token.toString());
}
});
add(button);
}
}
结果看起来像:
(单击按钮三次)
更新 :可以在Vaadin 8中使用相同的功能,其中最小示例的代码如下所示:
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
Button button = new Button("Click me", event -> {
Object token = VaadinSession.getCurrent().getAttribute("token");
if (token == null) {
Notification.show("No token found in session. Now storing token = 123456");
VaadinSession.getCurrent().setAttribute("token", "123456");
} else {
Notification.show("Found token in session: " + token.toString());
}
});
layout.addComponents(button);
setContent(layout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}