Struts2學習筆記 - 第003天

文件上傳

例子:用戶照片上傳
jsp

            <form id="form" action="User_register.do" method="post" enctype="multipart/form-data">

                <div class="item">
                    <input type="file" name="photo" size="28" multiple>
                </div>
            </form>

action

    private File[] photo;
    private String[] photoFileName;
    private String[] photoContentType;

        // set方法

    public String register() {
        if (photo != null) {
            List<String> filenames = new ArrayList<>();
            for (int i = 0; i < photo.length; i++) {
                if (canAccept(photoContentType[i])) {
                    String filename = getRandomFileName(photoFileName[i]);
                    filenames.add(filename);
                    String fullPath = getPath() + "/" + filename;
                    try (InputStream in = new FileInputStream(photo[i])) {
                        Files.copy(in, Paths.get(fullPath));
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        return "failed";
                    } 
                }
            }
            user.setPhotoFilename(filenames.toArray(new String[0]));
        }
        return "success";
    }
    
    private boolean canAccept(String contentType) {
        return contentType.equals("image/jpeg") ||
                contentType.equals("image/png") ||
                contentType.equals("image/gif");
    }
    
    private String getSuffix(String currentFileName) {
        return currentFileName.lastIndexOf(".") > 0 ?
                currentFileName.substring(currentFileName.lastIndexOf(".")) : "";
    }
    
    private String getRandomFileName(String currentFileName) {
        return UUID.randomUUID().toString() + getSuffix(currentFileName);
    }
    
    private String getPath() {
        return ServletActionContext.getServletContext()
                .getRealPath(path);
    }

文件copy

                    try (InputStream in = new FileInputStream(photo[i]);
                            OutputStream out = new FileOutputStream(fullPath)) {
                        // Files.copy(in, Paths.get(fullPath));
                        byte[] buf = new byte[1024];
                        while (in.read(buf) != -1) {
                            out.write(buf);
                        }

攔截器

例子:算出執行action花費的時間
pref攔截器

public class PerfInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) 
            throws Exception {
        long start = System.currentTimeMillis();
        String result = invocation.invoke();
        long end = System.currentTimeMillis();
        String name = invocation.getInvocationContext().getName();
        System.out.println(name + "執行時間: " + (end - start) + "ms");
        return result;
    }
}

struts.xml配置

        <interceptors>
            <interceptor name="perf" class="org.mobiletrain.interceptor.PerfInterceptor" />
            <interceptor-stack name="myStack">
                <interceptor-ref name="perf" />
                <interceptor-ref name="defaultStack" />
            </interceptor-stack>
        </interceptors>
        
        <default-interceptor-ref name="myStack" />

轉換器

例子:字符串經緯度自動轉換成對象
經緯高類

public class GeoLocation {
    private double latitude;
    private double longitude;
    private double altitude;
}

轉換器 繼承StrutsTypeConverter 或者 DefaultConverter

public class GeoLocationConverter extends StrutsTypeConverter {

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        String locationStr = values[0];
        String[] strs = locationStr.split("#");
        if (strs.length == 3) {
            GeoLocation location = new GeoLocation();
            location.setLatitude(Double.parseDouble(strs[0]));
            location.setLongitude(Double.parseDouble(strs[1]));
            location.setAltitude(Double.parseDouble(strs[2]));
            return location;
        }
        return null;
    }

    @Override
    public String convertToString(Map context, Object o) {
        GeoLocation location = (GeoLocation) o;
        return location.getLatitude() + "#" + location.getLongitude() +
                "#" + location.getAltitude();
    }

}

配置自己的轉換器 創建xwork-conversion.properties文件(格式必須)

com.kygo.entity.GeoLocation=com.kygo.converter.GeoLocationConverter

錯誤頁面struts.xml配置

        <global-results>
            <result name="error">/error.html</result>
        </global-results>
    
        <global-exception-mappings>
            <exception-mapping result="error" 
                exception="java.lang.Exception" />
        </global-exception-mappings>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容