java - Servlet 使用 html 文件和 XMLHttpRequest 来显示数据
问题描述
我创建了一个 AJAX 端点,它将提供带有 JSON 文章数组的前端 AJAX 请求。我需要在 HTML 文件中显示数据的帮助。Article 类用于可以表示来自文章数据的信息的 Article 对象。在 ArticleListGenerator 类中,我有一个名为 getArticleList() 的静态方法,它将返回文章列表。getArticleList() 方法访问用于生成 JSON 的 JSON 文件。在我的 JSONResponse 类中,我有一个静态方法,它接受一个响应对象和一个实现 JSONAware 接口的对象作为参数。Endpoint 类是我的 doGet 方法。接下来我要做的是在 HTML 页面上显示数据。
在 Html 文件中,我有一个 javascript,我正在使用 XMLHttpRequest 从端点获取 JSON 数据,servlet 类“端点”我不确定这是否是正确的方法。
在我的 HTML 文件中,我尝试了 javascript
<script>
var url="/endpoint";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (!xhttp) {
console.log('Unable to create XMLHTTP instance');
return false;
}else if(xhttp.readyState == 4 &&xhttp.status===200) {
data = JSON.parse(xhttp.responseText);
console.log(" test:"+data);
}else{
console.log("page not found")
}
};
xhttp.open("GET", "url", true);
xhttp.send();
</script>
我的 web.xml 文件
<servlet>
<servlet-name>Endpoint</servlet-name>
<servlet-class>Test.web.Endpoint</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Endpoint</servlet-name>
<url-pattern>/endpoint</url-pattern>
</servlet-mapping>
public class Article implements Serializable {
private int id;
private String title;
private String content;
private int authorId;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getAuthorId() {
return this.authorId;
}
public void setAuthorId(int authorId) {
this.authorId = authorId;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public static JSONObject toJson(Article a) {
JSONObject jObj = new JSONObject();
if (a != null) {
jObj.put("id", a.getId());
jObj.put("title", JSONObject.escape(a.getTitle()));
jObj.put("content", JSONObject.escape(a.getContent()));
jObj.put("author_id", a.getAuthorId());
}
return jObj;
}
}
public class ArticleListGenerator {
public static List<Article> getArticleList(){
List<Article> articles = new ArrayList<>();
try (InputStreamReader inputStreamReader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("JSONArray.json"))) {
Object obj = new JSONParser().parse(inputStreamReader);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Article article = new Article();
String title = (String) jsonObject.get("title");
Long id = (Long) jsonObject.get("id");
Long authorId = (Long) jsonObject.get("author_id");
String content = (String) jsonObject.get("content");
article.setTitle(title);
article.setId(id.intValue());
article.setAuthorId(authorId.intValue());
article.setContent(content);
articles.add(article);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return articles;
}
}
public class JSONResponse {
public static void send(HttpServletResponse response, JSONAware j) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().print(j.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Endpoint extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Article> article=ArticleListGenerator.getArticleList();
JSONArray jArr = new JSONArray();
for(int i=0; i<article.size();i++){
jArr.add(Article.toJson(article.get(i)));
}
JSONResponse.send(resp, jArr);
}
}
解决方案
推荐阅读
- java - Spring数据jpa集合不更新
- python - django 使用了错误的 django 版本,尽管我使用 pipenv 安装了特定版本
- php - 使用带有 try and catch 的 Symfony HTTP 客户端
- laravel - 登录 Lumen 7.0 和 JWT 时如何检查用户状态
- arrays - Google 表格中的外部联接
- nginx - 区分大小写/不区分大小写的匹配在 nginx 中不起作用
- javascript - Vuex:如何从服务脚本文件状态更改存储状态未定义
- download - setText() 仅在命令之后而不是之前有效
- python - Django - 视图中的多个权限
- django - 即使方法成功,Django POST 请求也总是返回 400