【发布时间】:2019-11-02 21:48:04
【问题描述】:
我尝试在 Java、SpringBoot 和 HTML (thymeleaf) 中创建登录,但使用哈希映射来存储用户名和密码,而不是使用 SQL 或内置支持。我遇到了麻烦,因为它会在网站上打印哈希图(我也试图在网站上显示这两个值),但它确实像这样为空:“ {} ” 这是我所做的:
setter 和 getter:
import java.util.HashMap;
import java.util.Map;
public class Greeting {
// id = username. content = password.
private String id;
private String content;
public Map<String, String> userAndPassword = new HashMap<>();
public void setId(String id) {
// username
this.id = id;
}
public String getId() {
return id;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setuserAndPassword(Map<String,String> userAndPassword) {
this.userAndPassword = userAndPassword;
// adding username and password into the hashmap
userAndPassword.put(id, content);
}
public Map<String, String> getuserAndPassword() {
return userAndPassword;
}
}
视图(result.html):
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Web Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Datos</h1>
<p th:text="'User ID: ' + ${greeting.id}" />
<p th:text="'Password: ' + ${greeting.content}" />
<p th:text="'Printing out hashmap with all data: ' + ${greeting.userAndPassword}" />
</body>
</html>
控制器:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute Greeting greeting) {
return "result";
}
}
【问题讨论】:
-
控制器代码呢?
-
@Kayaman 刚刚添加
-
Greeting类没有遵循良好的做法(例如适当的封装),我不了解其方法的意图或应该如何使用它。你在哪里以及如何初始化它?里面的userAndPassword映射的目的是什么? -
@MartinBG 这是整个应用程序,我没有遗漏任何代码。 userAndPassword 映射是一个哈希映射,我在其中存储 id(用户名)和内容(密码)
-
new Greeting()使用默认 (null)id和content和空的userAndPassword映射创建实例。这就解释了为什么这些在浏览器中是空的。
标签: java spring model-view-controller thymeleaf