使用actionerror做失败登录验证
一. 登录页面中放置如下代码:
<h4>员工登录</h4>
<div style="color:red">
<s:actionerror/>
</div>
如果登录出现异常,就会将你设置的异常信息反馈出来.
二. 这个<s:actionerror/>标签需要jsp的标签库支持,代码如下:
<%@ taglib uri="/struts-tags" prefix="s" %>
三. struts-tags标签库使用struts的filter进行过滤,需要在web.xml中过滤.jsp文件
代码如下:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
最后actionerror需要在验证登录的时候,接收抛出的异常
如果抛出的是UnknownAccountException,
就添加一个actionerror,代码如下:
this.addActionError("用户名错误!");
如果抛出的是IncorrectCredentialsException,
就添加一个actionerror,代码如下:
this.addActionError("密码错误!");
相关代码使用shiro框架进行验证,代码如下:
@Action("userAction_login")
public String login() throws Exception {
String realCheckcode = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
if(StringUtils.isNotBlank(realCheckcode)){
if(realCheckcode.equals(checkcode)){
//在shiro框架基础开始认证
//获取subject对象 认证状态:未认证
Subject subject = SecurityUtils.getSubject();
if(subject.isAuthenticated()){
return "index";
}else{
//认证令牌(用户在登陆页面中输入)
AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), Md5Util.encode(model.getPassword()));
//认证-登陆
try {
subject.login(token);
//跳转首页
//从subject中获取主角对象
User user = (User) subject.getPrincipal();
ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
return "index";
} catch (Exception e) {
if(e instanceof UnknownAccountException){
//账户错误
this.addActionError("用户名错误!"); //在登陆页面中获取错误信息。 通过strut2标签获取 <s:actionerror> 问题
}
if(e instanceof IncorrectCredentialsException){
//密码错误
this.addActionError("密码错误!"); //在登陆页面中获取错误信息。 通过strut2标签获取 <s:actionerror> 问题
}
e.printStackTrace();
}
}
}
}
return "login";
}