public class LoginAction extends ActionSupport implements SessionAware{
private String username;
private String password;
private Map<String,Object> session;
/*
* 该方法是获取session对象
* (non-Javadoc)
* @see org.apache.struts2.interceptor.SessionAware#setSession(java.util.Map)
*/
@Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
public String login(){
if("admin".equals(username) && "123".equals(password)){
session.put("username",username);
return SUCCESS;
}
else{
session.put("usernameerror","用户名输入不正确");
return ERROR;
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="LoginInteceptor" class="com.inteceptor.LoginInteceptor"></interceptor>
</interceptors>
<action name="auth">
<result>/WEB-INF/page/user.jsp</result>
<result name="login">/index.jsp</result>
<!-- 引用自定义的拦截器 -->
<interceptor-ref name="LoginInteceptor"></interceptor-ref>
</action>
<action name="LoginAction" method="login" class="com.action.LoginAction">
<result>/WEB-INF/source/user.jsp</result>
<result name="ERROR">/index2.jsp</result>
</action>
</package>
</struts>
public class LoginInteceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
//获取用户上下文
ActionContext context=ActionContext.getContext();
Map<String,Object> session=context.getSession();
if(session.get("username")!=null){
String result=invocation.invoke();
System.out.println(result);
return result;
}
else{
return "login";
}
}
}
<h2>用户登录</h2>
${usernameerror}
<form action="LoginAction.action" method="post">
用户名: <input type="text" name="username" value=""/>
密码: <input type="password" name="password" value="">
<input type="submit" value="登录"/>
</form>