【问题标题】:How can I get the current user's ID without Spring Security?在没有 Spring Security 的情况下如何获取当前用户的 ID?
【发布时间】:2021-08-06 03:18:28
【问题描述】:

我正在制作一个 Edairy 应用程序,我现在正在制作 StudentGrades HTML 页面,该页面应该列出学生的科目和他们的成绩。重要的是不同的学生有不同的科目,所以我只想显示登录的学生科目和他们的成绩。 (例如学生 1 有化学和物理,学生 2 有体育、数学)

现在我尝试创建一种方法,根据当前登录的学生 ID 从数据库中选择主题,但我不使用 Spring Security。我尝试了 2 种不同的方法,但都失败了。

public List<Subject> findAll(Integer userId) {

    
    String sql = "SELECT subject.subjectName,subject.subjectId FROM subject inner join subjectgrade on subject.subjectId = subjectgrade.subjectId right join users on subjectgrade.userId = users.user_id where subjectgrade.userId = ?";
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Subject.class));
}
 

通过这种尝试,程序无法处理预期的任务,因为 userId 存在,但是它是原始类型,并且由于某种原因不喜欢它:

Request processing failed; nested exception is java.lang.IllegalStateException: Optional int parameter 'userId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.

在第二次尝试中,我尝试将用户传递给参数。使用该方法,程序成功运行,但它没有选择登录用户的主题,因为我无法弄清楚如何从会话中获取用户的 ID(?)。

public List<Subject> findAll(User user) {

    
    String sql = "SELECT subject.subjectName,subject.subjectId FROM subject inner join subjectgrade on subject.subjectId = subjectgrade.subjectId right join users on subjectgrade.userId = users.user_id where subjectgrade.userId = "+ user.getUserId();
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Subject.class));
}

需要注意的是,我没有使用 Spring Security,因为我只是在练习编码。我可以在不重新构建整个程序的情况下获得用户的 ID 吗?还是我犯了一个巨大的逻辑缺陷,让我停下来? (?) = 不知道怎么称呼它。

【问题讨论】:

  • 你的学科课是什么样子的?在您的第一次尝试中,提供的 userId 不是原始类型。 Integer 是原始 int 的包装器,因此可以为 null。
  • 我的主题类仅由 getter 和 setter 及其属性组成。我将 subjectId 定义为 int,而不是 Integer。有问题吗?
  • 当然:正如异常所说,user_idint 类型,这是一个原始类型,除了 NULL 值之外。您需要使用 Integer 类,它是 int 的包装类型,允许 NULL 值
  • 你是最好的丹尼尔,没想到这么敏感。你能推荐我一种在没有 Spring Security 的情况下获取用户 ID 的方法吗?该程序现在将按照我的预期运行。
  • 不客气。将评论发布为答案,以便您接受。你应该在Can you recommend me a way to get the User's id without Spring Security 更准确。目前如何获取userId?

标签: java html mysql session


【解决方案1】:

正如例外所说,user_idint 类型,这是一种原始类型。原始类型不能是NULL

要将 NULL 用于 int 值,您需要使用名为 Integer 的相应包装类,它允许分配 NULL

【讨论】:

    猜你喜欢
    • 2010-10-06
    • 2020-02-12
    • 2018-08-18
    • 2018-01-25
    • 2011-01-31
    • 1970-01-01
    • 2014-09-15
    • 2011-09-16
    • 2023-03-25
    相关资源
    最近更新 更多