struts2上传的问题

5.    在这里我加一个struts2的一个上传验证的问题

上传时我们可以这样来验证
//判断上传的文件是否合要求
    public boolean filterType(String []types){
        //这里用的是 上传的file对象的方法length
        //上传的类型都是二进制,所以我们就自己找后缀名
        String fileType = uploadUtil.getExt();
        for(String type : types){
            if(! type.equals(fileType)){
                return false;
            }
        }
        System.out.println("go to to to");
        return true;
    }
    
    //判断文件的大小
    public boolean filterLength(long length){
        //length 就以字节为单位的 1024*1024*3 3M
        //这里用的是 上传的file对象的方法length
        if(uploadUtil.getUpload().length() > length){
            System.out.println("wen jian 太大");
            return false;
        }

//得到扩展名
    public  String getExt(){
        return getUploadFileName().substring(getUploadFileName().lastIndexOf(".") + 1);
    }
        

在action中重写这个方法,这个方法会在调用action逻辑方法时调用。
public void validate() {
        System.out.println("kai shi validate");
        // TODO Auto-generated method stub
        String[] s = new String[3];
        s[0]="gif";
        s[1]="jpg";
        s[2]="png";
        if(filterType(s) && filterLength(1024*1024*3)){
            System.out.println("ok");
        }else{
            System.out.println("err err");
            //如果验证错误,就可以用addFieldError来传递错误的信息
            //用了这个方法struts2就会自动的跳到struts.xml中配置的input对应的路径的页面,在该页面可以用<s:fieldError/>来接收信息。
            addFieldError("error", "you wen ti"); 
        }
    }


我在做这个上传时还出现了一个很经典的问题
    The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag
这个问题是你的web.xml中配置的sturts只过滤了.action,
可以改成
<filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

但是这样不是很好,因为这样所有的请求都要经过action.这样不好。
可以这样改
<filter-mapping>
            <filter-name>struts</filter-name>
            <url-pattern>*.action</url-pattern>
    </filter-mapping>
<filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
原文地址:https://www.cnblogs.com/shaoshao/p/3797818.html