springboot+springsecurity+velocity无法显示登录错误信息的问题修复

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y41992910/article/details/84990157

最近在整合springboot+springsecurity+velocity时,发现的假如登录错误。但是页面上无法显示springsecurity返回的登录错误信息。

通过查看源码发现,它是将错误信息放入了request中。
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,exception);

public class SimpleUrlAuthenticationFailureHandler implements
		AuthenticationFailureHandler 
		
	protected final void saveException(HttpServletRequest request,
			AuthenticationException exception) {
		if (forwardToDestination) {
			request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
		}
		else {
			HttpSession session = request.getSession(false);

			if (session != null || allowSessionCreation) {
				request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,
						exception);
			}
		}
	}

所以猜测原因有以下三种:最终确认是velocity配置的问题
解决方案:
在application.properties中配置,这样才能从request和session中获取信息

spring.velocity.expose-request-attributes=true
spring.velocity.expose-session-attributes=true

可能的原因1:请求进行了重定向,所以所有的信息都丢失了;解决方案改成请求转发。
可能的原因2:通过eclipse查看,确实request中没有这个错误信息的值。解决方案:我们直接在错误的时候,将错误信息放入session中,在页面上直接显示。
可能的错误3:是否是页面没有经过velocity解析器解析的问题。需要测试查看

velocity测试代码,发现只有testmodel能取到值,也就能明确问题所在

	@RequestMapping("/velocity")
	public String helloVelocity(
			HttpServletRequest request,
			HttpSession session,
			Model model
			){
		request.setAttribute("testrequest", "11111");
		session.setAttribute("testsessiont", "22222");
		model.addAttribute("testmodel", "22222");
		return "testvelocity";
	}
public static final String AUTHENTICATION_EXCEPTION = "SPRING_SECURITY_LAST_EXCEPTION";

但是通过代码查询,request中并没有这个参数,但是奇怪的是,页面上连testrequest=测试往testrequest中放入信息这个参数都没有了。调试是进行了重定向了。
但是session中的值也没有显示出来。

测试如何显示session和request中的值。

猜测应该是我们的页面解析没有其作用。

[null, null, org.springframework.web.context.request.async.WebAsyncManager.WEB_ASYNC_MANAGER=org.springframework.web.context.request.async.WebAsyncManager@22870d3f, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.FILTERED=true, null, null, null, null, null, org.springframework.security.web.header.HeaderWriterFilter@691500ab.FILTERED=true, characterEncodingFilter.FILTERED=true, null, null, null, null, null, null, null, testrequest=测试往testrequest中放入信息, null, null, null, null, null, null, null, null, null, null, null, null, null]

猜你喜欢

转载自blog.csdn.net/y41992910/article/details/84990157