我想暴露一個(gè)json字符串出來(lái)給前端頁(yè)面
package com.mvc.servlet;
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.mvc.bean.NewTotal;
import com.mvc.bean.News;
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 創(chuàng)建多個(gè)新聞?lì)悾M從數(shù)據(jù)庫(kù)獲取數(shù)據(jù),可將此處改為用JDBC從數(shù)據(jù)庫(kù)讀取數(shù)據(jù)
News new1 = new News(110, "日本地震", "日本福田發(fā)生了7級(jí)地震", "2016-5-16 10:22:20",
"http://world.huanqiu.com/exclusive/2016-05/8974294.html");
News new2 = new News(111, "Apple庫(kù)克第八次訪華", "近日庫(kù)克第八次訪華,與滴滴高層會(huì)談", "2016-5-16 10:22:20",
"http://mobile.163.com/16/0523/09/BNO7SG2B001168BQ.html");
News new3 = new News(113, "Google I/O大會(huì)開(kāi)幕", "Google開(kāi)發(fā)者大會(huì)即將舉辦,是否推出Android7.0?", "2016-5-16 10:22:20",
"http://www.ithome.com/html/android/227647.htm");
News new4 = new News(114, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20",
"http://news.mydrivers.com/1/484/484072.htm");
News new5 = new News(115, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new6 = new News(116, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new7 = new News(117, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new8 = new News(118, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new9 = new News(119, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new10 = new News(120, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new11 = new News(121, "獲取新數(shù)據(jù)?。。。。。?, "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new12 = new News(122, "獲取新數(shù)據(jù)!?。。。?!", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new13 = new News(123, "獲取新數(shù)據(jù)?。。。。?!", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new14 = new News(124, "獲取新數(shù)據(jù)?。。。。?!", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new15 = new News(125, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new16 = new News(126, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new17 = new News(127, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new18 = new News(128, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new19 = new News(129, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
News new20 = new News(130, "格力營(yíng)收下滑400億", "格里營(yíng)收下滑400億,董明珠說(shuō)我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
String page = req.getParameter("page");
// 將數(shù)據(jù)添加到數(shù)組
List<News> newslist = new ArrayList<News>();
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);
}
// 將數(shù)據(jù)封裝到新聞總計(jì)類(lèi)
NewTotal nt = new NewTotal(newslist.size(), newslist);
// 調(diào)用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轉(zhuǎn)換使用請(qǐng)看JsonTest類(lèi)
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>activemq.apache</groupId>
<artifactId>graduation03</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- webSocket -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- MySql 5.5 Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!-- config -->
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
</dependency>
<dependency>
<groupId>com.github.racc</groupId>
<artifactId>typesafeconfig-guice</artifactId>
</dependency>
<dependency>
<groupId>org.fusesource.stompjms</groupId>
<artifactId>stompjms-client</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>// 輸出到界面
System.out.println(json);
resp.setContentType("text/plain");
resp.setCharacterEncoding("gb2312");
PrintWriter out = new PrintWriter(resp.getOutputStream());
out.print(json);
out.flush();
改成response.getWriter.wirter(yourVariable); // 這樣前端訪問(wèn)你的servelt不就可以獲取到你的yourVaribale了嗎,接下來(lái)的就是前端多json 對(duì)象的解析了推薦我們開(kāi)發(fā)的Dgate,支持mock功能,目前只支持返回json格式,使用groovy DSL語(yǔ)法產(chǎn)生配置,只需簡(jiǎn)單幾下就可以生成一個(gè)mock的json給客戶端使用,如果你懂一些groovy會(huì)用的更順手。
撇開(kāi)各種框架不談,單單使用JSP+Servlet可以這么做:
1.新建一個(gè)JSP頁(yè)面,專(zhuān)門(mén)用于承載你返回的JSON數(shù)據(jù),類(lèi)似下面這樣:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
${json}
2.相關(guān)的Servlet執(zhí)行完畢之后,可以在response中設(shè)置一個(gè)名為json的屬性,屬性值就是你要返回的json格式數(shù)據(jù),完了將請(qǐng)求轉(zhuǎn)發(fā)到第一步的JSP頁(yè)面;
樓上有人提到了 SpringBoot,我這里就拋磚引玉,寫(xiě)個(gè) demo 給題主。
<!-- 基于 SpringBoot 1.5.9 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- 添加 Web 依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok 支持 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<!-- 添加構(gòu)建工具 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
假設(shè)需要定義的項(xiàng)目的目錄結(jié)構(gòu)如下:
src
`-- main
`-- java
`-- com.example
|-- dto
| `-- News.java
|-- controller
| `-- NewsEndpoint.java
`-- application
`-- Application.java
需要用 JSON 傳給前端的 News 對(duì)象定義如下:
@Getter
@Setter
@ToString
public class News implements Serializable {
/**
* 新聞主鍵
*/
private int nid;
/**
* 新聞標(biāo)題
*/
private String newsTitle;
/**
* 新聞內(nèi)容
*/
private String newsContent;
/**
* 新聞日期
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
private Date newsDate;
public News(int nid, String newsTitle, String newsContent, Date newsDate) {
this.nid = nid;
this.newsTitle = newsTitle;
this.newsContent = newsContent;
this.newsDate = newsDate;
}
}
@RestController
public class NewsEndpoint {
@GetMapping("/news")
public List<News> getNewsList() {
List<News> newsList = new ArrayList<>(3);
News news1 = new News(1, "title1", "content1", new Date());
News news2 = new News(2, "title2", "content2", new Date());
News news3 = new News(3, "title3", "content3", new Date());
newsList.add(news1);
newsList.add(news2);
newsList.add(news3);
return newsList;
}
}
@SpringBootApplication(scanBasePackages = "com.example")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
到這里,一個(gè)簡(jiǎn)單的返回 JSON 格式的 Endpoint 已經(jīng)寫(xiě)好了。默認(rèn)情況下,啟動(dòng)該項(xiàng)目(運(yùn)行 Application.class),前端通過(guò)調(diào)用 http://<你的主機(jī)ip地址>:8080/news 可以獲得如下返回結(jié)果:
北大青鳥(niǎo)APTECH成立于1999年。依托北京大學(xué)優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國(guó)IT技能型緊缺人才,是大數(shù)據(jù)專(zhuān)業(yè)的國(guó)家
達(dá)內(nèi)教育集團(tuán)成立于2002年,是一家由留學(xué)海歸創(chuàng)辦的高端職業(yè)教育培訓(xùn)機(jī)構(gòu),是中國(guó)一站式人才培養(yǎng)平臺(tái)、一站式人才輸送平臺(tái)。2014年4月3日在美國(guó)成功上市,融資1
北大課工場(chǎng)是北京大學(xué)校辦產(chǎn)業(yè)為響應(yīng)國(guó)家深化產(chǎn)教融合/校企合作的政策,積極推進(jìn)“中國(guó)制造2025”,實(shí)現(xiàn)中華民族偉大復(fù)興的升級(jí)產(chǎn)業(yè)鏈。利用北京大學(xué)優(yōu)質(zhì)教育資源及背
博為峰,中國(guó)職業(yè)人才培訓(xùn)領(lǐng)域的先行者
曾工作于聯(lián)想擔(dān)任系統(tǒng)開(kāi)發(fā)工程師,曾在博彥科技股份有限公司擔(dān)任項(xiàng)目經(jīng)理從事移動(dòng)互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍(lán)懿科技有限責(zé)任公司從事總經(jīng)理職務(wù)負(fù)責(zé)iOS教學(xué)及管理工作。
浪潮集團(tuán)項(xiàng)目經(jīng)理。精通Java與.NET 技術(shù), 熟練的跨平臺(tái)面向?qū)ο箝_(kāi)發(fā)經(jīng)驗(yàn),技術(shù)功底深厚。 授課風(fēng)格 授課風(fēng)格清新自然、條理清晰、主次分明、重點(diǎn)難點(diǎn)突出、引人入勝。
精通HTML5和CSS3;Javascript及主流js庫(kù),具有快速界面開(kāi)發(fā)的能力,對(duì)瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁(yè)制作和網(wǎng)頁(yè)游戲開(kāi)發(fā)。
具有10 年的Java 企業(yè)應(yīng)用開(kāi)發(fā)經(jīng)驗(yàn)。曾經(jīng)歷任德國(guó)Software AG 技術(shù)顧問(wèn),美國(guó)Dachieve 系統(tǒng)架構(gòu)師,美國(guó)AngelEngineers Inc. 系統(tǒng)架構(gòu)師。