Struts2 (X. display photo list on modification page and add delete photo function)

Posted by bruceleejr on Fri, 31 Jan 2020 18:08:49 +0100

1, Show photo list function

The general processing method in struts 2:
First, in action, prepare the data and go to jsp to display

1.UserAction

/**
     * Click modify user to jump to modify user interface
     * Prepare photos for users to display in modify.jsp
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws NamingException
     */
    public String modify() throws SQLException, ClassNotFoundException, NamingException
    {
        UserDAO dao=new UserDAO();
        //this user Will be in Value Stack Appear in
        user=dao.getUserById(user.getId());
        
        //By current user id Get all its photos
        PictureDAO pdao = new PictureDAO();
        ArrayList<Picture> list=pdao.getPicture(user.getId());
        //Store photos ActionContext Within limits
        ActionContext ctx = ActionContext.getContext();
        ctx.put("PICTURES", list);
        return "modify";
    }

 

2.modify.jsp

Display only when users have photos, and do not display without photos

Reference document for if tag
http://blog.csdn.net/chinajust/article/details/3922718

Reference documents for ognl
http://www.blogjava.net/parable-myth/archive/2010/10/28/336353.html

EL expression:$
OGNL expression: =

<s:if test="%{#PICTURES.size()>0}">        <!-- OGNL Expression -->
Show all photos of users
<br>
<br>
<!-- Photo display -->
<table class="bordered">
<thead>
<tr><th>Serial number</th><th>Photo name</th><th>display</th><th>delete</th></tr>
</thead>
<!-- PICTURES,cpic,s Deposited Stack Context -->
<s:iterator value="#PICTURES" id="cpic" status="s">
<tr>
<td><s:property value="#s.index+1"/></td>
<td><s:property value="#cpic.name"/></td>
<td><a href="#" class="display" lang="<s:property value="#cpic.id"/>">display</a></td>
<td><a href="#" class="delete" lang="<s:property value="#cpic.id"/>!<s:property value="#cpic.name"/>">delete</a></td>
</tr>
</s:iterator>
</table>
</s:if>

js:

//Display photos
    $(".display").click(function(){
        layer.use('extend/layer.ext.js');
        $.getJSON("${pageContext.request.contextPath}/picture/display",{"picture.id":this.lang},function(data){
            layer.photos({
                html:"",
                json: data
            });
        });
    });

 

3.PictureAciton

/**
     * Show photos by photo id
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     * @throws NamingException
     * @throws IOException
     */
    public String display() throws ClassNotFoundException, SQLException, NamingException, IOException{
        PictureDAO dao=new PictureDAO();
        //By photo id Get photos
        ArrayList<Picture> list = dao.displayPicture(picture.getId());
        //Get the root directory of the site deployment
        String path=ServletActionContext.getRequest().getContextPath();
        //call PictureService Medium getJSON Method
        String json=PictureService.getJSON(list, path);
        response.setCharacterEncoding("utf-8");
        out=response.getWriter();
        out.print(json);
        //Output to the console for a look
        System.out.println(json);
        return null;
    }

 

4.PictureDAO

/**
     * Show photos by photo id
     * @param id
     * @return
     * @throws NamingException
     * @throws SQLException
     */
    public ArrayList<Picture> displayPicture(int id) throws NamingException, SQLException{
        if(conn.isClosed())
        {
            Context ctx = new InitialContext();  
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");  
            conn = ds.getConnection();
        }
        ArrayList<Picture> pics=new ArrayList<Picture>();
        sql="select * from pictures where id=?";
        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();
        return pics;
    }

 

5. effect

 

2, Delete photo function

Delete function:
Delete the corresponding pictures saved locally
Delete records in database tables

1.modify.jsp

js:

//Delete photos
    $(".delete").click(function(){
        var str=this.lang.split("!");
        if(!confirm("Are you sure you want to delete"+ str[1] +"Is this picture?"))
        {
            return;
        }
        //jquery ajax mode request action
        $.post("${pageContext.request.contextPath}/picture/delete",{"picture.id":str[0]},function(){
            location.href="${pageContext.request.contextPath}/user/modify?user.id=" + $("[name='user.id']").val();
        });
    });

 

2.PictureAciton

/**
     * Delete photos by photo id
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     * @throws NamingException
     */
    public String delete() throws ClassNotFoundException, SQLException, NamingException{
        //Pay attention to the sequence, because you need to get it from the database url,If you delete the information in the database first, you won't get it, so delete the local photos first
        PictureDAO dao=new PictureDAO();
        //By photo id Get the url,To delete photos locally
        String url = dao.getUrl(picture.getId());
        ServletContext app=ServletActionContext.getServletContext();
        String path=app.getRealPath("") + "/" + url;
        File myfile=new File(path);
        //FileUtils(Need one file Type file),deleteQuietly(Do not prompt to delete)
        FileUtils.deleteQuietly(myfile);
        //Delete photo information in database
        dao.deletePicture(picture.getId());
        return null;
    }

 

3.PictureDAO

/**
     * Get the url of the photos in the database through the photo id to delete the photos locally
     * @param id
     * @return
     * @throws NamingException
     * @throws SQLException
     */
    public String getUrl(int id) throws NamingException, SQLException{
        if(conn.isClosed())
        {
            Context ctx = new InitialContext();  
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");  
            conn = ds.getConnection();
        }
        sql="select url from pictures where id = ?";
        ps=conn.prepareStatement(sql);
        ps.setInt(1, id);
        ResultSet rs = ps.executeQuery();
        rs.next();
        String url=rs.getString(1);
        conn.close();
        return url;
    }
/**
     * Delete photo data in database by photo id
     * @param id
     * @throws NamingException
     * @throws SQLException
     */
    public void deletePicture(int id) throws NamingException, SQLException{
        if(conn.isClosed())
        {
            Context ctx = new InitialContext();  
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");  
            conn = ds.getConnection();
        }
        sql="delete from pictures where id = ?";
        ps=conn.prepareStatement(sql);
        ps.setInt(1, id);
        ps.execute();
        conn.close();
    }

Topics: Java SQL Database JSP JSON