日期:2014-05-19  浏览次数:20680 次

struts2加入拦截器后页面取不了值
base.HelloWorld.java
Java code
package base;
import com.opensymphony.xwork2.ActionSupport;
import java.lang.Exception;

public class HelloWorld extends ActionSupport { 
    
    public void validate(){
        try{
        if(getUsername().trim().equals("")||this.getUsername()==null){
            System.out.println("validate");
            this.addFieldError("username",getText("username"));
        }
        //if(getPassword()==null|| getPassword()=="")this.addFieldError("password",getText("password"));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public String execute(){
        forwardMessage = "success";
        return forwardMessage;
    }
    
    public String getPassword() {
        return password; 
        }
    public void setPassword(String password) { 
        this.password = password;
        } 
    public String getUsername() { 
        return username; 
        }
    public void setUsername(String username) { 
        this.username = username; 
        }
    
    private String username;
    private String password; 
    private String forwardMessage;    
}



interceptors.ExampleInterceptor
Java code

package interceptors;

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

public class ExampleInterceptor implements Interceptor{

    public void destroy() {
        System.out.println("destroy");
        
    }

    public void init() {
        System.out.println("init");
    }

    public String intercept(ActionInvocation invocate) throws Exception {
        System.out.println("dobefore");
        invocate.invoke();
        System.out.println("doAfter");
        return "success";
    }
    
}



struts.xml
XML code

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

    <include file="struts-default.xml" />
    
    <package name="base" extends="struts-default">
        <interceptors>
            <interceptor name="Example" class="interceptors.ExampleInterceptor"></interceptor>
        </interceptors>
        
        <action name="HelloWorld" class="base.HelloWorld" >
            <result name="success">/HelloWorld.jsp</result>
            <result name="input">/index.jsp</result>
            <interceptor-ref name="Example"></interceptor-ref>
        </action>
    </package>
</struts>



index.jsp
HTML code

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ 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="Con