本部分内容:实现博客列表页;web程序问题的分析方法;实现博客详情页;
该部分的代码如下:
java
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
//Jackson ObjectMapper类(com.fasterxml.jackson.databind.ObjectMapper)解析JSON工具
//
//序列化: Java对象生成Json
//
//反序列化: Json解析为Java对象
private ObjectMapper objectMapper=new ObjectMapper();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BlogDao blogDao=new BlogDao();
List<Blog> blogs =blogDao.getblogs();
String respJson=objectMapper.writeValueAsString(blogs);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(respJson);
}
上述过程中的一些疑问
这部分的运行效果图如下:
修改后的BlogServlet.java代码如下:
java
package api;
import Dao.Blog;
import Dao.BlogDao;
import com.fasterxml.jackson.databind.ObjectMapper;
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.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Home-pc
* Date: 2023-10-28
* Time: 16:56
*/
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
//Jackson ObjectMapper类(com.fasterxml.jackson.databind.ObjectMapper)解析JSON工具
//
//序列化: Java对象生成Json
//
//反序列化: Json解析为Java对象
private ObjectMapper objectMapper=new ObjectMapper();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BlogDao blogDao=new BlogDao();
//尝试获取blogId这个参数,根据是否能获取到这个参数,将其进行分支
String blogId=req.getParameter("blogId");
if(blogId==null){
//说明此处是需要获取博客列表
List<Blog> blogs =blogDao.getblogs();
String respJson=objectMapper.writeValueAsString(blogs);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(respJson);
}else{
//说明此处要获得某篇博客的详情页 获取一篇博客
Blog blog=blogDao.getblog(Integer.parseInt(blogId));
//如果该篇博客不存在,那么此时的blog==null
if(blog==null){
blog=new Blog();
}
String respJson=objectMapper.writeValueAsString(blog);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(respJson);
}
}
}