《深入浅出struts2》--第十章 Preparable拦截器

一,主意参考转载的几篇关于这个拦截器的相关知识
1,得知,这个拦截器的prepare()方法,称为“action的准备方法”。也就是这个拦截器prepare()方法是在动作类action所有方法执行之前执行。它的作用是,是根据某个属性,检查某个模型类实例是不是已经存在, 如果不存在则新创建一个模型实例,如果这个属性已经被赋值,也就是这个模型实例已经存在的话,那么就调用别的层的相关方法 查找到这个对象。然后利用Model Driven拦截器把这个找到的模型对象压入ValueStack中。
2,但是必须要注意的是:
truts2的Action在实现com.opensymphony.xwork2.Preparable接口后,就可以重写prepare()方法
此时在Action中,prepare()方法的执行点是在:setXxx()和execute()的执行之前
比如需求:在执行Action的方法前,接收前台隐藏域传过来的值,再根据该值执行相应逻辑
如前台传过来ID,我们根据ID查找数据库对应的用户信息,再跳转到modify()中修改信息
但实际的运行过程中发现,通过Debug断点调试得知prepare()方法接收到的ID值是零
即前台隐藏域中的ID值没有传过来,事实上问题就出在默认的defaultStack拦截器栈上
其实defaultStack无法接收prepare()需要的数据,而应借助paramsPrepareParamsStack拦截器栈
事实上使用prepare拦截器之前,应先调用params拦截器,prepare()才能接收到表单数据
基于这个思路,于是可以通过各种手段将params拦截器放置在prepare拦截器之前即可
比如将defaultStack中的所有拦截器拷贝到struts.xml的我们自定义的myStack拦截器栈中
再按照paramsPrepareParamsStack拦截器栈中的params和prepare顺序修改二者位置即可。

3,书上知识:
这里写图片描述
这里写图片描述
4,案例:
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>
        app05a.ApplicationListener
    </listener-class>
  </listener>
  <filter>
     <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class> 
  </filter>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>  
</web-app>

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.devMode" value="false"/>  
    <package name="neizhi" extends="struts-default" namespace="/">
        <!-- 声明拦截器 -->
        <interceptors>
            <interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
            <interceptor-stack name="myStack1">
                <interceptor-ref name="modelDriven"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>
        <action name="Employee_list" method="list" class="app09.EmployeeAction">
            <result>/jsp/Employee.jsp</result>
        </action>
        <action name="Employee_create" method="create" class="app09.EmployeeAction">
            <result name="success" type="redirectAction">Employee_list</result>
            <result name="input">/jsp/Employee.jsp</result>
        </action>
        <action name="Employee_edit" method="edit" class="app09.EmployeeAction">
            <interceptor-ref name="paramsPrepareParamsStack"/>
            <result>/jsp/EditEmployee.jsp</result>
        </action>
        <action name="Employee_update" method="update" class="app09.EmployeeAction">
            <result type="redirectAction">Employee_list</result>
        </action>
        <action name="Employee_delete" method="delete" class="app09.EmployeeAction">
            <result>/jsp/Employee.jsp</result>
        </action>
    </package>
</struts>

动作类

package app09;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class EmployeeAction extends ActionSupport implements ModelDriven,Preparable{
    private int employeeId;
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    private Employee employee;
    private List<Employee> employees;
    public Employee getEmployee() {
        return employee;
    }
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
    public List<Employee> getEmployees() {
        employees=EmployeeManager.getEmployees();
        return employees;
    }
    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
    @Override
    public Object getModel() {
        return employee;
    }

    public String list(){
        employees=EmployeeManager.getEmployees();
        return SUCCESS;
    }

    public String create(){
        EmployeeManager.create(employee);
        return SUCCESS;
    }

    public String edit(){
        return SUCCESS;
    }

    public String update(){
        EmployeeManager.update(employee);
        return SUCCESS;
    }

    public String delete(){
        EmployeeManager.delete(employeeId);
        return SUCCESS;
    }

    @Override
    public void prepare() throws Exception {
        if(employeeId==0){
            employee=new Employee();
        }else{
            employee=EmployeeManager.find(employeeId);
        }
    }
}

模型类

package app09;

public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Employee() {
        super();
    }
    public Employee(int id, String firstName, String lastName) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

}

业务逻辑层

package app09;

import java.util.ArrayList;
import java.util.List;

public class EmployeeManager {
    private static List<Employee> employees;
    public static int id;
    static{
        employees=new ArrayList<Employee>();
        employees.add(new Employee(++id,"f1","l1"));
        employees.add(new Employee(++id,"f2","l2"));
        employees.add(new Employee(++id,"f3","l3"));
        employees.add(new Employee(++id,"f4","l4"));
    }
    public static List<Employee> getEmployees() {
        return employees;
    }
    public static void create(Employee employee){
        employee.setId(++id);
        employees.add(employee);
    }
    public static Employee find(int employeeId) {
        for (Employee em : employees) {
            if(em.getId()==employeeId){
                System.out.println("found");
                return em;
            }
        }
        return null;
    }
    public static void update(Employee employee) {
        int employeeId=employee.getId();
        for (Employee em : employees) {
            if(em.getId()==employeeId){
                em.setFirstName(employee.getFirstName());
                em.setLastName(employee.getLastName());
                break;
            }
        }
    }
    public static void delete(int employeeId) {
        for (Employee em : employees) {
            if(em.getId()==employeeId){
                employees.remove(em);
                break;
            }
        }
    }

}

试图

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'Employee.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <div>
        <h3>Add New Employee</h3>
        <s:form action="Employee_create">
            <s:textfield name="firstName" label="FirstName"/>
            <s:textfield name="lastName" label="lastName"/>
            <s:submit/>
        </s:form>
    </div>
    <br>
    <div>

        <s:iterator value="employees">
            <s:property value="id"/>&nbsp;&nbsp;<s:property value="firstName"/>&nbsp;&nbsp;<s:property value="lastName"/>
            <s:a href="Employee_edit.action?employeeId=%{id}">edit</s:a>
            <s:a href="Employee_delete.action?employeeId=%{id}">delete</s:a>
            <br>    
        </s:iterator>
    </div>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'Employee.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <div>

        <s:form action="Employee_update?employeeId=%{id}">
            <s:hidden name="id" label="%{employeeId}"/>
            <s:textfield name="firstName" label="FirstName"/>
            <s:textfield name="lastName" label="LastName"/>
            <s:submit/>
        </s:form>
    </div>
  </body>
</html>

运行结果:
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值