struts2實現攔截器的方法

jsp頁面 html

index.jsp java

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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>
<s:debug></s:debug>
${message}


<form action="login.action" method="post">
用戶名:<input type="text" name="username"><br>
密碼:<input type="text" name="passoword"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
jsp

Action方法 ide

package com.action;


import com.opensymphony.xwork2.ActionSupport;


public class InterAction extends ActionSupport {


@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("123");
return super.execute();
}


}
下面寫本身的interceptor post

package com.interceptor;
import model.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class FirstInterceptor implements Interceptor {
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("FirstInterceptor is destroyed...");
}
@Override
public void init() {
// TODO Auto-generated method stub
       System.out.println("FirstInterceptor is inited ....");
}


@Override
public String intercept(ActionInvocation arg0) throws Exception {
// TODO Auto-generated method stub
Object u=ActionContext.getContext().getSession().get("user");
if(u==null)
{
ActionContext.getContext().getSession().put("message","從新登陸");<!--把參數返回給jsp頁面-->
return "fail";
}
return arg0.invoke();
}
}
ui

struts.xml spa

<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="firstInterceptor" class="com.interceptor.FirstInterceptor">
</interceptor>
<!-- 加到本身設置的攔截器棧裏邊去 -->
<interceptor-stack name="myStack">
<interceptor-ref name="firstInterceptor">
</interceptor-ref>
<interceptor-ref name="defaultStack">
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack">
</default-interceptor-ref>
<action name="login" class="com.action.InterAction">
<result name="success">/successLogin.jsp</result>
<result name="fail">/index.jsp</result>
</action>
</package>
</struts>
debug

這樣即可以簡單實現本身的攔截器了
相關文章
相關標籤/搜索