python爬虫+JavaWeb接口+Android完整的小项目开发案例(2)

上一篇讲了python 爬取糗事百科的数据到数据库中,本篇讲解java web接口开发,以json的形式展示接口

准备:java 环境,tomcat环境,eclipse,eclipse集成tomcat ,json.jar,mysql-connect-java .jar

eclipse新建Dynamic web project,目录层级如下:


image.png

将jar包复制到lib目录下,然后add build to path

下面详述代码:

1.创建糗事百科实体类Qiushibaike

package com.entity;

public class Qiushibaike {
    private int id;
    private String imgurl;
    private String username;
    private String vote;
    private String comments;
    private String content;
    private String imgpath;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getImgurl() {
        return imgurl;
    }
    public void setImgurl(String imgurl) {
        this.imgurl = imgurl;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getVote() {
        return vote;
    }
    public void setVote(String vote) {
        this.vote = vote;
    }
    public String getComments() {
        return comments;
    }
    public void setComments(String comments) {
        this.comments = comments;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getImgpath() {
        return imgpath;
    }
    public void setImgpath(String imgpath) {
        this.imgpath = imgpath;
    }
    
    

}

2.写一个分页实体类QiushiPage:

package com.entity;

import java.util.List;

public class QiushiPage {
     private int currentPage;//当前页
        private int totalPage;//总页数
        private int count;//一页多少条数据
        private int totalCount;//数据总条数
        private List<Qiushibaike> qiushibaikes;//当前页的数据
       
        
        public int getTotalCount() {
            return totalCount;
        }
        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }
        
        public List<Qiushibaike> getQiushibaikes() {
            return qiushibaikes;
        }
        public void setQiushibaikes(List<Qiushibaike> qiushibaikes) {
            this.qiushibaikes = qiushibaikes;
        }
        public int getCurrentPage() {
            return currentPage;
        }
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
        public int getTotalPage() {
            return totalPage;
        }
        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }
        public int getCount() {
            return count;
        }
        public void setCount(int count) {
            this.count = count;
        }
        
        
}

3.数据库操作类QiushiDaoImpl:

package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.entity.Qiushibaike;


public class QiushiDaoImpl  {
    private PreparedStatement ptmt = null;  
    private ResultSet rs = null;
    
    //获取表中的数据,放入list,并返回
    public List<Qiushibaike> getCaseAll(int page, int count) {
        // TODO Auto-generated method stub
        List<Qiushibaike> list = new ArrayList<Qiushibaike>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/shop?useunicuee=true& characterEncoding=utf8";
            String username="root";
            String password="root";
            Connection conn=DriverManager.getConnection(url,username,password);
            String sql="select id,imgurl,comments,username,content,vote,imgpath from qiushibaike LIMIT ?,?";
            PreparedStatement ps = conn.prepareStatement(sql);
            
            
            ps.setInt(1, (page-1)*count);
            ps.setInt(2, count);
            
            ResultSet rs=ps.executeQuery();
            
            //查询实体放入list
            while(rs.next()){
                Qiushibaike qiushibaike=new Qiushibaike();
                
                //查询的每个字段值放入到实体中
                qiushibaike.setId(rs.getInt("id"));
                qiushibaike.setImgurl(rs.getString("imgurl"));
                qiushibaike.setComments(rs.getString("comments"));
                qiushibaike.setUsername(rs.getString("username"));
                qiushibaike.setContent(rs.getString("content"));
                qiushibaike.setVote(rs.getString("vote"));
                qiushibaike.setImgpath(rs.getString("imgpath"));
                
                list.add(qiushibaike);
            }
            rs.close();
            ps.close();
            conn.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
        
    }
    
    //查询表中的记录数,并返回
    public int count() throws SQLException {
        int count = 0;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/test?useunicuee=true& characterEncoding=utf8";
            String username="root";
            String password="root";
            Connection conn=DriverManager.getConnection(url,username,password);
            if(conn==null){
                throw new NullPointerException("conn is null");
            }
            PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM qiushibaike");
            if(ps==null){
                throw new NullPointerException("ps is null");
            }
            ResultSet rs = ps.executeQuery();

            if(rs==null){
                throw new NullPointerException("rs is null");
            }   
            
            if (rs.next()) {
                count = rs.getInt(1);
            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return count;
        
    }

}

4.数据分页类QiushiServiceImpl:

package com.dao;

import java.sql.SQLException;
import java.util.List;


import com.entity.QiushiPage;
import com.entity.Qiushibaike;


public class QiushiServiceImpl {
    
     private QiushiDaoImpl qiushiDaoImpl = new QiushiDaoImpl();

        
        public QiushiPage findPage(int page, int count) {
            if(qiushiDaoImpl==null){
                qiushiDaoImpl = new QiushiDaoImpl();
            }
            try {
                List<Qiushibaike> qiushibaikes = qiushiDaoImpl.getCaseAll(page, count);
                System.out.println(qiushibaikes);
                int totle = qiushiDaoImpl.count();
                System.out.println(totle);
                QiushiPage p=new QiushiPage();
                
                p.setQiushibaikes(qiushibaikes);;
                p.setCurrentPage(page);
                p.setCount(count);
                p.setTotalCount(totle);
                int totlePage = totle%count==0?totle/count:(totle/count)+1;
                p.setTotalPage(totlePage);
                return p;
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
        }

}

5.servlet类QiushiServlet:

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 com.dao.QiushiDaoImpl;
import com.dao.QiushiServiceImpl;

import com.entity.QiushiPage;
import com.entity.Qiushibaike;

import com.google.gson.Gson;




/**
 * Servlet implementation class TestAdd
 */
public class QiushiServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QiushiServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        QiushiServiceImpl qiushiServiceImpl=new QiushiServiceImpl();
        int currentPage=1;
        //每一页15条数据
        int count=15;
        String value = request.getParameter("page");
        if(value!=null&&!"".equals(value)){         
            currentPage = Integer.parseInt(value);
        }

        //转化成json
        QiushiPage page  = qiushiServiceImpl.findPage(currentPage, count);
        Gson gson = new Gson();
        String json = gson.toJson(page);

        // 输出到界面
        System.out.println(json);
        //response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");  
             
        
        //PrintWriter out = response.getWriter();
        
        
               PrintWriter out = new PrintWriter(response.getWriter());
        out.print(json); 
        out.flush();
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

6.WEB-INF 目录下新建一个xml文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
 
<servlet>
    <servlet-name>QiushiServlet</servlet-name>
    <servlet-class>com.servlet.QiushiServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>QiushiServlet</servlet-name>
    <url-pattern>/QiushiServlet</url-pattern>
  </servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

7.WebContent下新建一个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>
 <a href = "QiushiServlet">点击接口</a><br>
 
</body>
</html>

代码部分就是这样,附上代码结构图:


image.png

最有右击项目,run on server结果如图


image.png

点击上图的按钮跳转到接口界面:


image.png

需要访问第二页时输入如下网址,page后面的数字表示页数:
http://localhost:8080/QiuShiSample/QiushiServlet?page=2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容