Struts 2 (9. Use layer component to realize picture display function)

1. Introduction to layer front-end components

Layer is a well-known web shell layer component. It has a full range of solutions and is dedicated to serving developers at all levels. Your page will easily have rich and friendly operation experience.

http://sentsin.com/jquery/layer/

Usage method
http://sentsin.com/jquery/layer/ext.html

Introducing layer components into a project

<script type="text/javascript" src="${pageContext.request.contextPath}/layer/layer.min.js"></script>

 

2.userlist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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>User list</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/layer/layer.min.js"></script>
<script type="text/javascript">
$(function(){
    //Display photos
    $(".picture").click(function(){
        //Introduce layer.ext.js
        layer.use('extend/layer.ext.js');
        $.getJSON("${pageContext.request.contextPath}/picture/getpic",{"picture.uid":this.lang},function(data){
            layer.photos({
                html:"",        //The path of the web page indicates that the picture is displayed on the left, and a web page can be displayed on the right to introduce the picture
                json: data
            });
        });
    });
});
</script>
</head>
<body>
//User list
<br>
<br>
<table class="bordered">
<thead>
<tr><th>Serial number</th><th>User name</th><th>Password</th><th>Photo</th><th>delete</th><th>modify</th></tr>
</thead>
<!-- USERLIST,cuser,s Deposited Stack Context -->
<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"/>">Photo</a></td>
<td><a href="#" class="delete" lang="<s:property value="#cuser.id"/>!<s:property value="#cuser.userName"/>">delete</a></td>
<td><a href="#" class="modify" lang="<s:property value="#cuser.id"/>">modify</a></td>
</tr>
</s:iterator>
</table>
<br>
<br>
<a href="${pageContext.request.contextPath}/main.jsp">Back to main page</a>
</body>
<!-- debugging
Value Stack      No need to add# 
Stack Context   Add when visiting#
-->
<s:debug></s:debug>
</html>

 

3.PictureAction

/**
     * Get the json string of all photos of the current user
     * @return
     * @throws IOException
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws NamingException
     */
    public String getpic() throws IOException, SQLException, ClassNotFoundException, NamingException{
        PictureDAO dao=new PictureDAO();
        //From the database through the current user id Get all pictures of the current user
        ArrayList<Picture> list = dao.getPicture(picture.getUid());
        //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

/**
     * Get all photos of the current user from the database through uid (current user id)
     * @param id
     * @return
     * @throws SQLException
     * @throws NamingException
     */
    public ArrayList<Picture> getPicture(int id) throws SQLException, NamingException
    {
        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 uid = ?";
        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. Create a PictureService class to assemble json data

package mypicture;

import java.util.ArrayList;

/**
 * Receive all photos and return a json string
 */
public class PictureService {

    public static String getJSON(ArrayList<Picture> list,String contextPath)
    {
        //String connection  
        StringBuilder str = new StringBuilder();    
        str.append("{");  
        //The status of the request, 1 for success, and other for failure    \"Translated characters, for ""
        str.append("\"status\": 1, ");    
        //Status prompt
        str.append("\"msg\": \"Photo\", ");  
        //Album title  
        str.append("\"title\": \"whr Photo album\", ");    
        //Album id    
        str.append("\"id\": 0, ");  
        //The number of the initially displayed picture, 0 by default
        str.append("\"start\": 0, ");                  
        str.append("\"data\": [ ");  
        //Processing photos  
        for (int i = 0; i < list.size(); i++) {  
            str.append("{");  
            //Picture name
            str.append("\"name\": \"" + list.get(i).getName() + "\", ");
            //picture id
            str.append("\"pid\": 0, ");                                                          
            //Notice the left slash in the middle. If it's written as the right slash"\\"No results  
            //Picture path
            str.append("\"src\": \""+ contextPath + "/" +list.get(i).getUrl() + "\", "); 
            //Thumbnail address 
            str.append("\"thumb\": \"\", ");
            //Original height
            str.append("\"area\": [600,800] " );                                              
            str.append("}");
            //If it 's not the last item, plus
            if (i < list.size()-1) {  
                str.append(",");          
            }else {  
                break;  
            }  
        }  
        str.append("]");  
        str.append("}");  
        return str.toString();  
    }
}

 

6. The acceptable size of the uploaded file can be modified

Modify the constant struts.multipart.maxSize in struts.xml

<! -- control the size of uploaded file: 3 0 for Kb,6 0 for Mb, here is 10Mb-->
    <constant name="struts.multipart.maxSize" value="10000000"/>

Tags: Java JSON Javascript Struts JQuery

Posted on Fri, 31 Jan 2020 15:18:17 -0800 by doofystyle