码迷,mamicode.com
首页 > 编程语言 > 详细

【j2ee spring】38、巴巴运动网的产品文件的上传

时间:2015-07-10 11:20:13      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:j2ee   巴巴运动网   spring4   hibernate4   struts2   

巴巴运动网的产品文件的上传

1、项目图解

技术分享

技术分享

技术分享

2、我们开始做我们的相应的功能模块
页面的素材我会上传的,链接是:http://download.csdn.net/detail/cutter_point/8803985

上传文件的接口类与实现

/**
 * 功能:这个是文件业务处理的功能接口
 * 时间:2015年5月25日09:29:56
 * 文件:UploadFileService.java
 * 作者:cutter_point
 */
package com.cutter_point.service.uploadfile;

import java.util.List;

import com.cutter_point.service.base.DAO;

public interface UploadFileService extends DAO
{
    //这里面定义ProductTypeService专有的方法
    /**
     * 定义upload的获取路径的方法
     * @param ids[]
     * @return List 返回String类型的文件路径集合
     */
    public List<String> getFilepath(Integer[] ids);
}

/**
 * 功能:这是文件管理的服务类
 * 文件:UploadFileServiceBean.java
 * 时间:2015年5月25日09:32:38
 * 作者:cutter_point
 */
package com.cutter_point.service.uploadfile.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cutter_point.service.base.DaoSupport;
import com.cutter_point.service.uploadfile.UploadFileService;

//为这个类的每个方法添加事务,并且把这个类交给spring托管
@Service
@Transactional
public class UploadFileServiceBean extends DaoSupport implements UploadFileService
{
    //有一个方法可以根据id数组来批量获取数据
    @SuppressWarnings("unchecked")
    public List<String> getFilepath(Integer[] ids)
    {
        //首先ids不是空的,那么就可以执行下面操作
        if(ids != null && ids.length > 0)
        {
            Session session = this.sessionFactory.getCurrentSession();  //得到数据库的连接
            StringBuilder sql = new StringBuilder();
            //我们把相应的数据要一个一个地取出来,就得拼接SQL语句
            for(int i = 0; i < ids.length; ++i)
            {
                sql.append(" ?").append(",");
            }
            sql.deleteCharAt(sql.length() - 1); //去掉最后的“,”
            //执行语句得到相应结果
            Query query = session.createSQLQuery("select o.filepath from uploadfile o where id in (" + sql + ")");
            for(int i = 0; i < ids.length; ++i)
            {
                query.setParameter(i, ids[i]);  //为每个?依次填入相应的值
            }
            return query.list();        //返回的结果集
        }
        return null;
    }

}

技术分享

文件的显示界面uploadfilelist.jsp

<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>上传文件显示</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="/css/vip.css" type="text/css">
<script type="text/javascript">
    //到指定的分页页面
    function topage(page)
    {
        document.getElementById("page").value = page;
        var obj = document.getElementsByName("form1").item(0).submit();
    }

    function allselect()
    {

        var selectall = document.getElementsByName("all").item(0);  //获取得到全选按钮
        var selecteveryone = document.getElementsByName("fileids");
        //判断全选按钮是否被选中
        //如果被选中了,那么我们用循环进行和全选复选框同步为一样的
        for(var i = 0; i < selecteveryone.length; ++i)
        {
            //吧选项一个一个地进行同步一样的
            selecteveryone[i].checked = selectall.checked;
        }
    }

    function deleteFiles()  //为了把表单提交到相应的路径
    {
        var obj = document.getElementsByName("form1").item(0);
        obj.action = "delete-filemanage";
        obj.method = "post";
        obj.submit();
    }
</script>
<SCRIPT language=JavaScript src="/js/FoshanRen.js"></SCRIPT>
</head>

<body bgcolor="#FFFFFF" text="#000000" marginwidth="0" marginheight="0">
<s:form name="form1" action="uploadfilelist" method="post">
<s:hidden id="page" name = "page" />
  <table width="98%" border="0" cellspacing="1" cellpadding="2" align="center">
    <tr ><td colspan="4" bgcolor="6f8ac4" align="right">
        <%@ include file="../share/fenye.jsp" %>
   </td></tr>
    <tr>
      <td width="8%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">选择</font></div></td>
      <td width="10%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">代号</font></div></td>
      <td width="60%" bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">文件</font></div></td>
      <td width="22%" nowrap bgcolor="6f8ac4"> <div align="center"><font color="#FFFFFF">上传时间</font></div></td>
    </tr>
<!---------------------------LOOP START------------------------------>
<s:iterator value="#request.pageView.records" var="entry">
    <tr> 
      <td bgcolor="f5f5f5"> 
        <div align="center">
            <INPUT TYPE="checkbox" NAME="fileids" value="<s:property value="#entry.id" />" />
        </div>
      </td>
      <td bgcolor="f5f5f5"> 
        <div align="center"><s:property value="#entry.id" /></div>
      </td>
      <td bgcolor="f5f5f5"> 
        <div align="center">
            <a href="<s:property value="#entry.filepath" />" target="_blank"><s:property value="#entry.filepath" /></a>
        </div>
      </td>
      <td bgcolor="f5f5f5"> 
        <div align="center"><s:property value="#entry.uploadtime" /></div>
      </td>
    </tr>
</s:iterator>
    <!----------------------LOOP END------------------------------->
    <tr>
      <td bgcolor="f5f5f5" colspan="4" align="center"><table width="100%" border="0" cellspacing="1" cellpadding="3">
          <tr> 
            <td width="10%"><INPUT TYPE="checkbox" NAME="all" onclick="javascript:allselect()">全选/反选</td>
              <td width="85%">
              <input type="button" class="frm_btn" onClick="javascript:deleteFiles()" value=" 删 除 "> &nbsp;&nbsp;
            </td>
          </tr>
        </table></td>
    </tr>
  </table>
</s:form>
</body>
</html>

文件显示UploadFileAction.java

/**
 * 功能:这个是文件显示的控制器
 * 时间:2015年5月26日08:36:01
 * 文件:UploadFileAction.java
 * 作者:cutter_point
 */
package com.cutter_point.web.action.uploadfile;

import java.util.LinkedHashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cutter_point.bean.PageView;
import com.cutter_point.bean.uploadfile.UploadFile;
import com.cutter_point.service.uploadfile.UploadFileService;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Scope("prototype")
public class UploadFileAction extends ActionSupport implements ServletRequestAware
{
    private static final long serialVersionUID = 7754191209036170135L;
    //业务处理spring注入
    @Resource
    private UploadFileService uploadFileService;
    //通过实现接口获取相应的request
    private HttpServletRequest request;
    private String filepath;    //文件保存的路径
    private int page;       //当前的页面值

    @Override
    public String execute() throws Exception
    {
        /*
         * 1、分页的pageView的初始化
         * 2、初始化每页的第一个索引的初始值
         * 3、排序的规则(id, desc)
         * 4、查询的结果集
         */
        PageView<UploadFile> pv = new PageView<>(12, this.getPage());
        //2、初始化第一个索引值,也就是得到当前页面的值,然后-1*每页长度
        int firstindex = (pv.getCurrentpage() - 1) * pv.getMaxresult();
        //3、初始化排序顺序
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("id", "desc");  //按id号的倒序排序
        //得到结果集
        pv.setQueryResult(uploadFileService.getScrollData(UploadFile.class, firstindex, pv.getMaxresult(), orderby));
        request.setAttribute("pageView", pv);
        return "list";
    }

    @Override
    public void setServletRequest(HttpServletRequest arg0)
    {
        this.request = arg0;
    }

    public String getFilepath()
    {
        return filepath;
    }

    public void setFilepath(String filepath)
    {
        this.filepath = filepath;
    }

    public int getPage()
    {
        return page < 1 ? 1 : page;
    }

    public void setPage(int page)
    {
        this.page = page;
    }

    public UploadFileService getUploadFileService()
    {
        return uploadFileService;
    }

    public void setUploadFileService(UploadFileService uploadFileService)
    {
        this.uploadFileService = uploadFileService;
    }
}

文件上传界面uploadUI.jsp

<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>文件上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../css/vip.css" type="text/css">
<SCRIPT type="text/javascript" src="../../js/FoshanRen.js"></SCRIPT>
<script type="text/javascript">
function checkfm(form)
{   
    //这个是在客户端判断是不是需求的文件格式
    var uploadfile = document.getElementsByName("uploadfile").item(0).value;    //获取到这个属性的值
    //去掉空格
    while(uploadfile.indexOf(" ") != -1)
    {
        uploadfile = uploadfile.replace(" ", "");//吧" "替换为""
    }

    uploadfile = uploadfile.toLowerCase();
    //只要文件名不是空的
    if(uploadfile != "")
    {
        var types = ["jpg","gif","bmp","png","exe","doc","pdf","txt","xls","ppt","swf","docx"];
        //var ext = uploadfile.substr(uploadfile.lastIndexOf(".")); 
        var two = uploadfile.split(".");
        //后缀
        var ext = two[two.length - 1];
        var sing = false;   //判断是否成功
        for(var i = 0; i < types.length; ++i)
        {
            if(ext == types[i])
            {
                sing = true;
            }
        }
        if(!sing)
        {
            alert("只允许上传图片/flash动画/word文件/exe文件/pdf文件/TxT文件/xls文件/ppt文件");
        }
    }
    return true;

}
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<s:form action="upload-filemanage" method="post" enctype="multipart/form-data" onsubmit="return checkfm(this)">
  <table width="90%" border="0" cellspacing="2" cellpadding="3" align="center">
    <tr bgcolor="6f8ac4"><td colspan="2"  > <font color="#FFFFFF">上传文件:</font></td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td width="22%" > <div align="right">文件:</div></td>
      <td width="78%"> <input type="file" name="uploadfile" size="50"><br/>
      只允许上传图片/flash动画/word文件/exe文件/pdf文件/TxT文件/xls文件/ppt文件
      </td>
    </tr>
    <tr bgcolor="f5f5f5"> 
      <td colspan="2"> <div align="center"> 
          <input type="submit" value=" 确 定 " class="frm_btn">
        </div></td>
    </tr>
  </table>
</s:form>
<br>
</body>
</html>

文件上传UploadfileManageAction.java

/**
 * 功能:这个是文件的管理动作
 * 时间:2015年5月25日09:45:53
 * 文件:UploadfileManageAction.java
 * 作者:cutter_point
 */
package com.cutter_point.web.action.uploadfile;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cutter_point.bean.uploadfile.UploadFile;
import com.cutter_point.service.uploadfile.UploadFileService;
import com.cutter_point.utils.SiteUrl;
import com.opensymphony.xwork2.ActionSupport;


@Controller
@Scope("prototype")
public class UploadfileManageAction extends ActionSupport implements ServletRequestAware
{
    private static final long serialVersionUID = -815949461566116034L;
    //业务处理spring注入
    @Resource
    private UploadFileService uploadFileService;
    //通过实现接口获取相应的request
    private HttpServletRequest request;
    //上传文件需要的属性
    private File uploadfile;
    private String uploadfileFileName;  //上传文件的名字
    private String uploadfileContentType;   //这个是相应的文件类型在G:\Program Files\Apache Software Foundation\Tomcat 8.0\conf\web.xml中的文件类型对应的东西
    //从界面接受被选中要删除的id号
    private Integer[] fileids;

    /**
     * 上传界面显示
     * @return
     */
    public String uploadUI()
    {
        return "uploadUI";
    }

    /**
     * 保存上传文件
     * @return
     */
    public String upload() throws Exception
    {
        if(!this.validateFileType("uploadfile"))
        {
            request.setAttribute("message", "上传文件格式不对");
            return "error";
        }

        if(this.getUploadfile() != null && this.getUploadfile().length() > 0)
        {
            //如果文件确实上传上来了
            //获取完全的真实路径G:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\ 这个就是realpath
            String realpath = ServletActionContext.getServletContext().getRealPath("/images");
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy\\MM\\dd\\HH"); //设定日期的格式
            //设定文件的保存格式
            String realpathdir = realpath + "upload\\" + dateformat.format(new Date()); //得到系统的时间,以及我们要保存的文件所在位置
            File savedir = new File(realpathdir);
            if(!savedir.exists())//如果文件夹不存在的话
            {
                savedir.mkdirs();   //创建相应的文件夹
            }
            //获取相应的文件后缀
            //String ext = "." + this.getUploadfileContentType();   //得到相应的文件后缀,带.的
            //显示图片的时候我们有一个相应的路径,类似这个样../images/upload/2015/5/25/19
            String showpath = ".." + savedir.toString().substring(savedir.toString().lastIndexOf("\\images"));
            //这里保存文件的名称的时候,我们就用原来的名称
            String uploadname = this.getUploadfileFileName();
            //初始化输出流,和输入流
            String savefilepath = savedir + "\\" + uploadname;
            //设定实体的各项属性,保存显示的路径,用来web显示
            UploadFile uploadFile = new UploadFile(showpath + "\\" + uploadname);
            //使用IO流保存文件
            FileOutputStream fos = null;    //输出流
            FileInputStream fis = null; //输入流
            try
            {
                fos = new FileOutputStream(savefilepath);
                fis = new FileInputStream(this.getUploadfile());
                //设定字节缓存池和长度
                byte[] buffer = new byte[2048];
                int len = 0;    //每次上传文件的长度
                while((len = fis.read(buffer)) != -1)
                {
                    //调用输出流到相应的地方
                    fos.write(buffer, 0, len); //要输出的字节,开始的位置,结束的位置
                }
            } 
            catch (Exception e)
            {
                System.out.println("文件上传失败");
                e.printStackTrace();
            }
            finally
            {
                this.close(fos, fis);
            }
            //保存到数据库
            uploadFileService.save(uploadFile);
            request.setAttribute("message", "上传文件成功");
            //跳转到文件上传成功的界面
            return "fileuploadfinish";
        }
        else
        {
            request.setAttribute("message", "请上传文件");
        }
        return "message";
    }

    public String delete()
    {
        //获取要删除的路径对象
        List<String> files = uploadFileService.getFilepath(this.getFileids());
        //我们获取的id号不为空,才会删除
        if(files != null)
        {
            //循环删除file:..\images\\upload\2015\05\26\10\2.5年, 从0-阿里.docx
            for(String file : files)
            {
                //获取真实路径,通过真实路径删除
                //获取完全的真实路径G:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\babaSport_1100_brand\images\2015\05\26\15\.. 这个就是realpath
                String hpath = file.substring(9);
                System.out.println("help查询真实路径:" + hpath);
                String realpath = ServletActionContext.getServletContext().getRealPath("/images");
                System.out.println("真实路径是:" + realpath);
                //我们通过File指向这个文件
                File deletefile = new File(realpath + hpath);
                System.out.println("要删除的路径是:" + deletefile);
                //判断这个文件是不是存在
                if(deletefile.exists())
                {
                    //如果存在的话删除掉
                    deletefile.delete();
                }
            }
            //从数据库中删除相应的文件
            uploadFileService.delete(UploadFile.class, this.getFileids());
        }

        request.setAttribute("urladdress", SiteUrl.readUrl("control.uploadfile.list"));
        request.setAttribute("message", "删除成功");
        return "message";
    }

    //管理文件流
    protected void close(FileOutputStream fos, FileInputStream fis)
    {
        if(fis != null)
        {
            try
            {
                fis.close();
            } 
            catch (Exception e)
            {
                System.out.println("关闭文件输入流失败");
                e.printStackTrace();
            }
        }

        if(fos != null)
        {
            try
            {
                fos.close();
            } 
            catch (Exception e)
            {
                System.out.println("关闭文件输出流失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断得到文件类型是不是我们允许的类型
     * @param propertyName
     * @return
     * @throws Exception
     */
    protected boolean validateFileType(String propertyName) throws Exception
    {
        //得到相应类的所有属性,字段
        PropertyDescriptor[] propertydesc = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
        boolean exsit = false;  //判断属性是否存在的变量
        for(PropertyDescriptor property : propertydesc)     //相当于类里面的属性,字段
        {
            if(property.getName().equals(propertyName))
            {
                //名字得到匹配的话,属性是存在
                exsit = true;
                Method method = property.getReadMethod();   //取得用来读取属性的方法,也就是取得get方法
                if(method != null)
                {
                    File file = (File) method.invoke(this); //执行这个方法
                    //文件是存在的
                    if(file != null && file.length() > 0)
                    {
//                      List<String> allowType = Arrays.asList("image/bmp", "image/png", "image/gif", "image/jpeg", "image/pjpe", "image/jpg", 
//                              "application/x-shockwave-flash", "application/octet-stream", "application/msword", "application/pdf", "text/plain",
//                              "application/vnd.ms-excel", "<extension>ppt</extension>", 
//                              "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                        //验证后缀
//                      List<String> allowExtension = Arrays.asList("bmp","png","gif","jpeg","pjpe",
//                              "jpg","exe","doc","pdf","txt","xls","ppt","swf","docx");
                        List<String> allowType = new ArrayList<String>();
                        Properties p = SiteUrl.readallowtyope();
                        for(Object key : p.keySet())
                        {
                            String value = (String) p.get(key);
                            String[] values = value.split(","); //分割得到的属性
                            for(String v : values)
                            {
                                //吧所有的类型添加进去
                                allowType.add(v.trim());    //去掉空格
                            }
                        }

                        //获取的结果是不包含.的
                        String ext = this.getUploadfileFileName().substring(this.getUploadfileFileName().lastIndexOf(".") + 1).toLowerCase();
                        boolean b = allowType.contains(this.getUploadfileContentType().toLowerCase());  //判断类型是不是在里面,用小写比较
                        b = b && p.keySet().contains(ext);
                        return b;
                    }
                }
                else
                {
                    //如果文件没有穿进来
                    new RuntimeException(propertyName + "属性的getter方法不存在");
                }
            }
        }

        if(!exsit)
            new RuntimeException(propertyName + "属性的不存在");
        return true;    //如果没有上传文件的话,还是让他通过
    }

    public File getUploadfile()
    {
        return uploadfile;
    }

    public void setUploadfile(File uploadfile)
    {
        this.uploadfile = uploadfile;
    }

    public UploadFileService getUploadFileService()
    {
        return uploadFileService;
    }

    public void setUploadFileService(UploadFileService uploadFileService)
    {
        this.uploadFileService = uploadFileService;
    }

    public String getUploadfileFileName()
    {
        return uploadfileFileName;
    }

    public void setUploadfileFileName(String uploadfileFileName)
    {
        this.uploadfileFileName = uploadfileFileName;
    }

    @Override   //获取到相应的request
    public void setServletRequest(HttpServletRequest arg0)
    {
        this.request = arg0;
    }

    public String getUploadfileContentType()
    {
        return uploadfileContentType;
    }

    public void setUploadfileContentType(String uploadfileContentType)
    {
        this.uploadfileContentType = uploadfileContentType;
    }

    public Integer[] getFileids()
    {
        return fileids;
    }

    public void setFileids(Integer[] fileids)
    {
        this.fileids = fileids;
    }
}

上传报错error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片上传出错</title>
</head>
<body>
<center>${message}<br><a href="javascript:history.go(-1)">返回</a>
</center>
</body>
</html>

上传成功

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片上传结束</title>
<SCRIPT LANGUAGE="JavaScript">

    function writefile()
    {
    /*
        var imagepath="${pageContext.request.contextPath}${imagepath}";
        window.opener.writimage(imagepath);
        window.close();
        */
    }

</SCRIPT>
</head>
<body onload="writefile()">
<center>${message}</center>
</body>
</html>

上传的时候表单bean

/**
 * 功能:这个是用来存放文件信息的实体
 * 时间:2015年5月25日08:57:37
 * 文件:UploadFile.java
 * 作者:cutter_point
 */
package com.cutter_point.bean.uploadfile;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@SequenceGenerator(name="seq_2", sequenceName="seq_2", allocationSize=1, initialValue=1)    //oracle的id自增长,通过一个序列自增长,起始是1,每次增长1
public class UploadFile implements Serializable
{
    private static final long serialVersionUID = 4694353267624420027L;
    //文件的属性有ID,路径,添加日期
    private Integer id;
    private String filepath;
    private Date uploadtime = new Date();

    public UploadFile()
    {
    }

    public UploadFile(String filepath)
    {
        this.filepath = filepath;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_2")    //自增长
    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    /**
     * 这个是文件的路径
     * 格式: /images/brand/年/月/日/时/aaaa.gif  长度设定可以是80
     * @return
     */
    @Column(length = 200, nullable=false)
    public String getFilepath()
    {
        return filepath;
    }

    public void setFilepath(String filepath)
    {
        this.filepath = filepath;
    }

    @Temporal(TemporalType.TIMESTAMP)
    public Date getUploadtime()
    {
        return uploadtime;
    }

    public void setUploadtime(Date uploadtime)
    {
        this.uploadtime = uploadtime;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((filepath == null) ? 0 : filepath.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UploadFile other = (UploadFile) obj;
        if (filepath == null)
        {
            if (other.filepath != null)
                return false;
        } else if (!filepath.equals(other.filepath))
            return false;
        return true;
    }
}

3、struts2的配置

<?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>
    <include file="struts-default.xml" />
    <constant name="struts.ObjectFactory" value="spring" /> <!--    表示这里面的action由spring进行创建 -->
    <constant name="struts.devMode" value="true" />
    <!--解决乱码    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />

    <package name="control" namespace="/control" extends="struts-default">
        <global-results>
            <result name="message">/page/share/message.jsp</result>
        </global-results>
        <action name="center-*"><!-- 直接跳转,不需要经过class的验证,默认返回success -->
            <result name="success">/page/controlcenter/{1}.jsp</result>
        </action>
        <!-- 产品类别展示 -->
        <action name="producttypelist" class="productTypeAction" method="execute">
            <result name="list">/page/product/producttypelist.jsp</result>
        </action>
        <!-- 产品类别管理 -->
        <action name="*-producttypemanage" class="productTypeManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_productType.jsp</result>
        </action>
        <action name="producttypemanage-*" class="productTypeManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_productType.jsp</result>
        </action>
        <!-- 品牌类别展示 -->
        <action name="brandlist" class="brandAction" method="execute">
            <result name="list">/page/product/brandlist.jsp</result>
        </action>
        <!-- 品牌类别管理 -->
        <action name="*-brandmanage" class="brandManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_brand.jsp</result>
        </action>
        <action name="brandmanage-*" class="brandManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_brand.jsp</result>
        </action>
        <!-- 文件展示 -->
        <action name="uploadfilelist" class="uploadFileAction" method="execute">
            <result name="list">/page/uploadfile/uploadfilelist.jsp</result>
        </action>
        <!-- 文件上传管理 -->
        <action name="*-filemanage" class="uploadfileManageAction" method="{1}">
            <result name="{1}">/page/uploadfile/{1}.jsp</result>
            <result name="fileuploadfinish">/page/uploadfile/fileuploadfinish.jsp</result>
            <result name="error">/page/uploadfile/error.jsp</result>
        </action>
        <!-- 产品分页展示 -->
        <action name="productlist" class="productAction" method="execute">
            <result name="list">/page/product/productlist.jsp</result>
        </action>
        <!-- 产品管理 -->
        <action name="*-productmanage" class="productManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_product.jsp</result>
            <result name="type{1}">/page/product/productTypeSelect.jsp</result>
        </action>
        <action name="productmanage-*" class="productManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_product.jsp</result>
        </action>
        <!-- 产品样式分页展示 -->
        <action name="productstylelist" class="productStyleAction" method="execute">
            <result name="list">/page/product/productstylelist.jsp</result>
        </action>
        <!-- 产品样式管理 -->
        <action name="*-productstylemanage" class="productStyleManageAction" method="{1}UI">
            <result name="{1}">/page/product/{1}_productstyle.jsp</result>
        </action>
        <action name="productstylemanage-*" class="productStyleManageAction" method="{1}">
            <result name="{1}">/page/product/{1}_productstyle.jsp</result>
        </action>

    </package>

    <!-- #####################################前台显示######################################## -->
    <package name="front" namespace="/" extends="control">
        <action name="frontProductlist" class="frontProductAction" method="execute">
            <result name="list_image">/page/product/frontpage/productlist.jsp</result>
            <result name="list_imagetext">/page/product/frontpage/productlist_text.jsp</result>
        </action>
        <action name="switch-*" class="productSwitchAction" method="{1}">
            <result name="{1}">/page/product/frontpage/{1}.jsp</result>
        </action>
        <!-- 产品的展示 -->
        <action name="viewproduct" class="viewProductAction" method="execute">
            <result name="product">/page/product/frontpage/productview.jsp</result>
        </action>
        <!-- 购物车 -->
        <action name="shopping-cart" class="cartAction" method="execute">
            <result name="cart">/page/shopping/cart.jsp</result>
        </action>
        <!-- 购物车管理 -->
        <action name="cart-*" class="cartManageAction" method="{1}">
            <result type="redirectAction" name="cart">shopping-cart</result>
        </action>
    </package>
</struts>

4、接下来我们测试一下页面的效果

我们访问这个网站

http://localhost:8080/ babaSport_1300_brand_file/control/center-main

技术分享

技术分享

技术分享

技术分享

技术分享

5、总结

这里做的就是文件的上传,借助struts2框架可以很容易实现,当然我们也可以不用框架来实现,使用java-web的功能,加上几个jar包就可以上传了

版权声明:本文为博主原创文章,未经博主允许不得转载。

【j2ee spring】38、巴巴运动网的产品文件的上传

标签:j2ee   巴巴运动网   spring4   hibernate4   struts2   

原文地址:http://blog.csdn.net/cutter_point/article/details/46827697

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!