实现效果图:
分层架构图:
关键代码:控制台输出新闻内容
实现类:
package cn.news.impl;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import org.junit.Test;import cn.news.dao.BaseDao;import cn.news.dao.NewsDetailDao;import cn.news.entity.NewsDetail;public class NewsDetailDaoImpl extends BaseDao implements NewsDetailDao{ @Test public void test() throws Exception { Listlist=getAllNews(); for (NewsDetail item : list) { System.out.println(item.getNewsContent()); } } @Override public List getAllNews() throws Exception { List list=new ArrayList (); String sql="select * from newsDetails"; ResultSet rs=executeQuery(sql); if(rs!=null) { while(rs.next()) { NewsDetail news=new NewsDetail(); news.setNewsId(rs.getInt("newsId")); news.setNewsTitle(rs.getString("newsTitle")); news.setNewsContent(rs.getString("newsContent")); news.setNewsCreateDate(rs.getDate("newsCreateDate")); news.setNewsAuthor(rs.getString("newsAuthor")); news.setNewsCategoryId(rs.getInt("newsCategoryId")); list.add(news); } } return list; }}
页面显示新闻标题以及时间:
新增NewsServlet类继承HttpServlet。关键代码:
package cn.news.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.news.entity.NewsDetail;import cn.news.impl.NewsDetailDaoImpl;public class NewsServlet extends HttpServlet { /** */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //实例化dao NewsDetailDaoImpl dao=new NewsDetailDaoImpl(); try { Listlist=dao.getAllNews(); request.setAttribute("list", list); } catch (Exception e) { e.printStackTrace(); } request.getRequestDispatcher("/index.jsp").forward(request, response); }}
index.jsp
- <% List
- <%=item.getNewsTitle() %><%=item.getNewsCreateDate() %> <% } %>
web.xml