我正在为我们的 Web 应用程序使用 Spring MVC 和 Spring Security。成功登录后,请求被重定向到 HTML 页面 (login.html)。在使用 Ext-JS 之后,我们有大约 4 个 AJAX 调用被执行。
我有一个需求,就是登录成功后发送JSON数据。这意味着 JSON 数据必须与登录页面一起传递给客户端。在登录页面上,我们需要访问此 JSON 数据并呈现它。坦率地说,这与 login.html 页面上的 Ext-JS 代码请求的数据相同。目标是通过 AJAX 调用避免额外的请求。
我在 stackoverflow 和其他网站上尝试了各种示例(只是避免提及,以防止困惑)并创建了一个自定义身份验证处理程序,并进行了适当的更改。一切正常,但无法将 JSON/任何数据发送到客户端。
下面是application-context.xml的配置
<http auto-config="false" use-expressions="true">
<form-login login-page="/login"
login-processing-url="/static/j_spring_security_check"
authentication-failure-url="/login?login_error=t"
authentication-success-handler-ref="customAuthHandler"
authentication-failure-handler-ref="customAuthHandler"
default-target-url="/html/index.html"
always-use-default-target="true"/>
<beans:bean id="customAuthHandler"
class="com.mycompany.security.CustomAuthenticationHandler"/>
在 CustomAuthenticationHandler 的 onAuthenticationSuccess 方法上,我有以下代码来查看我是否可以获得此值,但我不能。我的理解是,因为它是一个 HTML/静态内容,所以我无法将 session 值传递给客户端,而这需要是一个 JSP。 (如有错误,请指正!)由于官僚主义原因,我无法将 HTML 更改为 JSP:
测试 1:
request.getSession(true).setAttribute("ssntest", "hello:how:are:you");
测试 2:
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
Writer out = responseWrapper.getWriter();
String targetUrl = "/login";
out.write("{success:true, targetUrl : \'" + targetUrl + "\'}");
out.close();
什么是在成功验证时将 JSON 值与 HTML 一起传递的方法。
最佳答案
在 session 中保留这种数据不是一个好方法,但您可以尝试使用 SpringMVC 提供的 @SessionAttributes
注解。再看一个answer
重点是将您的 JSON 值保存到登录页面的 session 中,然后在成功验证后在另一个 AJAX 请求中将其返回。
关于java - 身份验证成功后将 JSON 数据传递给 HTML - Spring security 和 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9717046/