java - 如何将 session 属性传递给 ThymeLeaf 表单字段以保存到数据库中

标签 java spring spring-boot thymeleaf

我有一个 Thymeleaf 表单,当用户登录时,它会将数据发送到数据库表。ThymeLeaf 模板能够从分配的 Controller 捕获登录用户的 session 。将数据保存到数据库时。

我需要将表单数据与捕获的 session 用户名一起保存,以便所述 session 用户名也保存在数据库表中。但是我收到一个错误,上面写着

org.springframework.beans.NotReadablePropertyException: Invalid property 'userName' of bean class [com.example.jobonics.Persistence.model.NewJobs]: Bean property 'userName' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

我有一个 Controller ,它选择用户 session 并将其发送到 thymeleaf 模板,以及我的表单中的隐藏输入用户字段,该字段保存来自 Controller 的 session 对象。为了清楚起见,我的代码粘贴在下面:

@RequestMapping(value = "/new_job", method = RequestMethod.GET)
public String newRegistration(ModelMap model) {
    NewJobs newJobs = new NewJobs();
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ServletRequestAttributes attr = (ServletRequestAttributes)
    RequestContextHolder.currentRequestAttributes();

   //extract user session from HttpSession
    HttpSession session = attr.getRequest().getSession(true);
    //initialize user service to get authenticated user
    User user = userService.findUserByEmail(auth.getName());

    model.addAttribute("newjobs", newJobs);
    //add session captured name as attribute to view
    model.addAttribute("userName", "Welcome " + user.getFullName() + "");
    return "new_job";

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveRegistration(@Valid NewJobs newJobs, BindingResult result, 
ModelMap model,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
     System.out.println("has errors");
        return "new_job";
    }

    NJS.save(newJobs);


    return "redirect:/new_job";
}
}

我的 Controller

<form class="form-horizontal" th:action="@{/save}" th:object="${newjobs}" method="post">

<div class="form-group">
    <div class="col-sm-7">
        <input type="text" class="form-control" th:value="*{userName}" style="display:none">
    </div>
</div>

新工作

@Entity
@Table(name = "newjobs")
public class NewJobs {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int job_id;

@Column(name = "Employer")
private String Employer;

@Column(name = "JobTitle")
@NotEmpty(message = "Please provide the job title")
private String jobTitle;

@Column(name = "job_summary", length = 1000)
private String jobSummary;

@Column(name = "job_description", length = 1000)
private String jobDescription;

@Column(name = "location")
private String Location;

@Column(name = "career_level")
@NotEmpty(message = "Please provide career level required")
private String careerLevel;

@Column(name = "industry")
private String industry;

@Column(name = "profession")
@NotEmpty(message = "Please provide the profession")
private String profession;

@Column(name = "jobtype")
@NotEmpty(message = "Please provide your job type")

private String jobType;
@Column(name = "min_experience")
@NotEmpty(message = "Please provide the Min years of experience")

private String minExperience;
@Column(name = "min_qualification")
@NotEmpty(message = "Please provide the Min Qualifications")
private String minQualification;

@Column(name = "salary")
@NotEmpty(message = "Please provide the salary")
private String salary;

@Column(name = "deadline_date")
@NotEmpty(message = "Please provide the Applications Deadline")
private String deadlineDate;

@Column(name = "created_at", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", insertable = false, nullable = false)
private Date created_at;
}`

我的预期输出是将登录的用户 session 对象作为提交表单的一部分发送到数据库。我该如何纠正上述错误?

最佳答案

我认为错误是您从错误的位置获取用户名:
th:value="*{userName}" 表示 newjobs.username
但在 Controller 中,您没有将用户名设置为newjobs,而是设置为模型属性

让我们更改 Controller 中的代码(使用额外的 getter)
newjobs.setUserName("欢迎光临"+ user.getFullName())


th:value="${userName}"($ 但不是 *)

注意:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expressions-on-selections-asterisk-syntax

There is an important difference though: the asterisk syntax evaluates expressions on selected objects rather than on the whole context. That is, as long as there is no selected object, the dollar and the asterisk syntaxes do exactly the same.

关于java - 如何将 session 属性传递给 ThymeLeaf 表单字段以保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733488/

相关文章:

java - Spring Boot junit 中 Resttemplate 的 Mocking 失败

java - 数据源无法通过 Spring boot 应用程序初始化?

java - 任务不可序列化 - Spark Java

java - 同步 不同步

java - 如何使用独立的 Neo4j 服务器配置 spring-data-neo4j?

java - 如何在Spring中动态启用系统文件访问?

java - SQLException:Jsp 登录数据库用户身份验证?

java - Spotify API 授权每次都会给我不同的刷新 token

java - 在本地创建 spring 和 nodejs 应用程序之间的 SSL 连接

java - Drools 8.x Java 8 兼容性