(017)java后台开发之客户端通过HTTP获取接口Json数据

通过前面的文章,我们能了解javaWeb工程的基本知识。然后最激动的东西来了!我们建立了JsonTest工程,部署到了tomcat,本地浏览器访问了我们的JsonTest工程的index.jsp页面。
  1. 那我们怎么进行客户端和服务器后台交互尼?
    跟着一个例子实现:
    http://blog.csdn.net/jaikydota163/article/details/51458880
    在之前建好的JsonTest工程,创建我们需要的文件。

步骤一:新建测试用Model类
新建新闻测试类News,主要用于数据模型测试显示,Json转换测试等,代码如下:

import java.util.Date;  

public class News {  

    private int nId; // 新闻ID  
    private String title; // 新闻标题  
    private String content; // 新闻内容  
    private String date; // 新闻发布日期  
    private String url; //新闻地址  
    private Date nDate; // 新闻日期,Date类型  

    public News(int nId, String title, String content, String date, String url) {  
        this.nId = nId;  
        this.title = title;  
        this.content = content;  
        this.date = date;  
        this.url = url;  
    }  

    public News() {  
    }  

    public News(int nId, String title, String content, Date nDate, String url) {  
        this.nId = nId;  
        this.title = title;  
        this.content = content;  
        this.nDate = nDate;  
        this.url = url;  
    }  

    public String getUrl() {  
        return url;  
    }  

    public void setUrl(String url) {  
        this.url = url;  
    }  

    public Date getnDate() {  
        return nDate;  
    }  

    public void setnDate(Date nDate) {  
        this.nDate = nDate;  
    }  

    public int getnId() {  
        return nId;  
    }  

    public void setnId(int nId) {  
        this.nId = nId;  
    }  

    public String getTitle() {  
        return title;  
    }  

    public void setTitle(String title) {  
        this.title = title;  
    }  

    public String getContent() {  
        return content;  
    }  

    public void setContent(String content) {  
        this.content = content;  
    }  

    public String getDate() {  
        return date;  
    }  

    public void setDate(String date) {  
        this.date = date;  
    }  
}  

新建分页测试类NewTotal,主要用于Json分页显示,代码如下:

import java.util.List;  

public class NewTotal {  
    private int total; //新闻数量  
    private List rows; //新闻列表  

    public NewTotal() {  
    }  
    public NewTotal(int total, List rows) {  
        this.total = total;  
        this.rows = rows;  
    }  
    public int getTotal() {  
        return total;  
    }  
    public void setTotal(int total) {  
        this.total = total;  
    }  
    public List getRows() {  
        return rows;  
    }  
    public void setRows(List rows) {  
        this.rows = rows;  
    }   
}  

步骤二:添加测试用Action和JSP界面
新建JsonServlet,继承自HttpServlet,具体代码详解已经在代码中注释:

Servlet的创建:
http://blog.csdn.net/gaohuanjie/article/details/36377425

import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.ArrayList;  
import java.util.List;  

import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import com.google.gson.Gson;  
import com.test.model.NewTotal;  
import com.test.model.News;  

public class JsonServlet extends HttpServlet {  

    private static final long serialVersionUID = 1L;  

    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
        // 创建多个新闻类,模拟从数据库获取数据,可将此处改为用JDBC从数据库读取数据  
        News new1 = new News(110, "日本地震", "日本福田发生了7级地震", "2016-5-16 10:22:20",  
                "http://world.huanqiu.com/exclusive/2016-05/8974294.html");  
        News new2 = new News(111, "Apple库克第八次访华", "近日库克第八次访华,与滴滴高层会谈", "2016-5-16 10:22:20",  
                "http://mobile.163.com/16/0523/09/BNO7SG2B001168BQ.html");  
        News new3 = new News(113, "Google I/O大会开幕", "Google开发者大会即将举办,是否推出Android7.0?", "2016-5-16 10:22:20",  
                "http://www.ithome.com/html/android/227647.htm");  
        News new4 = new News(114, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20",  
                "http://news.mydrivers.com/1/484/484072.htm");  
        News new5 = new News(115, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new6 = new News(116, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new7 = new News(117, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new8 = new News(118, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new9 = new News(119, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new10 = new News(120, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new11 = new News(121, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new12 = new News(122, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new13 = new News(123, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new14 = new News(124, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new15 = new News(125, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new16 = new News(126, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new17 = new News(127, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new18 = new News(128, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new19 = new News(129, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  
        News new20 = new News(130, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");  

        String page = req.getParameter("page");  
        // 将数据添加到数组  
        List newslist = new ArrayList();  
        if (page == null || page.equals("0")) {  
            newslist.add(new1);  
            newslist.add(new2);  
            newslist.add(new3);  
            newslist.add(new4);  
            newslist.add(new5);  
            newslist.add(new6);  
            newslist.add(new7);  
            newslist.add(new8);  
            newslist.add(new9);  
            newslist.add(new10);  
        }  
        else {  
            newslist.add(new11);  
            newslist.add(new12);  
            newslist.add(new13);  
            newslist.add(new14);  
            newslist.add(new15);  
            newslist.add(new16);  
            newslist.add(new17);  
            newslist.add(new18);  
            newslist.add(new19);  
            newslist.add(new20);  
        }  

        // 将数据封装到新闻总计类  
        NewTotal nt = new NewTotal(newslist.size(), newslist);  

        // 调用GSON jar工具包封装好的toJson方法,可直接生成JSON字符串  
        Gson gson = new Gson();  
        String json = gson.toJson(nt);  

        // 输出到界面  
        System.out.println(json);  
        resp.setContentType("text/plain");  
        resp.setCharacterEncoding("gb2312");  
        PrintWriter out = new PrintWriter(resp.getOutputStream());  
        out.print(json);  
        out.flush();  
        // 更多Json转换使用请看JsonTest类  
    }  

    @Override  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
        this.doGet(req, resp);  
    }  
}  

修改项目index.jsp页面如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  

  
<html>  
  <head>  
    <base href="<%=basePath%>">  

    <title>Test Jsontitle>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8>  
    pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
      
  head>  

  <body>  
     <form action="getJson" method="get">  
        <input type="submit" value="点击获取新闻JSON数据"/>  
     form>  
  body>  
html>  

在项目中配置web.xml,注册JsonServlet映射,配置如下:

  
<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_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>JsonTestdisplay-name>  
  <welcome-file-list>  
    <welcome-file>index.jspwelcome-file>  
  welcome-file-list>  

  <servlet>  
      <servlet-name>JsonServletservlet-name>  
      <servlet-class>com.test.json.JsonServletservlet-class>  
  servlet> 

  <servlet-mapping>  
      <servlet-name>JsonServletservlet-name>  
      <url-pattern>/getJsonurl-pattern>  
  servlet-mapping>  
web-app>  

步骤三:添加项目到Tomcat容器,运行服务器
运行服务器,在地址栏输入地址:
http://localhost:8080/JsonTest/getJson?page=0,

⚠️这里可能会出现乱码。解决办法:
只需要把网页编码切换一下就可以了,设置下编码为utf-8。客户端编码设置为utf8,这样保证交互过程中,编码一致。OK了!

效果如图:
(017)java后台开发之客户端通过HTTP获取接口Json数据_第1张图片

一个简单的http请求已经返回就完成了!

例子参考:
http://blog.csdn.net/jaikydota163/article/details/51458880

你可能感兴趣的:(java开发之路)