本文演示当使用spring security登录失败之后,在浏览器的页面上显示一个json字符串,内容是{"status","666","message","帐号密码不匹配"}
阅读本文之前如果要想运行的话,则需要先了解之前的文章使用浏览器访问并登录,因为本文涉及到一些HTML页面,如果不需要运行,那么直接看本文就行
首先定义一个往前端输出字符串的类,具备往response写数据的功能,当登录成功之后,该类被调用,这样就是先了本文的功能,代码如下
public class TestLoginErrorHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out=response.getWriter();
out.write("{\"status\",\"666\",\"message\",\"帐号密码不匹配\"}");
out.close();
}
}
通过前文可知我们应该实现WebSecurityConfigurerAdapter接口,代码如下
@Service
public class TestWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/TestLogin.html")
.loginProcessingUrl("/myLoginProcess")
.permitAll()
// 下面这行代码就是本篇文章新增的类,该类决定帐号密码输入错误之后如何处理
.failureHandler(new TestLoginErrorHandler())
.and()
.csrf().disable();
}
}
上一篇:登录成功后的处理逻辑
下一篇:模拟从数据库中获取用户信息