第 18 讲 struts2的拦截器

struts的拦截器
Struts2 拦截器是在访问某个 Action 或 Action 的某个方法,字段之前或之后实施拦截,并且 Struts2 拦截器是可 插拔的,拦截器是AOP的一种实现. 优点:通用功能的封装,提供了可重用性

1.复制项目HeadFirstStruts2chapter02_07,并改名:HeadFirstStruts2chapter03,同时修改web project settings
2新建包com.cruise.interceptor 包, 和类Myinterceptor,实现interceptor接口,删除多余的Action,保留并修改HelloAction,
MyInterceptor如下,调String result = invocation.invoke();这个方法的时候,就是调用Action里面的方法。

package com.cruise.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyInterceptor implements Interceptor{

    @Override
    public void destroy() {

       System.out.println("Myinterceptor销毁");
    }

    @Override
    public void init() {
       System.out.println("Myinterceptor初始化");
       
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
       System.out.println("在Action执行之前。。。");
       String result = invocation.invoke();
       System.out.println("在Action执行之后。。。");
       System.out.println(result);
       return result;
    }
}
HelloAction如下:
package com.cruise.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport{
    
    private String name ;
    
    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }
    @Override
    public String execute() throws Exception {
       System.out.println("HelloAction方法执行了");
       return "success";
    }
}
3struts.xml文件,定义拦截器,并在标签中引用拦截器,一个是自定义的,一个是默认的拦截器,先执行自定义的拦截器,再执行默认的拦截器。这样其他的拦截器栈才可以引用
xml version="1.0" encoding="UTF-8" ?>
DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="manage" namespace="/" extends="struts-default">
    <interceptors>
       <interceptor name="myInterceptor" class="com.cruise.interceptor.MyInterceptor">interceptor>
    interceptors>
    <action name="hello" class="com.cruise.action.HelloAction" >
       <result name="success" >success.jspresult>
       <interceptor-ref name="myInterceptor">interceptor-ref>
       <interceptor-ref name="defaultStack">interceptor-ref>
    action>
package>
struts>
3修改success.jsp删除其他的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 heretitle>
head>
<body>
name:${name}
body>
html>
4测试:
http://localhost:8080/HeadFirstStruts2chapter03/hello?name=你好

猜你喜欢

转载自blog.csdn.net/u010393325/article/details/83928680