jsp显示新闻列表

码云地址:https://gitee.com/xmr123/JAVAEE/tree/feature-JSP/ 

实现步骤:

1.创建表News并插入数据

 

 

 2.导入新闻模板

 

 3.新建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 QueryNews() throws SQLException {
        String sql="Select * from news";
        DatabaseOperation operation=new DatabaseOperation();
        ResultSet rs= operation.executeQuery(sql);
        List lsNews=new ArrayList();
        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(){}

}
复制代码

4.新建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 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来实现网页信息的动态展示

实现效果:

 

 

你可能感兴趣的:(jsp显示新闻列表)