java - Spring MVC 奇怪的行为

标签 java spring model-view-controller

我有一个方法可以处理 URI 为“/home”的请求。该请求是在成功登录过程后生成的。这是一些支持我的情况的代码:

<security:form-login login-processing-url="/static/j_spring_security_check"
login-page="/login" authentication-failure-url="/login?login_error=t"
default-target-url="/home"/> 

方法主体演示了我想要实现的目标:

String userMail = SecurityContextHolder.getContext().
    getAuthentication().getName();
logger.info(userMail);

Person p = userService.retrieveUserByEmail(userMail);
session.setAttribute("person", p);

return "user/home";

这一位很重要,因为人 p 被用作其他请求的数据源。

现在问题来了。我不知道它是否是 Google Chrome 的属性,但由于某种原因,浏览器会记住您在登录之前所做的请求,并且在成功登录过程后不会通过/home 请求,而是会生成之前的请求请求绕过此/home 门,导致空指针异常,因为 person p 从未设置,因为/home 请求未填充 session 。

我知道对于其他请求我应该进行验证,但我不喜欢让用户在不事先经过/home 的情况下生成任何请求的想法。

完成文字描述,现在解释我如何逐步获得不需要的行为:

  1. 提出您知道存在的请求,例如: myApp/nameOfSomething/viewThisSomething - 您将按预期进入登录页面(您必须经过身份验证才能接受请求)

  2. 您输入正确的凭据,而不是转到 default-target-url="/home" 您会自动发出先前的请求 myApp/nameOfSomething/viewThisSomething ,而不会使用必要的数据填充 session 并导致空指针异常。

其他有趣的是记录器显示邮件,因此它们可能同时执行,但/home 请求较慢 - 这会发生吗?

我通过检查是否为空并强制返回/home 来解决其他方法中的情况,这按预期工作,但我是控制狂,不喜欢用户做他不打算做的事情。

感谢您的宝贵时间,

最佳答案

这不是一个错误,而是一个功能。登录后让用户去他想去的地方比强制他去主页要方便得多。他可能已经为 protected 页面之一添加了书签,或者只是浏览了一些包含 protected 页面链接的非 protected 页面。

来自http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-form-target :

If a form login isn't prompted by an attempt to access a protected resource, the default-target-url option comes into play. This is the URL the user will be taken to after successfully logging in, and defaults to "/". You can also configure things so that the user always ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the always-use-default-target attribute to "true"

恕我直言,您应该保持原样,但请确保在登录成功后设置所需的 session 属性,而不是在主页中设置此属性。这将确保每个 protected 页面都可以访问 session 属性,即使用户没有访问主页。

您可以通过使用自定义 UsernamePasswordAuthenticationFilter 子类轻松完成此操作,一旦身份验证成功,该子类就会在 session 中设置适当的属性。

关于java - Spring MVC 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8913897/

相关文章:

ios - Objective-C 中的解耦模型和分离公共(public)/私有(private)方法(协议(protocol)与公共(public)/私有(private) header )

java - 将 BufferedReader 转换为文件

Java通过套接字发送文件

java - 如何在 Guice 中为变量设置默认值

java - Spring com.mongodb.util.JSONParseException

ios - 如何最好地在此 MVC 中构建模型

java - p :selectOneMenu: Validation Error: Value is not valid

java - 使用 Junit 5 和 Micronaut 设置测试 MongoDBContainer

java - 如何在Spring上有条件地创建@Controller和@Service实例

c# - MVC 替代路由因可选参数而失败