首页 > 代码库 > Java语言实现通过Ajax抓取后台数据及图片

Java语言实现通过Ajax抓取后台数据及图片

 

1.Java语言实现通过Ajax抓取后台数据及图片信息

1.1数据库设计

create table picture(   pic_id number not null,   pic_name varchar(200)not null,   pic_url varchar2(200) not null,   pic_descp varchar2(200) not null,   pic_price varchar2(200) not null)insert into picture values(1 ,小米5s Plus,img/1.jpg,5.7英寸大屏双摄手机,拍照黑科技 ,79元);insert into picture values(2 ,红米手机4,img/2.jpg,12月27日早10点开售 ,699元起);insert into picture values(3 ,小米电视3s 48英寸,img/3.jpg,原装液晶屏,金属机身 ,1999元);insert into picture values(4 ,小米平板2 16GB现货,img/4.jpg,轻薄全金属,海量内容 ,999元);insert into picture values(5 ,小米盒子3s,img/5.jpg,人工智能机顶盒,2GB+8GB 大存储 ,299元);insert into picture values(6 ,小米移动电源2,img/6.jpg,双向快充,高密度锂聚合物电芯 ,79元);insert into picture values(7 ,米家扫地机器人,img/7.jpg,远程智能控制,扫得干净扫得快 ,1699元);insert into picture values(8 ,米家恒温电水壶,img/8.jpg,快速沸腾,水温智能控制 ,299元);insert into picture values(9 ,小米净水器 厨上式,img/9.jpg,RO反渗透直出纯净水 ,1299元);insert into picture values(10 ,小米手环 2,img/10.jpg,OLED 显示屏幕,升级计步算法 ,149元);select * from picture;

 运行效果:

技术分享

1.2 新建一个JavaWeb项目

1.2.1 添加项目说需要的包  即连接数据库的ojdbc的jar包

1.2.2编写连接数据库的工具类

技术分享
package org.user.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DBUtil {    private static String driver="oracle.jdbc.driver.OracleDriver";    private static String url="jdbc:oracle:thin:@localhost:1521:orcl";    private static String user="yongl";    private static String passwd="121314";    public static Connection getConnection() {        try {            Class.forName(driver);            return DriverManager.getConnection(url, user, passwd);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    public static void closeConn(Connection conn,Statement stm , ResultSet rs ) {        if(stm!=null){            try {                stm.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if (conn != null) {            try {                conn.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if(rs!=null){            try{                rs.close();            }catch(SQLException e){                e.printStackTrace();            }        }    }    public static void main(String[] args) {        System.out.println(getConnection());    }}
View Code

 运行效果:

技术分享

连接成功。

1.2.3编写字符串转化为json的的工具类

package org.picture.util;import com.google.gson.Gson;import com.google.gson.GsonBuilder;public class GsonUtil {    public static String toJson(Object obj){        return new Gson().toJson(obj);    }         public static String toJson(Object obj, String dateFormat){        GsonBuilder builder = new GsonBuilder();        Gson gson = builder.setDateFormat("yyyy-MM-dd").create();        return gson.toJson(obj);            } }

 

1.2.4 编写实体类

package org.picture.entity;public class Entity {    private int id;    private String name;    private String url;    private String descp;    private String price;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getDescp() {        return descp;    }    public void setDescp(String descp) {        this.descp = descp;    }    public String getPrice() {        return price;    }    public void setPrice(String price) {        this.price = price;    }    @Override    public String toString() {        return "Entity [id=" + id + ", name=" + name + ", url=" + url + ", descp=" + descp + ", price=" + price + "]";    }             }

1.2.5 编写dao方法

package org.picture.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.junit.Test;import org.picture.entity.Entity;import org.picture.util.DBUtil;public class Dao {    //查询所有picture的所有信息    public List<Entity> findPicture(){        String sql="select * from picture";        Connection conn = DBUtil.getConnection();        ResultSet rs= null;        PreparedStatement ps=null;        List<Entity> list = new ArrayList<Entity>();        try {            ps = conn.prepareStatement(sql);            rs=ps.executeQuery();            while(rs.next()){                Entity  p= new Entity();                p.setId(rs.getInt(1));                p.setName(rs.getString(2));                p.setUrl(rs.getString(3));                p.setDescp(rs.getString(4));                p.setPrice(rs.getString(5));                list.add(p);            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            DBUtil.closeConn(conn, ps, rs);        }        return list;    }    @Test    public void test(){        Dao dao = new Dao();        List<Entity> i=dao.findPicture();        for (Entity e : i) {            System.out.println(e);        }    }}

运行效果:

技术分享

1.2.6 编写servlet

package org.picture.servlet;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.picture.dao.Dao;import org.picture.entity.Entity;import com.google.gson.Gson; @WebServlet("/pictureServlet")public class PictureServlet extends HttpServlet {    private static final long serialVersionUID = 1L;        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        Dao dao = new Dao();        List<Entity> i=dao.findPicture();                Gson gson = new Gson();        //在这里转化成json        String json =gson.toJson(i);        System.out.println(json);                response.setContentType("application/json;charset=UTF-8");        response.getWriter().println(json);    }}

运行效果:

技术分享

在返回的是json 最终要返回到页面

1.2.7 html页面:

示例代码:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title>     <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>     <style type="text/css">            #book {                width: 100%;                position: absolute;                border:1px red solid;                display:inline-block;            }                          .p1{                font-size: 16px;                color: #000;                font-family: Microsoft YaHei;            }             .p2{                font-size: 14px;                color: #b0b0b0;                margin-top:10px;                font-family: Microsoft YaHei;            }             .p3{                font-size: 16px;                color: #ff5f19;                margin-top:10px;                font-family: Microsoft YaHei;            }            .product{                float:left;                text-align: center;                width:19%;                position: relative;                margin: 30px 20px 5px 50px;                                 box-shadow: 0px 10px 10px #adadad;                height: 330px;                background: #fafafa;            }            .book-img{                width:100%;                height:67%;                margin: 0 0 8px 0;            }            .book-img img{                width:100%;                height:100%;            }        </style>    <script>    //页面加载   获取全部信息        $(function(){            $.get("pictureServlet",function(result){                                //result数据添加到表格中;                 addBox(result);            });             });           function addBox(result){            //result是一个集合,所以需要先遍历            $.each(result,function(index,obj){             $("#picture").append("<div class=‘product‘>"+//获得图片地址                                         "<div class=‘book-img‘><img src=http://www.mamicode.com/"+obj.url+"></div>"+                                //获得商品名字                                     "<div class=‘p1‘>"+obj.name+"</div>"+                            //获得商品描述                        "<div class=‘p2‘>"+obj.descp+"</div>"+                            //获得商品价格                        "<div class=‘p3‘>"+obj.price+"</div>"+                                            "</div>");             });        }            </script></head><body>    <!-- 构建装一个容器 -->             <div id="picture">        </div>     </body></html>

运行效果:

技术分享

 

技术分享

 

 

 

 

Java语言实现通过Ajax抓取后台数据及图片