• java:struts框架(网路静态U盘项目)


    1.网络静态U盘项目:

       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.multipart.maxSize" value="209715200"></constant>
        <package name="udisk" extends="struts-default">
            <global-results>
                <result name="error">/error.jsp</result>
            </global-results>
            
            <!-- 配置struts2的异常映射 -->
            <global-exception-mappings>
                <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
            </global-exception-mappings>
    
            <action name="user-*" class="cn.zzsxt.udisk.action.UserinfoAction" method="{1}">
                <result type="redirect">/login.jsp</result>
                <result name="login" type="redirect">/login.jsp</result>
                <result name="list" type="redirectAction">file-list</result>
            </action>
            <action name="file-*" class="cn.zzsxt.udisk.action.FileinfoAction" method="{1}">
                <result name="list">/list.jsp</result>
                <result name="success" type="redirectAction">file-list</result>
                <!-- 下载 -->
                <result type="stream" name="download">
                    <!-- inputName="输入流的名称",回掉action中getInputStream()方法获取输入流 -->
                    <param name="inputName">inputStream</param>
                    <!--contentType="文件类型" application/octet-stream代表对下载类型不限制  -->
                    <param name="contentType">application/octet-stream</param>
                    <!-- attachment:以附件方式保存 filename="保存的文件名称" ${fileName}获取action中fileName属性的值 -->
                    <param name="contentDisposition">attachment;filename=${fileName}</param>
                </result>
            </action>
        </package>
    </struts>

      FileinfoAction:

    package cn.zzsxt.udisk.action;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.SessionAware;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    import cn.zzsxt.udisk.model.Fileinfo;
    import cn.zzsxt.udisk.model.Userinfo;
    import cn.zzsxt.udisk.service.IFileinfoService;
    import cn.zzsxt.udisk.service.impl.FileinfoServiceImpl;
    
    public class FileinfoAction extends ActionSupport implements SessionAware,ServletRequestAware{
        private IFileinfoService fileinfoService  =new FileinfoServiceImpl();
        private Map<String,Object> session;
        private HttpServletRequest request;
        private File[] upload;//接收上传的文件信息
        private String[] uploadFileName;//接收上传文件的名称
        private int fileId;
        private String fileCode;//提取码
        private String fileName;//文件名称
        //结合stream结果视图完成下载功能
        private InputStream inputStream;
        
        public File[] getUpload() {
            return upload;
        }
        public void setUpload(File[] upload) {
            this.upload = upload;
        }
        public String[] getUploadFileName() {
            return uploadFileName;
        }
        public void setUploadFileName(String[] uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
        
        public int getFileId() {
            return fileId;
        }
        public void setFileId(int fileId) {
            this.fileId = fileId;
        }
        
        public String getFileCode() {
            return fileCode;
        }
        public void setFileCode(String fileCode) {
            this.fileCode = fileCode;
        }
        
        public InputStream getInputStream() {
            return inputStream;
        }
        public void setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }
        
        public String getFileName() {
            return fileName;
        }
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
        /**
         * 查询用户的文件列表
         * @return
         * @throws Exception
         */
        public String list() throws Exception {
            //从session中获取用户信息
            Userinfo user = (Userinfo)session.get("loginUser");
            if(user!=null){
                int userId = user.getUserId();
                List<Fileinfo> list = fileinfoService.findFileinfoByUserId(userId);
                request.setAttribute("list", list);
            }
            return "list";
        }
        /**
         * 文件的上传
         * @return
         */
        public String upload() throws Exception{
            //获取登陆用户信息
            Userinfo user = (Userinfo)session.get("loginUser");
            String path = request.getServletContext().getRealPath("/");
            Fileinfo[] files = new Fileinfo[upload.length];
            for(int i=0;i<files.length;i++){
                Fileinfo file = new Fileinfo();
                file.setFileName(uploadFileName[i]);//设置文件名称
                file.setFileSize(upload[i].length());//设置文件大小
                file.setFilePath(path+"upload\"+user.getUserName()+"\"+uploadFileName[i]);
                file.setUserId(user.getUserId()); //file.setUserinfo(user);
                files[i]=file;
            }
            int count = fileinfoService.uploadFile(files, user, path, upload);
            if(count>0){
                return this.SUCCESS;
            }
            return this.ERROR;
        }
    
        /**
         * 删除文件
         * @return
         * @throws Exception
         */
        public String delete() throws Exception{
            int count = fileinfoService.removeFile(fileId);
            if(count>0){
                return this.SUCCESS;
            }
            return this.ERROR;
        }
        
        /**
         * 下载
         * @return
         * @throws Exception
         */
        public String download() throws Exception{
            //根据提取码获取文件信息
            Fileinfo downloadFileinfo = fileinfoService.findFileinfoByFileCode(fileCode);
            //获取文件保存的真实路径
            String filePath = downloadFileinfo.getFilePath();
            inputStream = new FileInputStream(filePath);
            //解决下载时中文名称乱问问题
            fileName =  new String(downloadFileinfo.getFileName().getBytes("UTF-8"),"iso-8859-1");
            return "download";
        }
        
        @Override
        public void setSession(Map<String, Object> arg0) {
            this.session=arg0;
        }
    
        @Override
        public void setServletRequest(HttpServletRequest arg0) {
            this.request=arg0;
        }
    }

      

      UserinfoAction:

    package cn.zzsxt.udisk.action;
    
    import java.util.Map;
    
    import javax.servlet.ServletContext;
    
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.interceptor.SessionAware;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    import cn.zzsxt.udisk.model.Userinfo;
    import cn.zzsxt.udisk.service.IUserinfoService;
    import cn.zzsxt.udisk.service.impl.UserinfoServiceImpl;
    
    public class UserinfoAction extends ActionSupport implements SessionAware{
        private Userinfo user;
        private IUserinfoService uesrinfoService = new UserinfoServiceImpl();
        private Map<String,Object> session;
        public Userinfo getUser() {
            return user;
        }
    
        public void setUser(Userinfo user) {
            this.user = user;
        }
        /**
         * 注册
         * @return
         * @throws Exception
         */
        public String doRegister() throws Exception {
            //获取服务器的upload目录
            ServletContext servletContext = ServletActionContext.getServletContext();
            String path =  servletContext.getRealPath("/upload");
            int count = uesrinfoService.doRegister(user,path);
            if(count>0){
                return this.SUCCESS;
            }
            return this.ERROR;
        }
        
        public String doLogin() throws Exception {
            Userinfo loginUser = uesrinfoService.doLogin(user);
            if(loginUser!=null){
                //将用户信息保持到session中
                session.put("loginUser", loginUser);
                return "list";
            }
            return this.LOGIN;
        }
    
        @Override
        public void setSession(Map<String, Object> arg0) {
            this.session=arg0;
        }
    }

      

      FileinfoServiceImpl:

    package cn.zzsxt.udisk.service.impl;
    
    import java.io.File;
    import java.util.List;
    
    import org.apache.commons.io.FileUtils;
    
    import cn.zzsxt.udisk.commons.MD5Utils;
    import cn.zzsxt.udisk.dao.IFileinfoDao;
    import cn.zzsxt.udisk.dao.impl.FileinfoDaoImpl;
    import cn.zzsxt.udisk.model.Fileinfo;
    import cn.zzsxt.udisk.model.Userinfo;
    import cn.zzsxt.udisk.service.IFileinfoService;
    
    public class FileinfoServiceImpl implements IFileinfoService {
        private IFileinfoDao fileinfoDao = new FileinfoDaoImpl();
        @Override
        public List<Fileinfo> findFileinfoByUserId(int userId) {
            return fileinfoDao.findFileinfoByUserId(userId);
        }
        /**
         * 上传文件
         * 1.将文件上传到服务器端
         * 2.将文件信息添加到数据库中
         */
        @Override
        public int uploadFile(Fileinfo[] file, Userinfo user,String path,File[] upload) throws Exception{
            //将文件信息上次到服务器端
            long totalSize=0,freeSize=32*1024*1024,usedSize=0; //此处freeSize初始化设置值,因为第一次进来listFiles()方法一直返回为空,fressSize一直为0,
            //普通用户空间总大小为32M,VIP用户空间总大小128M      最下面判断剩余空间和文件大小,就一直抛异常。 并且要给listFiles()方法后面的循环遍历加一个
            if(user.getUserType()==1){//普通用户            判断是否为空,如果为空执行的话会错误。  服务器每关闭一次,所有数据清空一次,所以没有那个路径,
                totalSize = 32*1024*1024;//总字节数           导致第一次进来listFiles()返回为空
            }else if(user.getUserType()==2){//VIP用户
                totalSize = 128*1024*1024;
            }
            String userDirStr = path+"upload\"+user.getUserName();
            File userDir = new File(userDirStr);//用户上传文件的文件夹
            File[] fs = userDir.listFiles();//获取该目录下的所有文件
            //统计该用户已用空间大小
         if(fs!=null){
       for (File f : fs) {    usedSize+=f.length();    }    freeSize = totalSize-usedSize;//计算剩余空间大小
        }
    //统计上传文件的总大小 long uploadTotalSize=0; for(File uploadFile:upload){ long length = uploadFile.length();//上传单文件的大小 if(user.getUserType()==1&&length>1*1024*1024){//普通用户 throw new Exception("普通用户单文大小不能超过1M!"); } if(user.getUserType()==2&&length>2*1024*1024){ throw new Exception("VIP用户单文大小不能超过2M!"); } uploadTotalSize+=length; } //上传文件大于剩余空间,抛出异常 if(uploadTotalSize>freeSize){ throw new Exception("剩余空间不足!"); } int count=0; //上传文件 for(int i=0;i<upload.length;i++){ File uploadFile = upload[i]; Fileinfo f = file[i]; //将文件上传到服务器端 FileUtils.copyFile(uploadFile, new File(userDir,f.getFileName())); //将文件信息添加到数据库中 //对真实路径进行加密 String fileCode = MD5Utils.createMD5(f.getFilePath()); f.setFileCode(fileCode); count = fileinfoDao.addFileinfo(file[i]); } return count; } /** * 移除文件: * 1.从服务器端用户上传目录下移除文件 * 2.从数据库中删除文件信息 */ @Override public int removeFile(int fileId) { //根据文件编号查询文件详情信息 Fileinfo fileinfo = fileinfoDao.findFileinfoById(fileId); String filePath = fileinfo.getFilePath();//获取文件保存的真实路径 File file = new File(filePath); if(file.exists()){ file.delete();//删除文件 } //从数据库中删除文件信息 return fileinfoDao.deleteFileinfo(fileId); } @Override public Fileinfo findFileinfoByFileCode(String fileCode) { return fileinfoDao.findFileinfoByFileCode(fileCode); } }

      

       UserinfoServiceImpl:

    package cn.zzsxt.udisk.service.impl;
    
    import java.io.File;
    
    import cn.zzsxt.udisk.commons.MD5Utils;
    import cn.zzsxt.udisk.dao.IUserinfoDao;
    import cn.zzsxt.udisk.dao.impl.UserinfoDaoImpl;
    import cn.zzsxt.udisk.model.Userinfo;
    import cn.zzsxt.udisk.service.IUserinfoService;
    
    public class UserinfoServiceImpl implements IUserinfoService {
        private IUserinfoDao userinfoDao = new UserinfoDaoImpl();
        /**
         * 注册需要对密码进行MD5密码
         */
        @Override
        public int doRegister(Userinfo user,String path) {
            String oldPass = user.getUserPass();
            //对用户输入的密码进行加密
            String newPass = MD5Utils.createMD5(oldPass);
            user.setUserPass(newPass);
            //在服务器端创建一个与用户名相同的文件夹,用于保存该用户上次的文件
            File uploadDir = new File(path+"/"+user.getUserName());
            if(!uploadDir.exists())
                uploadDir.mkdirs();
            return userinfoDao.addUser(user);
        }
        
        /**
         * 登陆
         */
        @Override
        public Userinfo doLogin(Userinfo user) {
            //对用户输入的密码进行加密
            String oldPass = user.getUserPass();
            //对用户输入的密码进行加密
            String newPass = MD5Utils.createMD5(oldPass);
            user.setUserPass(newPass);
            return userinfoDao.doLogin(user);
        }
    
    }

      

      

      

  • 相关阅读:
    P1268 树的重量
    P2419 [USACO08JAN]牛大赛Cow Contest
    P1306 斐波那契公约数
    P2905 [USACO08OPEN]农场危机Crisis on the Farm
    P1081 开车旅行
    P2906 [USACO08OPEN]牛的街区Cow Neighborhoods
    P1550 [USACO08OCT]打井Watering Hole
    P2746 [USACO5.3]校园网Network of Schools
    P1613 跑路
    【BZOJ4868】期末考试(整数三分)
  • 原文地址:https://www.cnblogs.com/kuangzhisen/p/7360690.html
走看看 - 开发者的网上家园