Struts2中的拦截器入门

来源:互联网 发布:mac office 卸载 编辑:程序博客网 时间:2024/06/06 00:35

1。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="default" namespace="/" extends="struts-default">        <interceptors>            <interceptor name="my" class="cn.itcast.intercept.MyInterceptor"/>        </interceptors>        <action name="demo1" class="cn.itcast.action.Demo1Action">            <result name="login">/login.jsp</result>            <interceptor-ref name="my" />        </action>    </package></struts>

2。定义的拦截器MyInterceptor.java文件:

package cn.itcast.intercept;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;public class MyInterceptor implements Interceptor {    public void destroy() {    }    public void init() {        System.out.println("my interceptor init");    }    public String intercept(ActionInvocation ai) throws Exception {        System.out.println("my interceptor 拦截。。。。。");        return ai.invoke(); // 放行    }}

3。动作类Demo1Action.java 文件:

package cn.itcast.action;import com.opensymphony.xwork2.ActionSupport;public class Demo1Action extends ActionSupport {    @Override    public String execute() throws Exception {        System.out.println("demo1 action");        return "login";    }    public String a() throws Exception {        System.out.println("a action");        return null;    }}

4。视图login.jsp文件:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title></head><body>        <s:fielderror/>        <s:actionerror/>            <form action="${pageContext.request.contextPath}/login" method="post">        username:<input type="text" name=username><br>        password:<input type="password" name="password"><br>        <input type="submit" value="login">    </form></body></html>

运行:http://localhost:8080/Struts2_Interceptor/demo1
结果:这里写图片描述

0 0