其中要用到的 gson此处用于将持久化对象解析为Json,或将Json序列化为对象。
==目录如下==
主要是使用到下边红框中的类
package cn.hy.newsTest;
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 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;
}
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 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;
}
}
package cn.hy.newsTest;
import java.util.List;
public class NewsList {
private int total; //新闻数量
private List<News> rows; //新闻列表
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<News> getRows() {
return rows;
}
public void setRows(List<News> rows) {
this.rows = rows;
}
public NewsList() {}
public NewsList(int total, List<News> rows) {
this.total = total;
this.rows = rows;
}
}
package cn.hy.newsTest;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.google.gson.Gson;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;
public class JsonServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "SELECT * FROM news";
List<News> newsList = runner.query(sql, new BeanListHandler<News>(News.class));
// 将数据封装到新闻总计类
NewsTotal nt = new NewsTotal(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类
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
发布项目,在tomcat访问JsonServlet,最后在浏览器就能拿到数据