java - Vaadin 前端和令牌/Cookie
问题描述
我在后端环境中使用 nodeJS,并且大多数 API 都准备好了。由于Java 电子表格组件,我想在前端使用 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网络?)每次我提出请求时。
解决方案
您使用哪个版本的 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 {
}
}
推荐阅读
- c++ - 共享指针继承,无需先显式转换
- c# - windows 域外的应用程序服务器可以验证该域的用户吗?
- rabbitmq - centos7上无法启动rabbitmq-server
- android - Recyclerview 点击事件不适用于数据绑定和 livedata
- javascript - 在 for...of 对象循环中使用变量
- python - 如果它不在注释中,则替换字符串,在 Python 中使用正则表达式
- uproot - 如何使用 np 数组作为锯齿数组的掩码(python - 尴尬)?
- prometheus - PromQL:识别在时间范围内不断上升的指标
- python - 为什么我的 Python 代理不接受连接?
- python - 将多种格式的持续时间数据转换为通用格式的 '%H%M%S' 。格式(分钟)的 %M 部分不一致