struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!--定义常量 -->
<!-- 禁用动态调用方法 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<constant name="struts.devMode" value="true"></constant>
<package name="default" namespace="/" extends="struts-default">
<!-- 注册拦截器 -->
<interceptors>
<interceptor name="auth" class="com.imooc.intercepter.AuthIntercepter"></interceptor>
<!-- 定义拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="auth"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 通过此Action访问后台管理页面 ,需要判断用户是否已登录,如果未登录则跳转到登录页面-->
<action name="auth">
<result>/WEB-INF/page/manager.jsp</result>
<result name="login">/lo.jsp</result>
<!-- 引用自定义的拦截器栈 -->
<interceptor-ref name="myStack"></interceptor-ref>
</action>
<action name="login" class="com.imooc.action.LoginAction" method="login">
<result name="success">/WEB-INF/page/manager.jsp</result>
<result name="error">/lo.jsp</result>
</action>
</package>
</struts>
LoginAction.class
package com.imooc.action;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport implements SessionAware{
private String uname ;
private String upwd;
private Map<String, Object> session;
//获取session
public void setSession(Map<String,Object> session) {
this.session = session;
}
public String getName() {
return uname;
}
public void setName(String name) {
this.uname = name;
}
public String getPassword() {
return upwd;
}
public void setPassword(String password) {
this.upwd = password;
}
// 处理login的问题
public String login(){
if("admin".equals(uname) && "123456".equals(upwd)){
session.put("loginInfo", uname);
return SUCCESS;
}else{
session.put("loginError","用户名或密码错误!");
return ERROR;
}
}
}
AuthInterceptor.class
public class AuthIntercepter extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext context = ActionContext.getContext();
Map<String,Object> session = context.getSession();
if(session.get("loginInfo")!=null){
String result = invocation.invoke();
return result;
}else{
return "login";
}
}
}