JSP显示新闻

Posted jilan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSP显示新闻相关的知识,希望对你有一定的参考价值。

实现效果:

 

 

 

 实现步骤:

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

 

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

 


 

以上是关于JSP显示新闻的主要内容,如果未能解决你的问题,请参考以下文章

JSP显示新闻

JSP显示新闻

JSP显示新闻

JSP显示新闻

JSP显示新闻

JSP显示新闻