Struts2框架学习总结

* struts 2.0学习
   * 创建web工程
   *  引入jar包
       * mysql的驱动包
       * struts2需要的jar包,apps文件夹里 blank.war 解压,拷贝lib里面的jar包, 复制web.xml文件到WEB-INF目录下,复制strust.xml文件到src目录下,picture.xml文件放在src目录下,user.xml文件配置放在src目录下

       * 导入css文件夹及文件,导入jslib文件夹及文件,导入layer 1.8.5文件夹和文件。

   * 包的介绍

   * 总结
    1、OGNL标签使用,引入 <%@taglib uri="/struts-tags" prefix="s" %>
    <s:iterator /> 遍历
    <s:property  /> 输出
        判断有图片时才会显示用户图片列表
    <s:if test="%{#PICTURES.size()>0}"></s:if>

    2、form表单上传文件需要使用 enctype="multipart/form-data" 
    multipart/form-data:制定传输数据的特殊类型(二进制形式),上传的非文本的内容,比如图片或是是mp3
    ext/plain ---纯文本编码传输,不能用于上传文件
    
    上传文件图片在eclipse-workspace\.metadata里搜索

    3、前端提示框 alert(""),可以通过它一步步检查错误的位置
       split()方法分离用户名和id,给后端提交用户id,前端确认是否删除用户。
    
    4、Action用来存放数据的两种方式:
    (1)Value Stack 值栈,不用加#;
    (2)Stack Context,访问加#,通过<s:debug></s:debug> 以查看值栈结构和存储值)        
    
    5、用户列表和用户图片列表保存范围:ActionContext (之前常用的是page,request,seesion,application四个范围)
    
    6、Action中的3种获取前端数据的方式
        (1)注入属性(不用改前端变量名)。
        (2)Domain Model 这是一般常用的方式(需要改前端标量名)。
        (3)ModelDriven

    7、三种解决绝对路径方法:
    (1)Java代码:request.getContextPath()
    (2)EL表达式:${pageContext.request.contextPath}
    (3)OGNL:<s:property value="#request.get('javax.servlet.forward.context_path')" />
    
    8、删除文件
      File myfile=new File(path);
      FileUtils.deleteQuietly();

    9、复制文件
         将源文件image复制到myfile目标文件里。
         FileUtils.copyFile(image, myfile);

   * 搭建strusts
    * 建立请求路径和action之间的关联
          * 创建strusts.xml文件,放置在src下
          * 文件内容如下:
        <?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.action.extension" value="action,,"></constant>
        <constant name="struts.devMode" value="true"></constant>
        <package name="all" namespace="" extends="struts-default">
        <global-results>
        <result name="list" type="redirectAction">
            <param name="namespace">/user</param>
            <param name="actionName">list</param>
        </result>
        </global-results>
        </package>
        <include file="user.xml"></include>
        <include file="picture.xml"></include>
        </struts>

    * 在web.xml文件配置
        <?xml version="1.0" encoding="UTF-8"?>
        <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

               <display-name>Struts Blank</display-name>
            <filter>
               <filter-name>struts2</filter-name>
               <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
               </filter>

               <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
            </filter-mapping>

            <welcome-file-list>
                <welcome-file>index.html</welcome-file>
            </welcome-file-list>

        </web-app>
    * 在picture.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>
        <package name="picture" namespace="/picture" extends="all">
        <action name="*" class="mypicture.PictureAction" method="{1}"></action>
        </package>
        </struts>


    * 在user.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>
        <package name="user" namespace="/user" extends="all">
         <action name="*" class="myuser.UserAction" method="{1}">
          <result name="success">/WEB-INF/user/userlist.jsp</result>
          <result name="modify">/WEB-INF/user/modify.jsp</result>
         </action>
        </package>
        </struts>


    * 测试:建空白jsp测试一下环境是否配置好。
    
    *  定义user javaBean接收表单数据,放置在myuser包下

    *  定义picture javaBean接收表单数据,放置在mypicture包下
    
    *  新建userAction类,继承ActionSupport类  重写execute方法。action中的处理请求的方法的签名是有要求public String execute()

    * 用户注册(参考register.jsp)
        <body>
        用户注册
        <br/>
        <br/>
        <form method="post" action="${pageContext.request.contextPath}/user/add">
        <table>
        <tr><td>用户名:</td><td><input type="text" name="user.userName"/></td></tr>
        <tr><td>密码:</td><td><input type="password" name="user.pwd"/></td></tr>
        <tr><td colspan="2"><input type="submit" value="注册"/></td></tr>
        </table>
        </form>
        <input type="hidden" name="isExists" value="0"/>
        <div id="msg"></div>
        <br/>
    * 检查用户是否存在,判读密码是否为空(参考register.jsp)
        $(function(){
            $("[name='user.userName']").blur(function(){
            if($.trim($(this).val())=="")
            {
             return;
            }
 $.post("${pageContext.request.contextPath}/user/checkExists",{"user.userName":$(this).val(),"user.pwd":""},function(data){
            $("[name='isExists']").val(data);
            if(data=="1")
                {
                 $("#msg").html("该用户名已经注册,请重新注册");
                }
            else
                {
                 $("#msg").html("恭喜,该用户名可以使用!");
                }
                });
            });
            $("[type='submit']").click(function(){
             if($.trim($("[name='user.userName']").val())=="")
             {
             $("#msg").html("用户名不能为空,请重新输入用户名");
             return false;
             }
             if($("[name='isExists']").val()=="1")
             {
             $("#msg").html("该用户名已经注册,请重新注册"); 
             return false;
             }
              if($.trim($("[name='user.pwd']").val())=="")
             {
             $("#msg").html("密码不能为空,请重新输入用户名");
             return false;
             }
             return true;
            });
            });

    * userAction接收前端提交账号密码,往数据库添加数据,从数据库中检查用户是否存在
            public String add() throws Exception {
            // TODO Auto-generated method stub
            dao.addUser(user);
            return "list";
            }
            public String checkExists() throws Exception {
        
            out=response.getWriter();
            if(dao.checkExists(user))
            {
            out.print("1");
            }
            else
            {
            out.print("0");
            }
            return null;
            }
    * userDAO代码,通过用户名和密码添加用户。
            public void addUser(User user) 
             {
             String sql="insert into users (userName,pwd) values (?,?)";
              try {
                ps=conn.prepareStatement(sql);
             ps.setString(1, user.getUserName());
             ps.setString(2, user.getPwd());
             ps.execute();
             conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
             }
        * 检查用户是否存在
            public boolean checkExists(User user)
            {
            sql="select * from users where userName=?";
            boolean flag=false;
            try {
            ps=conn.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ResultSet rs=ps.executeQuery();
            if(rs.next())
            {
                flag=true;
            }
            conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            return flag;
            }
    
    * 用户登录,检查用户名是否为空,密码是否为空。后台返回的值等于1代码,代码用户名和密码正确,等于0,代表用户名和密码不对。
            $(function(){
            $("[type='button']").click(function(){
            if($.trim($("[name='userName']").val())=="")
              {
            $("[name='userName']").select();
            $("[name='userName']").focus();
            $("#msg").html("请输入用户名!");
            return;
               }
            if($.trim($("[name='pwd']").val())=="")
               {
            $("[name='pwd']").select();
            $("[name='pwd']").focus();
            $("#msg").html("请输入密码!");
            return;
                }
$.post("${pageContext.request.contextPath}/user/checkLogin",{"user.userName":$("[name='userName']").val(),"user.pwd":$("[name='pwd']").val                ()},function(data){
                if(data=="1")
                {
                    location.href="${pageContext.request.contextPath}/main.jsp";
                }
                else
                {
                    $("#msg").html("用户名密码错误,请重新登录!");
                }
                });
                });
                });
            </script>
            </head>

        * checkAction代码,通过数据库查找,如果正确,返回1,并把用户保存到session中。

            public String checkLogin() throws Exception {
            try {
            PrintWriter out=response.getWriter();
            if(dao.checkLogin(user))
            {
                session.setAttribute("user", user);
                out.print("1");
            }
            else
            {
                out.print("0");
            }
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
        
            return null;
            }
    * 首页(main.jsp)显示用户是否登录,通过引入OGNL表达式 <%@taglib uri="/struts-tags" prefix="s" %>
            
            <body>
            <br/>
            <s:if test="#session.user==null">
             未登录
            </s:if>
            <s:else>
            当前登录用户:<s:property value="#session.user.userName"/>
            </s:else>
            <br/>
    * userDAO代码,通过查数据用户名和密码,正确返回真,错误返回假。
            public boolean checkLogin(User user)
            {
            boolean flag=false;
            sql="select * from users where userName=? and pwd=?" ;
            try {
            ps=conn.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getPwd());
            ResultSet rs=ps.executeQuery();
            if(rs.next())
            {
                flag=true;
            }
            conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            return flag;
            }
    * 用户列表显示(userAction),通过调用dao.getUsers();得到所有用户(数组方式),并保存到ActionContext 范围中,放入键USERLIST中,转向userlist.jsp
            public String list() 
            {
            ArrayList<User> list=dao.getUsers();
            //保护用户到ActionContext范围内
            ActionContext acx=ActionContext.getContext();
            acx.put("USERLIST",list);
            return SUCCESS;
            }

    * userDAO代码,从数据库查找所有用户,并返回用户数组list
            public ArrayList<User> getUsers()
            {
            sql="select * from users";
            ArrayList<User> list=new ArrayList<User>();
            try {
            ps=conn.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();
            while(rs.next())
            {
                User user=new User();
                user.setId(rs.getInt(1));
                user.setUserName(rs.getString(2));
                user.setPwd(rs.getString(3));
                list.add(user);
            }
             conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            return list;
            }
    * 前端userlist 通过OGNL表达式标签,遍历显示用户列表(注意action用来存放数据的两种方式:1、Value Stack 值栈,不用加#;2、Stack Context,访问加#,通过                    <s:debug></s:debug> 以查看值栈结构和存储值)        
        <br/>
        <table class="bordered">
        <tr><th>序号</th><th>用户名</th><th>密码</th><th>照片</th><th>删除</th><th>修改</th></tr>
        <s:iterator value="#USERLIST" id="cuser" status="s">
        <tr>
        <td><s:property value="#s.index+1"/></td>
        <td><s:property value="#cuser.userName"/></td>
        <td><s:property value="#cuser.pwd"/></td>
        <td><a href="#" class="picture" lang="<s:property value="#cuser.id"/>">照片</a></td>
        <td><a href="#" class="delete" lang="<s:property value="#cuser.id"/>!<s:property value="#cuser.userName"/>">删除</a></td>
        <td><a href="#" class="modify" lang="<s:property value="#cuser.id"/>">修改</a></td>
        </tr>
        </s:iterator>
        </table>
        <a href="${pageContext.request.contextPath}/main.jsp">返回首页</a>
        </body>
    *  删除用户
        * 前端代码,把用户id提交至delete.action,并转向userlist.jsp(参考userlist,split方法分离用户名和id,给后端提交用户id,前端确认是否删除用户名)
             $(".delete").click(function(){            
              var str=this.lang.split("!");
             if(!confirm("确认删除用户: " + str[1] + " 吗?"))
             {
              return;
             }
             $.post("${pageContext.request.contextPath}/user/delete.action",{"user.id":str[0]},function(){
                 alert("当前用户的id为:"+str[0]);
                 location.href="list.action";
                 
                 });
             }); 
        * delteAction代码,用Domain Model方式接收前端数据,(注意:Action中的3种获取前端数据的方式1.注入属性,2.Domain Model 这是一般常用的方式,3.ModelDriven)

            public String delete() {
            // TODO Auto-generated method stub
            dao.deleteUser(user);
            System.out.println(user.getId());
            return null;
            }

        * userDAO代码:通过用户id,删除用户
            public void deleteUser(User user)
            {
            sql="delete from users where id=?";
            try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1, user.getId());
            ps.execute();
            conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            }    
    *  修改用户
        * 前端userlist提交用户id,转向modify action
             $(".modify").click(function(){
             alert("转到modify.action用户id为"+ this.lang);
             location.href="${pageContext.request.contextPath}/user/modify.action?user.id="+this.lang;
                  });
        * modify action代码,接收用户id。并通过调用dao.getUserById方法,得到用户(用户名和密码),转向modify.jsp。
            public String modify()  {
            // TODO Auto-generated method stub
            user=dao.getUserById(user.getId());
            PictureDAO pdao=new PictureDAO();
            ArrayList<Picture> list=pdao.getPictures(user.getId(),"user");
            ActionContext ctx=ActionContext.getContext();
            ctx.put("PICTURES", list);
            return "modify";
            }
        * userDAO代码,通过id,查询数据库,返回一个用户。
            public User getUserById(int id)
            {
            sql="select * from users where id=?";
            User user=new User();
            try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs=ps.executeQuery();
            rs.next();
            user.setId(rs.getInt(1));
            user.setUserName(rs.getString(2));
            user.setPwd(rs.getString(3));
            conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            return user;
            }
        * modify.jsp 输入密码后,提交表单(用户名,密码和用户id),提交到save.action方法里。
            <form method="post" action="${pageContext.request.contextPath}/user/save.action">
            <table>
            <tr><td>用户名:</td><td><input type="text" name="user.userName" readonly value="<s:property value="user.userName"/>"/></td></tr>
            <tr><td>密码:</td><td><input type="password" name="user.pwd" value="<s:property value="user.pwd"/>"/></td></tr>
            <tr><td><input type="hidden" name="user.id" value="<s:property value="user.id"/>"/></td></tr>
            <tr><td colspan="2"><input type="submit" value="修改"/></td></tr>
            </table>
            </form>
        * save.action代码,获取前端提交的用户数据,通过调用dao.modifyUser()修改后,转回到uselist.jsp界面
            public String save()
            {
            dao.modifyUser(user);
            return "list";
            } 
        * userDAO代码:通过id更新用户名和密码。(因前端传的用户名是只读的,所以在前端只能更改密码)
            public void modifyUser(User user)
            {
            sql="update users set userName=?,pwd=? where id=?" ;
            try {
            ps=conn.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getPwd());
            ps.setInt(3, user.getId());
            ps.execute();
            conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            }
    * 上传图片
        * modify前端代码,提交表单(图片数据:图片名,图片uid即用户id)到picture里的add action方法里。
            <form method="post"  enctype="multipart/form-data" action="${pageContext.request.contextPath}/picture/add">
            <table>
            <tr><td>选择照片</td><td><input type="file" name="image"></tr>
            <tr><td>照片名称</td><td><input type="text" name="picture.name"/><td>
            <tr><td colspan="2"><input type="hidden" name="picture.uid" value="<s:property value="user.id"/>"/>
            <input type="submit" value="提交" /></td>
            </table>
            </form>    

        * add action代码,获取图片数据,通过application获取绝对路径,复制文件,并设置图片文件路径。调用dao.addPicture()图片数据添加到数据库。
            public String add()  
                {
                ServletContext app=ServletActionContext.getServletContext();
                String path=app.getRealPath("")+"/images";
                System.out.println(path);
                //新建文件用来存放上传的文件
                File myfile=new File(path,imageFileName);
                //如果文件上一级目录不存在,创建目录
                if(!myfile.getParentFile().exists())
                    {
                    myfile.getParentFile().mkdirs();
                    }
        
                try {
                    //保存上传文件,将源文件image复制到myfile目标文件里。
                    FileUtils.copyFile(image, myfile);
                    //设置文件路径
                    picture.setUrl("images/" + imageFileName);
                    dao.addPicture(picture);
                } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                }
                return "list";
                }
        * pictureDAO代码:图片数据添加到数据库。
                public void addPicture(Picture picture) 
                    {
                     try {
                       if (conn.isClosed()) {
                       conn = DBLib.getConnection();
                       }
                   } catch (SQLException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
                   }
                    String sql="insert into pictures (uid,name,url) values (?,?,?)";
                    try {
                    ps=conn.prepareStatement(sql);
                    ps.setInt(1, picture.getUid());
                    ps.setString(2, picture.getName());
                    ps.setString(3, picture.getUrl());
                    ps.executeUpdate();
                    conn.close();
                   } catch (SQLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                       }
                    }
            
    * 图片保存在ActionContext范围里,通过键PICTURES查找。(参考userListAction)
        public String modify()  {
        // TODO Auto-generated method stub
        user=dao.getUserById(user.getId());
        PictureDAO pdao=new PictureDAO();
        ArrayList<Picture> list=pdao.getPictures(user.getId(),"user");
        ActionContext ctx=ActionContext.getContext();
        ctx.put("PICTURES", list);
        return "modify";
        }

        * 显示用户图片列表模块删除照片功能
    
          * jsp请求提交表单,url为delete.action,数据为picture.id
         $(".delete").click(function(){
              var str=this.lang.split("!");
             if(!confirm("确认删除照片:[ " + str[1] + " ]吗?"))
             {
              return;
             }
              $.post("${pageContext.request.contextPath}/picture/delete",{"picture.id":str[0]},function(){
               location.href="${pageContext.request.contextPath}/user/list";
              });
         });
    * 实现通过id删除数据库表中数据,同时通过id删除图片文件(参考PictureAction,delete方法)
                
        *删除数据库表中数据(PictureDAO)
                public void deletePictrue(int id)
            {    
                    try {
                    if (conn.isClosed()) {
                    conn = DBLib.getConnection();
                    }
                } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String sql = "delete from pictures where id=?";
            try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            ps.executeUpdate();
            conn.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
                }
            }
        * //得到url(参考PictureDAO)
         public String getUrl(int id)
           {    
                   try {
               if (conn.isClosed()) {
                   conn = DBLib.getConnection();
               }
               } catch (SQLException e1) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
               }
               String sql = "select url from pictures where id=?";
               String url="";
               try {
               ps = conn.prepareStatement(sql);
               ps.setInt(1, id);
               ResultSet rs = ps.executeQuery();
               rs.next();
               url=rs.getString(1);
               conn.close();
               } catch (SQLException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
               }
            return url;
           }

        * //删除文件(参考PictureAction)
        public String delete()
           {
        //删除文件:数据库url值例如为images/1.png,还需要通过application得到真实路径。
        String url=dao.getUrl(picture.getId());
        ServletContext app=ServletActionContext.getServletContext();
        String path=app.getRealPath("")+"/"+url;
        File myfile=new File(path);
        FileUtils.deleteQuietly(myfile);
        
        //删除表中数据
        dao.deletePictrue(picture.getId());
        System.out.println(picture.getId());
        return null;
            }

    * 用户列表里和用户图片列表里分别通过得到用户id和图片id显示图片
     * 用户列表前端代码,在js代码下面导入

<script type="text/javascript" src="${pageContext.request.contextPath}/layer/layer.min.js"></script>(参考userList.jsp)

         $(".picture").click(function(){
         layer.use('extend/layer.ext.js');
 $.getJSON("${pageContext.request.contextPath}/picture/getPic.action",{"picture.uid":this.lang,"idType":"user"},function(data){
             layer.photos({
                   html:"",
                  json:data
                 });
             });
             });
         * 用户图片列表前端代码在js代码下面导入

<script type="text/javascript" src="${pageContext.request.contextPath}/layer/layer.min.js"></script>(参考modify.jsp)
         $(".display").click(function(){
         layer.use('extend/layer.ext.js');
 $.getJSON("${pageContext.request.contextPath}/picture/getPic.action",{"picture.id":this.lang,"idType":"picture"},function(data){
             layer.photos({
                   html:"",
                  json:data
                 });
             });
     });

        * 通过得到用户id或图片id,调用dao.getPictures和picService.getJSON来得到数据库图片数据和图片文件json数据,返给前端实现图像显示(参考PictureAction)
        public String getPic() 
        {
        int id=0;
        if(idType.equals("user"))
        {
            id=picture.getUid();
        }
        else
        {
            id=picture.getId();
        }
        ArrayList<Picture> list=dao.getPictures(id,idType);
        String path=ServletActionContext.getRequest().getContextPath();
        String json=picService.getJSON(list, path);
        response.setCharacterEncoding("utf-8");        
        try {
            out = response.getWriter();
            out.print(json);
            System.out.println(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("接收到的id为"+id +"类型为"+idType);
        return null;
        }

        * DAO代码:通过id和idType变量返回图片
        
          public ArrayList<Picture> getPictures(int id,String idType)
            {
                 try {
               if (conn.isClosed()) {
                   conn = DBLib.getConnection();
               }
           } catch (SQLException e1) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
           }
                 String fieldName="";
             if(idType.equals("user"))
             {
             fieldName="uid";
             }
             else
             {
             fieldName="id";
             }
            String sql="select * from pictures where "+ fieldName +"=?";
            ArrayList<Picture> pics=new ArrayList<Picture>();
             try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs=ps.executeQuery();
            while(rs.next())
            {
                Picture pic=new Picture();
                pic.setId(rs.getInt(1));
                pic.setUid(rs.getInt(2));
                pic.setName(rs.getString(3));
                pic.setUrl(rs.getString(4));
                pics.add(pic);
            }
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }     
            return pics;
            }

      * picService代码:使用 StringBuilder和append 返回字符串数据
        
            package mypicture;

        import java.util.ArrayList;

        public class picService {
        public static String getJSON(ArrayList<Picture> list,String contextPath)
            {
                   StringBuilder str =new StringBuilder();
                    str.append("{");
                      str.append("\"status\": 1,");    //请求的状态,1表示成功,其它表示失败
                      str.append("\"msg\": \" \", "); //状态提示语
                      str.append("\"title\": \" 用户相册 \",");    //相册标题
                      str.append("\"id\": 0,");    //相册id
                       str.append("\"start\": 0,"); //初始显示的图片序号,默认0
                      
                      str.append("\"data\": [");   //相册包含的图片,数组格式
         
                      //处理相片
                      for(int i = 0; i<list.size() ; i++)
                      {       str.append("{");
                                str.append("\"name\": \""+list.get(i).getName()+"\","); //图片名
                          str.append("\"pid\": 0,"); //图片id
                           str.append("\"src\" : \""+contextPath+"/"+list.get(i).getUrl() +"\","); //原图地址
                          str.append("\"thumb\": \"\","); //缩略图地址
                          str.append("\"area\": [638, 851]"); //原图宽高
                             str.append("}");
                        if(i<list.size()-1)
                      {
                          str.append(",");
                      }
                       else
                        {
                            break;
                       }
                      }
                      str.append("]");
             
                str.append("}");
                    return str.toString();
        
                }
            }
    *  多文件上传,动态数组处理
        * 前端数据modify代码,把多张图片数据提交至add action里。
            <form method="post"  enctype="multipart/form-data" action="${pageContext.request.contextPath}/picture/add">
            <table>
            <tr><td>选择照片</td><td><input type="file" name="image"></td></tr>
            <tr><td>照片名称</td><td><input type="text" name="pictures[0].name"/>
            <input type="hidden" name="pictures[0].uid" value="<s:property value="user.id"/>"/>
            </td></tr>

            <tr><td>选择照片</td><td><input type="file" name="image"></td></tr>
            <tr><td>照片名称</td><td><input type="text" name="pictures[1].name"/>
            <input type="hidden" name="pictures[1].uid" value="<s:property value="user.id"/>"/>
            </td></tr>
            <tr><td colspan="2"><input type="submit" value="提交" /></td></tr>
            </table>
            </form>

        * picture add action代码,定义动态数组ArrayList<Picture> pictures=new ArrayList<Picture>();(需要做set和get)接收多张图片
            
            public String add()  
            {
                ServletContext app=ServletActionContext.getServletContext();
                String path=app.getRealPath("")+"/images";
                for(int i=0;i<image.length;i++)
                {
                    // 新建文件用来存放上传的文件
                    File myfile = new File(path, imageFileName[i]);
                    // 如果文件上一级目录不存在,创建目录
                    if (!myfile.getParentFile().exists()) {
                    myfile.getParentFile().mkdirs();
                }

                try {
                // 保存上传文件,将源文件image复制到myfile目标文件里。
                FileUtils.copyFile(image[i], myfile);
                // 设置第i张图片文件路径
                pictures.get(i).setUrl("images/" + imageFileName[i]);
                dao.addPicture(pictures.get(i));
                } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                }
                }
                return "list";
            }
            
        * pictureDAO代码,图片数据添加到数据库。    
    
    


 

猜你喜欢

转载自blog.csdn.net/tangbin0505/article/details/81812427