当浏览器中输入:
http://127.0.0.1:8080/strutslearn5/checkLogin时,向LoginAction发送请求,此请求会被LoginInterceptor 拦截,因为此时肯定没有用户的登录信息,因此会返回到login.jsp界面。
登录action
package test;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
public String execute(){
return SUCCESS;
}
}
自定义拦截器文件
package testInterceptor;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation ai) throws Exception {
Map session = ai.getInvocationContext().getSession();
String username = (String) session.get("user");
if(username!=null && username.length()>0){
return ai.invoke();
} else {
ActionContext ac = ai.getInvocationContext();
ac.put("popedom", "您还没有登陆");
return Action.LOGIN;
}
}
}
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>
<package name="testInterceptor" extends="struts-default" namespace="/">
<interceptors>
<interceptor name="checkLogin" class="testInterceptor.LoginInterceptor"></interceptor>
</interceptors>
<action name="checkLogin" class="test.LoginAction">
<result name="success">/success.jsp</result>
<result name="login">/login.jsp</result>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="checkLogin" />
</action>
</package>
</struts>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆</title>
</head>
<body>
<center>
<s:property value="popedom" /> <!-- 定义信息输出标签 -->
<br /> <b>用户登录</b> <br />
<s:form>
<s:textfield label="用户名" name="username"></s:textfield>
<s:password label="密码" name="password"></s:password>
<s:submit value="提交" ></s:submit>
</s:form>
</center>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
登陆成功
</body>
</html>