实现效果:
实现步骤:
创建表News并插入数据
导入新闻模板
新建NewsService,提供News类的数据服务
package Service; import Controller.DatabaseOperation; import Entity.News; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; //提供News类的数据服务 public class NewsService { public void AddNews(){} public void DeleteNews(){} public void UpdateNews(){} public List<News> QueryNews() throws SQLException { String sql="Select * from news"; DatabaseOperation operation=new DatabaseOperation(); ResultSet rs= operation.executeQuery(sql); List<News> lsNews=new ArrayList<News>(); while (rs.next()) { News news=new News(); news.setIdnews(rs.getInt(1)); news.setCategory(rs.getString(2)); news.setTitle(rs.getString(3)); news.setContent(rs.getString(4)); news.setAuthor(rs.getString(5)); news.setNewsdate(rs.getDate(6)); lsNews.add(news); } return lsNews; } public void GetNews(){} }
新建ShowNewsListServlet.java,从NewsService中获取所需的数据,并将数据传递给ShowNewsList.jsp来显示
@WebServlet(name = "Controller.ShowNewsListServlet") public class ShowNewsListServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); NewsService newsService=new NewsService(); try { List<News> lsNews=newsService.QueryNews(); request.setAttribute("lsNews",lsNews); request.getRequestDispatcher("ShowNewsList.jsp").forward(request,response); } catch (SQLException e) { e.printStackTrace(); } } }
配置web.xml文件
调整模板的内容,将后台主界面index.html中的herf改为ShowNewsListServlet,用以通过Servlet来实现网页信息的动态展示