为什么会报500错误呢?
相关代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/axios.js"></script>
</head>
<body>
<div id="container"></div>
<script>
// axios.get("/news", {params: {"t": "pypl"}}).then((response) => {
// console.log(response)
// var newsList = response.data
// for (let i = 0; i < newsList.length; i++) {
// var news = newsList[i]
// let container = document.getElementById("container");
// container.innerHTML = container.innerHTML + "<h1>" + news.title + "</h1>"
// }
// }).catch((error) => {
// console.log(error)
// })
// const params = new URLSearchParams()
// params.append("t", "pypl")
// params.append("t", "abc")
// axios.post("/news", params)
axios.post("/news", "t=pypl&l=abc",
{headers: {"content-type": "application/x-www-form-urlencoded"}})
.then((response) => {
console.respnose
var newsList = response.data
for (let i = 0; i < newsList.length; i++) {
var news = newsList[i]
let container = document.getElementById("container");
container.innerHTML = container.innerHTML + "<h1>" + news.title + "</h1>"
}
})
.catch((error) => {
console.log(error)
});
</script>
</body>
</html>
相关代码:
package com.imooc.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.entity.News;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/news")
public class NewsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String t = request.getParameter("t");
List<News> list = new ArrayList<>();
if (t.equals("tiobe")) {
list.add(new News("TIOBE:2018年编程语言排行趋势", "2018-5-1", "TIOBE", "..."));
list.add(new News("TIOBE:2019年编程语言排行趋势", "2019-5-1", "TIOBE", "..."));
list.add(new News("TIOBE:2020年编程语言排行趋势", "2020-5-1", "TIOBE", "..."));
list.add(new News("TIOBE:2021年编程语言排行趋势", "2021-5-1", "TIOBE", "..."));
} else if(t.equals("pypl")){
list.add(new News("PYPL:2018年编程语言排行趋势", "2018-5-1", "PYPL", "..."));
list.add(new News("PYPL:2019年编程语言排行趋势", "2019-5-1", "PYPL", "..."));
list.add(new News("PYPL:2020年编程语言排行趋势", "2020-5-1", "PYPL", "..."));
list.add(new News("PYPL:2021年编程语言排行趋势", "2021-5-1", "PYPL", "..."));
}
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(list);
response.setContentType("text/json;charset=UTF-8");
response.getWriter().println(json);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
问题描述:
我按照视频里面老师的方法,写了post,结果报了空指针异常的错误
相关截图:
16
收起
正在回答
1回答
同学你好,代码经过测试可以正确运行,建议清除浏览器缓存,再清除IDEA缓存,重启tomcat后再测试运行试下。
代码测试运行结果图如下:
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星