我正在尝试使用 Java、SpringBoot 和 HTML (thymeleaf) 创建登录,但使用 HashMap 来存储用户名和密码,而不是 SQL 或内置支持。我遇到了麻烦,因为它在网站上打印 HashMap (我也尝试在网站上显示这两个值),但它像这样是空的:“{} ” 这是我所做的:
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;
}
}
View (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>
Controller :
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";
}
}
最佳答案
我不太清楚你的问题。假设您希望在 post
调用之后进入 result
页面。但是您没有在那里绑定(bind)任何 Greeting
对象。所以请尝试如下所示。
@PostMapping("/greeting")
public ModelAndView greetingSubmit(@ModelAttribute Greeting greeting) {
ModelAndView mv= new ModelAndView("result");
mv.addAddObject("greeting", greeting);
return mv;
}
希望您的问候语
不是null
关于java - 在 Java Spring MVC 中使用 hashmap 作为数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675591/