You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何在HTML页面展示已登录用户名并通过输入框将其传入用户表

1. 在Spring Boot项目的HTML页面显示已登录用户名并作为输入内容

咱们分两步来实现:后端把登录用户信息传递给前端,前端用模板引擎渲染显示并填充输入框。

后端部分(Controller)

首先,你需要从Spring Security的上下文里拿到当前登录用户的用户名,然后把它放到Model对象中传给前端页面。示例代码如下:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserPageController {

    @GetMapping("/dashboard")
    public String loadDashboard(Model model) {
        // 获取当前登录用户的认证信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String loggedInUsername = auth.getName(); // 提取用户名
        
        // 将用户名存入Model,供前端使用
        model.addAttribute("currentUser", loggedInUsername);
        
        return "dashboard"; // 对应src/main/resources/templates下的dashboard.html
    }
}

前端部分(HTML + Thymeleaf)

Spring Boot默认用Thymeleaf作为模板引擎,你可以用它来渲染用户名,并把值填充到输入框里:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>用户控制台</title>
</head>
<body>
    <!-- 显示已登录用户名 -->
    <div class="welcome-text">
        欢迎回来,<span th:text="${currentUser}" style="font-weight: bold;"></span>!
    </div>

    <!-- 将用户名作为输入框内容 -->
    <form th:action="@{/save-user-record}" method="post">
        <div class="form-group">
            <label>操作人用户名:</label>
            <!-- 用th:value填充默认值,readonly防止用户修改(可选) -->
            <input type="text" name="operator" th:value="${currentUser}" readonly />
        </div>
        <!-- 其他表单字段... -->
        <button type="submit">提交记录</button>
    </form>
</body>
</html>

这样页面加载后,就会显示当前登录的用户名,同时输入框也会自动填充这个值。如果不需要锁定输入框,去掉readonly属性即可。


2. 将已登录的ADMIN用户名传入用户表

这里有两种可靠的实现方式,推荐第二种(后端直接获取),更安全:

方式一:通过前端表单传递,后端接收保存

这种方式基于上面的前端表单,后端接收输入框里的用户名,然后存入数据库:

1. 定义User实体和Repository

首先确保你有对应的实体类和数据访问层:

// User实体类
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    // 其他字段如角色、创建时间等
    // 省略构造方法、getter和setter
}

// UserRepository接口
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

2. 后端Controller处理请求

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserRecordController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/save-user-record")
    public String saveUserRecord(@RequestParam("operator") String operatorUsername) {
        // 创建User对象,设置用户名
        User newUser = new User();
        newUser.setUsername(operatorUsername);
        // 可根据需求设置其他属性,比如角色为ADMIN
        // newUser.setRole("ADMIN");
        
        // 保存到数据库
        userRepository.save(newUser);
        
        return "redirect:/success"; // 跳转到成功页面
    }
}

方式二:后端直接获取登录用户名(更安全)

如果要确保传入的一定是当前登录的ADMIN用户名,避免前端篡改,直接在后端从Security上下文获取即可,不需要依赖前端传递:

@PostMapping("/save-user-record")
public String saveUserRecord() {
    // 直接从Security上下文获取当前登录用户名
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String adminUsername = auth.getName();
    
    User newUser = new User();
    newUser.setUsername(adminUsername);
    // 设置其他属性...
    
    userRepository.save(newUser);
    
    return "redirect:/success";
}

这种方式下,前端甚至不需要显示用户名输入框,完全由后端控制,安全性更高,非常适合你的需求。


内容的提问来源于stack exchange,提问作者isfa afreen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:37:36